nus-yam/ex-repair huggingface dataset:
Program: CWE-352
Project: CVE-2017-9365
Buggy source:
<?
	$bigtree["current_page"] = $page;
	$bigtree["resources"] = $page["resources"];
	
	// Show the properties section
	include BigTree::path("admin/modules/pages/_properties.php");
	
	// Check for a page lock
	$force = isset($_GET["force"]) ? $_GET["force"] : false;
	$admin->lockCheck("bigtree_pages",$page["id"],"admin/modules/pages/_locked.php",$force);
	
	// Grab template information
	$template_data = $cms->getTemplate($page["template"]);

	// Audit Trail link
	$bigtree["subnav_extras"][] = array("link" => ADMIN_ROOT."developer/audit/search/?table=bigtree_pages&entry=".$page["id"],"icon" => "trail","title" => "View Audit Trail");		

	// Provide developers a nice handy link for edit/return of this form
	if ($admin->Level > 1) {
		$bigtree["subnav_extras"][] = array("link" => ADMIN_ROOT."developer/templates/edit/".$page["template"]."/?return=".$page["id"],"icon" => "setup","title" => "Edit Current Template in Developer");
	}
	
	$bigtree["form_action"] = "update";
	include BigTree::path("admin/modules/pages/_form.php");
?>

Fixed version (ground truth):
<?
	$bigtree["current_page"] = $page;
	$bigtree["resources"] = $page["resources"];
	
	// Show the properties section
	include BigTree::path("admin/modules/pages/_properties.php");
	
	// Check for a page lock
	if (!empty($_GET["force"])) {
		$admin->verifyCSRFToken();
		$force = true;
	} else {
		$force = false;
	}
	
	$admin->lockCheck("bigtree_pages",$page["id"],"admin/modules/pages/_locked.php",$force);
	
	// Grab template information
	$template_data = $cms->getTemplate($page["template"]);

	// Audit Trail link
	$bigtree["subnav_extras"][] = array("link" => ADMIN_ROOT."developer/audit/search/?table=bigtree_pages&entry=".$page["id"],"icon" => "trail","title" => "View Audit Trail");		

	// Provide developers a nice handy link for edit/return of this form
	if ($admin->Level > 1) {
		$bigtree["subnav_extras"][] = array("link" => ADMIN_ROOT."developer/templates/edit/".$page["template"]."/?return=".$page["id"],"icon" => "setup","title" => "Edit Current Template in Developer");
	}
	
	$bigtree["form_action"] = "update";
	include BigTree::path("admin/modules/pages/_form.php");
?>
Program: CWE-352
Project: CVE-2018-6656
Buggy source:
<?php
require '../../../zb_system/function/c_system_base.php';

require '../../../zb_system/function/c_system_admin.php';

require dirname(__FILE__) . '/function.php';

$zbp->Load();

$action = 'root';
if (!$zbp->CheckRights($action)) {$zbp->ShowError(6);die();}

if (!$zbp->CheckPlugin('AppCentre')) {$zbp->ShowError(48);die();}

$type = $_GET['type'];

$id = $_GET['id'];

$app = new App;

if (!$app->LoadInfoByXml($type, $id)) {
	exit;
}

ob_clean();

if (
	function_exists('gzencode') &&
	$zbp->Config('AppCentre')->enablegzipapp &&
	$app->adapted > 140614// 1.3和之前版本不打包为gzba
) {
	header('Content-Disposition:attachment;filename=' . $id . '.gzba');
	echo AppCentre_Pack($app, true);
} else {
	header('Content-Disposition:attachment;filename=' . $id . '.zba');
	echo AppCentre_Pack($app, false);
}

Fixed version (ground truth):
None
Program: CWE-352
Project: CVE-2018-7634
Buggy source:
<?php
require '../../../zb_system/function/c_system_base.php';

require '../../../zb_system/function/c_system_admin.php';

require dirname(__FILE__) . '/function.php';

$zbp->Load();

$action = 'root';
if (!$zbp->CheckRights($action)) {$zbp->ShowError(6);die();}

if (!$zbp->CheckPlugin('AppCentre')) {$zbp->ShowError(48);die();}

$type = $_GET['type'];

$id = $_GET['id'];

$app = new App;

if (!$app->LoadInfoByXml($type, $id)) {
	exit;
}

ob_clean();

if (
	function_exists('gzencode') &&
	$zbp->Config('AppCentre')->enablegzipapp &&
	$app->adapted > 140614// 1.3和之前版本不打包为gzba
) {
	header('Content-Disposition:attachment;filename=' . $id . '.gzba');
	echo AppCentre_Pack($app, true);
} else {
	header('Content-Disposition:attachment;filename=' . $id . '.zba');
	echo AppCentre_Pack($app, false);
}

Fixed version (ground truth):
None
Program: CWE-352
Project: CVE-2019-15150
Buggy source:
{
	"name": "MW-OAuth2Client",
	"version": "0.3",
	"author": [
		"[http://dekeijzer.org Joost de Keijzer]",
		"[https://www.mediawiki.org/wiki/User:Nischayn22 Nischay Nahata]",
		"[https://star-made.org Schine GmbH]"
	],
	"url": "https://www.mediawiki.org/wiki/Extension:OAuth2_Client",
	"descriptionmsg": "oauth2client-act-as-a-client-to-any-oauth2-server",
	"license-name": "LGPL-3.0",
	"type": "other",
	"AutoloadClasses": {
		"OAuth2ClientHooks": "OAuth2Client.php",
		"SpecialOAuth2Client": "SpecialOAuth2Client.php"
	},
	"ExtensionMessagesFiles": {
		"OAuth2ClientAlias": "OAuth2Client.alias.php"
	},
	"Hooks": {
		"PersonalUrls": [
			"OAuth2ClientHooks::onPersonalUrls"
		]
	},
	"SpecialPages": {
		"OAuth2Client": "SpecialOAuth2Client"
	},
	"MessagesDirs": {
		"MyExtension": [
			"i18n"
		]
	},
	"manifest_version": 1
}


Fixed version (ground truth):
{
	"name": "MW-OAuth2Client",
	"version": "0.4",
	"author": [
		"[http://dekeijzer.org Joost de Keijzer]",
		"[https://www.mediawiki.org/wiki/User:Nischayn22 Nischay Nahata]",
		"[https://star-made.org Schine GmbH]"
	],
	"url": "https://www.mediawiki.org/wiki/Extension:OAuth2_Client",
	"descriptionmsg": "oauth2client-act-as-a-client-to-any-oauth2-server",
	"license-name": "LGPL-3.0",
	"type": "other",
	"AutoloadClasses": {
		"OAuth2ClientHooks": "OAuth2Client.php",
		"SpecialOAuth2Client": "SpecialOAuth2Client.php"
	},
	"ExtensionMessagesFiles": {
		"OAuth2ClientAlias": "OAuth2Client.alias.php"
	},
	"Hooks": {
		"PersonalUrls": [
			"OAuth2ClientHooks::onPersonalUrls"
		]
	},
	"SpecialPages": {
		"OAuth2Client": "SpecialOAuth2Client"
	},
	"MessagesDirs": {
		"MyExtension": [
			"i18n"
		]
	},
	"manifest_version": 1
}
Program: CWE-352
Project: CVE-2019-17675
Buggy source:
<?php
/**
 * WordPress Version
 *
 * Contains version information for the current WordPress release.
 *
 * @package WordPress
 * @since 1.1.0
 */

/**
 * The WordPress version string
 *
 * @global string $wp_version
 */
$wp_version = '5.3-beta3-46476';

/**
 * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.
 *
 * @global int $wp_db_version
 */
$wp_db_version = 45805;

/**
 * Holds the TinyMCE version
 *
 * @global string $tinymce_version
 */
$tinymce_version = '4960-20190918';

/**
 * Holds the required PHP version
 *
 * @global string $required_php_version
 */
$required_php_version = '5.6.20';

/**
 * Holds the required MySQL version
 *
 * @global string $required_mysql_version
 */
$required_mysql_version = '5.0';


Fixed version (ground truth):
<?php
/**
 * WordPress Version
 *
 * Contains version information for the current WordPress release.
 *
 * @package WordPress
 * @since 1.1.0
 */

/**
 * The WordPress version string
 *
 * @global string $wp_version
 */
$wp_version = '5.3-beta3-46477';

/**
 * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.
 *
 * @global int $wp_db_version
 */
$wp_db_version = 45805;

/**
 * Holds the TinyMCE version
 *
 * @global string $tinymce_version
 */
$tinymce_version = '4960-20190918';

/**
 * Holds the required PHP version
 *
 * @global string $required_php_version
 */
$required_php_version = '5.6.20';

/**
 * Holds the required MySQL version
 *
 * @global string $required_mysql_version
 */
$required_mysql_version = '5.0';
Program: CWE-352
Project: CVE-2021-29435
Buggy source:
module Trestle
  module Auth
    module Controller
      module Authentication
        extend ActiveSupport::Concern

        included do
          helper_method :current_user, :logged_in?, :authentication_scope

          prepend_before_action :require_authenticated_user
          prepend_before_action :authenticate_user
        end

      protected
        def authentication_backend
          @_authentication_backend ||= Trestle.config.auth.backend.new(controller: self, request: request, session: session, cookies: cookies)
        end

        def current_user
          authentication_backend.user
        end

        def logged_in?
          authentication_backend.logged_in?
        end

        def authenticate_user
          authentication_backend.authenticate
        end

        def require_authenticated_user
          logged_in? || login_required!
        end

        def login!(user)
          authentication_backend.login!(user)
        end

        def logout!
          authentication_backend.logout!
        end

        def login_required!
          authentication_backend.store_location(request.fullpath)
          redirect_to instance_exec(&Trestle.config.auth.login_url)
          false
        end

        def authentication_scope
          authentication_backend.scope
        end
      end
    end
  end
end


Fixed version (ground truth):
module Trestle
  module Auth
    module Controller
      module Authentication
        extend ActiveSupport::Concern

        included do
          helper_method :current_user, :logged_in?, :authentication_scope

          prepend_before_action :require_authenticated_user
          prepend_before_action :authenticate_user

          # Ensure that CSRF protection happens before authentication
          protect_from_forgery prepend: true
        end

      protected
        def authentication_backend
          @_authentication_backend ||= Trestle.config.auth.backend.new(controller: self, request: request, session: session, cookies: cookies)
        end

        def current_user
          authentication_backend.user
        end

        def logged_in?
          authentication_backend.logged_in?
        end

        def authenticate_user
          authentication_backend.authenticate
        end

        def require_authenticated_user
          logged_in? || login_required!
        end

        def login!(user)
          authentication_backend.login!(user)
        end

        def logout!
          authentication_backend.logout!
        end

        def login_required!
          authentication_backend.store_location(request.fullpath)
          redirect_to instance_exec(&Trestle.config.auth.login_url)
          false
        end

        def authentication_scope
          authentication_backend.scope
        end
      end
    end
  end
end
Program: CWE-352
Project: CVE-2021-32677
Buggy source:
import gzip
import json

import pytest
from fastapi import Request
from fastapi.testclient import TestClient

from docs_src.custom_request_and_route.tutorial001 import app


@app.get("/check-class")
async def check_gzip_request(request: Request):
    return {"request_class": type(request).__name__}


client = TestClient(app)


@pytest.mark.parametrize("compress", [True, False])
def test_gzip_request(compress):
    n = 1000
    headers = {}
    body = [1] * n
    data = json.dumps(body).encode()
    if compress:
        data = gzip.compress(data)
        headers["Content-Encoding"] = "gzip"
    response = client.post("/sum", data=data, headers=headers)
    assert response.json() == {"sum": n}


def test_request_class():
    response = client.get("/check-class")
    assert response.json() == {"request_class": "GzipRequest"}


Fixed version (ground truth):
import gzip
import json

import pytest
from fastapi import Request
from fastapi.testclient import TestClient

from docs_src.custom_request_and_route.tutorial001 import app


@app.get("/check-class")
async def check_gzip_request(request: Request):
    return {"request_class": type(request).__name__}


client = TestClient(app)


@pytest.mark.parametrize("compress", [True, False])
def test_gzip_request(compress):
    n = 1000
    headers = {}
    body = [1] * n
    data = json.dumps(body).encode()
    if compress:
        data = gzip.compress(data)
        headers["Content-Encoding"] = "gzip"
    headers["Content-Type"] = "application/json"
    response = client.post("/sum", data=data, headers=headers)
    assert response.json() == {"sum": n}


def test_request_class():
    response = client.get("/check-class")
    assert response.json() == {"request_class": "GzipRequest"}
Program: CWE-352
Project: CVE-2021-3931
Buggy source:
<?php
/*
* Custom Fields Routes
*/



Route::group([ 'prefix' => 'fields','middleware' => ['auth'] ], function () {

    Route::get('required/{fieldset_id}/{field_id}',
        ['uses' => 'CustomFieldsetsController@makeFieldRequired',
            'as' => 'fields.required']
    );

    Route::get('optional/{fieldset_id}/{field_id}',
        ['uses' => 'CustomFieldsetsController@makeFieldOptional',
            'as' => 'fields.optional']
    );

    Route::get('{field_id}/fieldset/{fieldset_id}/disassociate',
        ['uses' => 'CustomFieldsController@deleteFieldFromFieldset',
        'as' => 'fields.disassociate']
    );

    Route::post('fieldsets/{id}/associate',
        ['uses' => 'CustomFieldsetsController@associate',
        'as' => 'fieldsets.associate']
    );

    Route::resource('fieldsets', 'CustomFieldsetsController', [
    'parameters' => ['fieldset' => 'field_id', 'field' => 'field_id']
    ]);


});

Route::resource('fields', 'CustomFieldsController', [
    'middleware' => ['auth'],
    'parameters' => ['field' => 'field_id', 'fieldset' => 'fieldset_id']
]);


Fixed version (ground truth):
<?php
/*
* Custom Fields Routes
*/



Route::group([ 'prefix' => 'fields','middleware' => ['auth'] ], function () {

    Route::post('required/{fieldset_id}/{field_id}',
        ['uses' => 'CustomFieldsetsController@makeFieldRequired',
            'as' => 'fields.required']
    );

    Route::post('optional/{fieldset_id}/{field_id}',
        ['uses' => 'CustomFieldsetsController@makeFieldOptional',
            'as' => 'fields.optional']
    );

    Route::post('{field_id}/fieldset/{fieldset_id}/disassociate',
        ['uses' => 'CustomFieldsController@deleteFieldFromFieldset',
        'as' => 'fields.disassociate']
    );

    Route::post('fieldsets/{id}/associate',
        ['uses' => 'CustomFieldsetsController@associate',
        'as' => 'fieldsets.associate']
    );

    Route::resource('fieldsets', 'CustomFieldsetsController', [
    'parameters' => ['fieldset' => 'field_id', 'field' => 'field_id']
    ]);


});

Route::resource('fields', 'CustomFieldsController', [
    'middleware' => ['auth'],
    'parameters' => ['field' => 'field_id', 'fieldset' => 'fieldset_id']
]);
Program: CWE-352
Project: CVE-2021-3932
Buggy source:
None

Fixed version (ground truth):
// POST logout action

const logoutButton = function () {
  const logoutForm = document.querySelector('[data-logout-form]')

  if (!logoutForm) return

  document.body.addEventListener('click', e => {
    if (e.target.hasAttribute('data-logout-btn')) {
      e.preventDefault()
      logoutForm.submit()
    }
  })
}

export default logoutButton
Program: CWE-352
Project: CVE-2021-3993
Buggy source:
<?php

// 当php版本达到composer包要求的版本时候，则require autoload
// vendor/composer/platform_check.php 里面可以看到composer包要求的最低版本
define('COMPOSER_PHP_VERSION', '7.2.5' );
if(version_compare(PHP_VERSION,COMPOSER_PHP_VERSION,'>')){
    // 增加自动加载
    require './vendor/autoload.php';
}

// 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false
define('APP_DEBUG',True);

// 定义应用目录
define('APP_PATH','./Application/');

// 引入ThinkPHP入口文件
require './ThinkPHP/ThinkPHP.php';

Fixed version (ground truth):
<?php

// 当php版本达到composer包要求的版本时候，则require autoload
// vendor/composer/platform_check.php 里面可以看到composer包要求的最低版本
define('COMPOSER_PHP_VERSION', '7.2.5' );
if(version_compare(PHP_VERSION,COMPOSER_PHP_VERSION,'>')){
    // 增加自动加载
    require './vendor/autoload.php';
}

// cookie安全，给PHPSESSID加上Strict
if (PHP_VERSION_ID >= 70300) {
    session_set_cookie_params([
        'samesite' => 'Strict'
    ]);
} else { 
    session_set_cookie_params(
        NULL,
        '/; samesite=Strict',
    );
}

// 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false
define('APP_DEBUG',True);

// 定义应用目录
define('APP_PATH','./Application/');

// 引入ThinkPHP入口文件
require './ThinkPHP/ThinkPHP.php';
Program: CWE-352
Project: CVE-2021-4017
Buggy source:
<?php

// 当php版本达到composer包要求的版本时候，则require autoload
// vendor/composer/platform_check.php 里面可以看到composer包要求的最低版本
define('COMPOSER_PHP_VERSION', '7.2.5' );
if(version_compare(PHP_VERSION,COMPOSER_PHP_VERSION,'>')){
    // 增加自动加载
    require './vendor/autoload.php';
}

// 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false
define('APP_DEBUG',True);

// 定义应用目录
define('APP_PATH','./Application/');

// 引入ThinkPHP入口文件
require './ThinkPHP/ThinkPHP.php';

Fixed version (ground truth):
<?php

// 当php版本达到composer包要求的版本时候，则require autoload
// vendor/composer/platform_check.php 里面可以看到composer包要求的最低版本
define('COMPOSER_PHP_VERSION', '7.2.5' );
if(version_compare(PHP_VERSION,COMPOSER_PHP_VERSION,'>')){
    // 增加自动加载
    require './vendor/autoload.php';
}

// cookie安全，给PHPSESSID加上Strict
if (PHP_VERSION_ID >= 70300) {
    session_set_cookie_params([
        'samesite' => 'Strict'
    ]);
} else { 
    session_set_cookie_params(
        NULL,
        '/; samesite=Strict',
    );
}

// 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false
define('APP_DEBUG',True);

// 定义应用目录
define('APP_PATH','./Application/');

// 引入ThinkPHP入口文件
require './ThinkPHP/ThinkPHP.php';
Program: CWE-352
Project: CVE-2021-4049
Buggy source:
<?php

header('X-Frame-Options: DENY');

$lhUser = erLhcoreClassUser::instance();

erLhcoreClassChatEventDispatcher::getInstance()->dispatch('user.logout',array('user' => & $lhUser));

$lhUser->logout();

erLhcoreClassChatEventDispatcher::getInstance()->dispatch('user.after_logout',array('user' => & $lhUser));

erLhcoreClassModule::redirect('user/login');
exit;

?>

Fixed version (ground truth):
<?php

header('X-Frame-Options: DENY');

$lhUser = erLhcoreClassUser::instance();

if (!$lhUser->isLogged() || !$lhUser->validateCSFRToken($Params['user_parameters_unordered']['csfr'])) {
    die('Invalid CSFR Token');
    exit;
}

erLhcoreClassChatEventDispatcher::getInstance()->dispatch('user.logout',array('user' => & $lhUser));

$lhUser->logout();

erLhcoreClassChatEventDispatcher::getInstance()->dispatch('user.after_logout',array('user' => & $lhUser));

//erLhcoreClassModule::redirect('user/login');
exit;

?>
Program: CWE-352
Project: CVE-2021-4082
Buggy source:
{% extends '@PimcoreAdmin/Admin/Login/layout.html.twig' %}

{% block content %}
    {% if error is defined %}
        <div class="text error">
            {{ error|trans([],'admin')|raw }}
        </div>
    {% else %}
        <div class="text info">
            {{ 'Enter your verification code'|trans([],'admin') }}
        </div>
    {% endif %}

    <form method="post" action="{{ path('pimcore_admin_2fa-verify') }}">
        <input name="_auth_code" id="_auth_code" autocomplete="one-time-code" type="password" placeholder="{{ '2fa_code'|trans([],'admin') }}" required autofocus>
        <input type="hidden" name="csrfToken" value="{{ pimcore_csrf.getCsrfToken() }}">

        <button type="submit">{{ 'Login'|trans([],'admin') }}</button>
    </form>

    <a href="{{ path('pimcore_admin_logout') }}">{{ 'Back to Login'|trans([],'admin') }}</a>

    {{ pimcore_breach_attack_random_content() }}
{% endblock %}





Fixed version (ground truth):
{% extends '@PimcoreAdmin/Admin/Login/layout.html.twig' %}

{% block content %}
    {% if error is defined %}
        <div class="text error">
            {{ error|trans([],'admin')|raw }}
        </div>
    {% else %}
        <div class="text info">
            {{ 'Enter your verification code'|trans([],'admin') }}
        </div>
    {% endif %}

    <form method="post" action="{{ path('pimcore_admin_2fa-verify') }}">
        <input name="_auth_code" id="_auth_code" autocomplete="one-time-code" type="password" placeholder="{{ '2fa_code'|trans([],'admin') }}" required autofocus>
        <input type="hidden" name="csrfToken" value="{{ pimcore_csrf.getCsrfToken() }}">

        <button type="submit">{{ 'Login'|trans([],'admin') }}</button>
    </form>

    <form id="pimcore_logout_form" method="post" action="{{ path('pimcore_admin_logout') }}">
        <input type="hidden" name="csrfToken" value="{{ pimcore_csrf.getCsrfToken() }}">
        <a href="#" onclick="document.getElementById('pimcore_logout_form').submit();">{{ 'Back to Login'|trans([],'admin') }}</a>
    </form>



    {{ pimcore_breach_attack_random_content() }}
{% endblock %}
Program: CWE-352
Project: CVE-2021-4092
Buggy source:
{*<!--
/*********************************************************************************
** The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is:  vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*
********************************************************************************/
-->*}
{strip}
	<div class="mainContainer container">
		<div class="jumbotron mt-5">
			<div class="row">
				<div class="col-md-12 text-center">
					<h1><span class="far fa-times-circle u-fs-10x"></span></h1>
					<h2>{\App\Language::translate('LBL_NO_FOUND_VIEW')}</h2>
					<p class="my-5">
						<a class="btn btn-success mr-2" role="button" href="javascript:window.history.back();">
							<span class="fas fa-chevron-left mr-2"></span>{\App\Language::translate('LBL_GO_BACK')}
						</a>
						<a class="btn btn-warning mr-2" role="button" href="?module=Users&action=Logout">
							<span class="fas fa-power-off fa-fw mr-2"></span>{\App\Language::translate('LBL_SIGN_OUT')}
						</a>
						<a class="btn btn-primary" role="button" href="?module=Users&action=Logout">
							<i class="fas fa-home mr-2"></i>{\App\Language::translate('LBL_MAIN_PAGE')}
						</a>
					</p>
				</div>
			</div>
		</div>
	</div>
{/strip}


Fixed version (ground truth):
{*<!--
/*********************************************************************************
** The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is:  vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*
********************************************************************************/
-->*}
{strip}
	<div class="mainContainer container">
		<div class="jumbotron mt-5">
			<div class="row">
				<div class="col-md-12 text-center">
					<h1><span class="far fa-times-circle u-fs-10x"></span></h1>
					<h2>{\App\Language::translate('LBL_NO_FOUND_VIEW')}</h2>
					<p class="my-5">
						<a class="btn btn-success mr-2" role="button" href="javascript:window.history.back();">
							<span class="fas fa-chevron-left mr-2"></span>{\App\Language::translate('LBL_GO_BACK')}
						</a>
						<a class="btn btn-warning mr-2 js-post-action" role="button" href="index.php?module=Users&action=Logout">
							<span class="fas fa-power-off fa-fw mr-2"></span>{\App\Language::translate('LBL_SIGN_OUT')}
						</a>
						<a class="btn btn-primary" role="button" href="index.php">
							<i class="fas fa-home mr-2"></i>{\App\Language::translate('LBL_MAIN_PAGE')}
						</a>
					</p>
				</div>
			</div>
		</div>
	</div>
{/strip}
Program: CWE-352
Project: CVE-2021-41260
Buggy source:
{extends file='ajouter_contribution.tpl'}
{block name="content"}
    <div id="mass_contributions"{if $mode neq 'ajax'} class="center"{else} title="{$page_title}"{/if}>
    <form action="{$form_url}" method="post">
        {if $mode neq 'ajax'}<h2>{$page_title}</h2>{/if}
        <div class="button-container">
            {$smarty.block.parent}
            <input type="submit" id="masschange" class="button" value="{if !isset($changes)}{_T string="Edit"}{else}{_T string="OK"}{/if}"/>
            <a href="{$cancel_uri}" class="button" id="btncancel">{_T string="Cancel"}</a>
            <input type="hidden" name="confirm" value="1"/>
            {if $mode eq 'ajax'}<input type="hidden" name="ajax" value="true"/>{/if}
            {foreach $data as $key=>$value}
                {if is_array($value)}
                    {foreach $value as $val}
                <input type="hidden" name="{$key}[]" value="{$val}"/>
                    {/foreach}
                {else}
                <input type="hidden" name="{$key}" value="{$value}"/>
                {/if}
            {/foreach}
        </div>
    </form>
    </div>
{/block}


Fixed version (ground truth):
{extends file='ajouter_contribution.tpl'}
{block name="content"}
    <div id="mass_contributions"{if $mode neq 'ajax'} class="center"{else} title="{$page_title}"{/if}>
    <form action="{$form_url}" method="post">
        {if $mode neq 'ajax'}<h2>{$page_title}</h2>{/if}
        <div class="button-container">
            {$smarty.block.parent}
            <input type="submit" id="masschange" class="button" value="{if !isset($changes)}{_T string="Edit"}{else}{_T string="OK"}{/if}"/>
            <a href="{$cancel_uri}" class="button" id="btncancel">{_T string="Cancel"}</a>
            <input type="hidden" name="confirm" value="1"/>
            {if $mode eq 'ajax'}<input type="hidden" name="ajax" value="true"/>{/if}
            {foreach $data as $key=>$value}
                {if is_array($value)}
                    {foreach $value as $val}
                <input type="hidden" name="{$key}[]" value="{$val}"/>
                    {/foreach}
                {else}
                <input type="hidden" name="{$key}" value="{$value}"/>
                {/if}
            {/foreach}
            {include file="forms_types/csrf.tpl"}
        </div>
    </form>
    </div>
{/block}
Program: CWE-352
Project: CVE-2021-41273
Buggy source:
<?php

namespace Pterodactyl\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'remote/*',
        'daemon/*',
        'api/*',
    ];
}


Fixed version (ground truth):
<?php

namespace Pterodactyl\Http\Middleware;

use Closure;
use Pterodactyl\Models\ApiKey;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification. These are
     * never hit by the front-end, and require specific token validation
     * to work.
     *
     * @var string[]
     */
    protected $except = ['remote/*', 'daemon/*'];

    /**
     * Manually apply CSRF protection to routes depending on the authentication
     * mechanism being used. If the API request is using an API key that exists
     * in the database we can safely ignore CSRF protections, since that would be
     * a manually initiated request by a user or server.
     *
     * All other requests should go through the standard CSRF protections that
     * Laravel affords us. This code will be removed in v2 since we have switched
     * to using Sanctum for the API endpoints, which handles that for us automatically.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     *
     * @throws \Illuminate\Session\TokenMismatchException
     */
    public function handle($request, Closure $next)
    {
        $key = $request->attributes->get('api_key');

        if ($key instanceof ApiKey && $key->exists) {
            return $next($request);
        }

        return parent::handle($request, $next);
    }
}
Program: CWE-352
Project: CVE-2021-41274
Buggy source:
<?php

namespace Pterodactyl\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'remote/*',
        'daemon/*',
        'api/*',
    ];
}


Fixed version (ground truth):
<?php

namespace Pterodactyl\Http\Middleware;

use Closure;
use Pterodactyl\Models\ApiKey;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification. These are
     * never hit by the front-end, and require specific token validation
     * to work.
     *
     * @var string[]
     */
    protected $except = ['remote/*', 'daemon/*'];

    /**
     * Manually apply CSRF protection to routes depending on the authentication
     * mechanism being used. If the API request is using an API key that exists
     * in the database we can safely ignore CSRF protections, since that would be
     * a manually initiated request by a user or server.
     *
     * All other requests should go through the standard CSRF protections that
     * Laravel affords us. This code will be removed in v2 since we have switched
     * to using Sanctum for the API endpoints, which handles that for us automatically.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     *
     * @throws \Illuminate\Session\TokenMismatchException
     */
    public function handle($request, Closure $next)
    {
        $key = $request->attributes->get('api_key');

        if ($key instanceof ApiKey && $key->exists) {
            return $next($request);
        }

        return parent::handle($request, $next);
    }
}
Program: CWE-352
Project: CVE-2021-41275
Buggy source:
class Spree::UsersController < Spree::StoreController
  before_action :set_current_order, except: :show
  prepend_before_action :load_object, only: [:show, :edit, :update]
  prepend_before_action :authorize_actions, only: :new

  include Spree::Core::ControllerHelpers

  def show
    @orders = @user.orders.for_store(current_store).complete.order('completed_at desc')
  end

  def create
    @user = Spree.user_class.new(user_params)
    if @user.save

      if current_order
        session[:guest_token] = nil
      end

      redirect_back_or_default(root_url)
    else
      render :new
    end
  end

  def update
    if @user.update(user_params)
      if params[:user][:password].present?
        # this logic needed b/c devise wants to log us out after password changes
        Spree.user_class.reset_password_by_token(params[:user])
        if Spree::Auth::Config[:signout_after_password_change]
          sign_in(@user, event: :authentication)
        else
          bypass_sign_in(@user)
        end
      end
      redirect_to spree.account_path, notice: Spree.t(:account_updated)
    else
      render :edit
    end
  end

  private

  def user_params
    params.require(:user).permit(Spree::PermittedAttributes.user_attributes)
  end

  def load_object
    @user ||= spree_current_user
    authorize! params[:action].to_sym, @user
  end

  def authorize_actions
    authorize! params[:action].to_sym, Spree.user_class.new
  end

  def accurate_title
    Spree.t(:my_account)
  end
end


Fixed version (ground truth):
class Spree::UsersController < Spree::StoreController
  before_action :set_current_order, except: :show
  prepend_before_action :authorize_actions, only: :new

  include Spree::Core::ControllerHelpers

  def show
    load_object
    @orders = @user.orders.for_store(current_store).complete.order('completed_at desc')
  end

  def edit
    load_object
  end

  def create
    @user = Spree.user_class.new(user_params)
    if @user.save

      if current_order
        session[:guest_token] = nil
      end

      redirect_back_or_default(root_url)
    else
      render :new
    end
  end

  def update
    load_object
    if @user.update(user_params)
      if params[:user][:password].present?
        # this logic needed b/c devise wants to log us out after password changes
        Spree.user_class.reset_password_by_token(params[:user])
        if Spree::Auth::Config[:signout_after_password_change]
          sign_in(@user, event: :authentication)
        else
          bypass_sign_in(@user)
        end
      end
      redirect_to spree.account_path, notice: Spree.t(:account_updated)
    else
      render :edit
    end
  end

  private

  def user_params
    params.require(:user).permit(Spree::PermittedAttributes.user_attributes)
  end

  def load_object
    @user ||= spree_current_user
    authorize! params[:action].to_sym, @user
  end

  def authorize_actions
    authorize! params[:action].to_sym, Spree.user_class.new
  end

  def accurate_title
    Spree.t(:my_account)
  end
end
Program: CWE-352
Project: CVE-2021-4131
Buggy source:
<?php


$CacheManager = erConfigClassLhCacheConfig::getInstance();
$CacheManager->expireCache(true);
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;

?>

Fixed version (ground truth):
<?php

$currentUser = erLhcoreClassUser::instance();

if (!$currentUser->validateCSFRToken($Params['user_parameters_unordered']['csfr'])) {
    die('Invalid CSFR Token');
    exit;
}

$CacheManager = erConfigClassLhCacheConfig::getInstance();
$CacheManager->expireCache(true);
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;

?>
Program: CWE-352
Project: CVE-2022-0638
Buggy source:
<?php

namespace MicroweberPackages\User\Http\Controllers;

use App\Http\Resources\User\UserResource;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use MicroweberPackages\App\Http\Middleware\SameSiteRefererMiddleware;

class UserLogoutController extends Controller
{
    public $middleware = [
        [
            'middleware' => 'xss',
            'options' => []
        ]
    ];

    public function __construct()
    {
        event_trigger('mw.init');
    }

    /**
     * Display a listing of Role.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $ref = $request->headers->get('referer');

        $same_site = app()->make(SameSiteRefererMiddleware::class);
        $is_same_site = $same_site->isSameSite($ref);

        if ($is_same_site) {
            return logout();
        }

        return view('user::logout.index');
    }

    public function submit(Request $request)
    {
        return logout();
    }

}


Fixed version (ground truth):
<?php

namespace MicroweberPackages\User\Http\Controllers;

use App\Http\Resources\User\UserResource;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use MicroweberPackages\App\Http\Middleware\SameSiteRefererMiddleware;

class UserLogoutController extends Controller
{
    public $middleware = [
        [
            'middleware' => 'xss',
            'options' => []
        ]
    ];

    public function __construct()
    {
        event_trigger('mw.init');
    }

    /**
     * Display a listing of Role.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $ref = $request->headers->get('referer');

        $same_site = app()->make(SameSiteRefererMiddleware::class);
        $is_same_site = $same_site->isSameSite($ref);

        if ($is_same_site) {
            return logout();
        }

        return view('user::logout.index');
    }

    public function submit(Request $request)
    {
        Auth::logout();

        $url = site_url();

        return app()->url_manager->redirect($url);
    }

}
Program: CWE-352
Project: CVE-2022-23601
Buggy source:
None

Fixed version (ground truth):
<?php

$container->loadFromExtension('framework', [
    'form' => [
        'legacy_error_messages' => false,
    ],
    'session' => [
        'storage_factory_id' => 'session.storage.factory.native',
        'handler_id' => null,
    ],
]);
Program: CWE-352
Project: CVE-2022-31000
Buggy source:
None

Fixed version (ground truth):
<?php

$container->loadFromExtension('framework', [
    'form' => [
        'legacy_error_messages' => false,
    ],
    'session' => [
        'storage_factory_id' => 'session.storage.factory.native',
        'handler_id' => null,
    ],
]);
Program: CWE-434
Project: CVE-2019-8293
Buggy source:
<?php
    if(isset($_FILES["fileUpload"]["name"])){
        $imageFile = ($_FILES["fileUpload"]["name"]);
        $imageType = ($_FILES["fileUpload"]["type"]);
        $validext = array("jpeg","jpg","png");
        $fileExt = pathinfo($imageFile, PATHINFO_EXTENSION);
        $ready = false;
        if((($imageType == "image/jpeg") || ($imageType == "image/jpg") || ($imageType == "image/png"))&&in_array($fileExt, $validext)){
            $ready = true;
        }else{
            echo "was not an image<br>";
        }

        if($_FILES["fileUpload"]["size"] < 1000000){
            $ready = true;
            echo "file size is ".$_FILES['fileUpload']["size"]."<br>";
        }else{
            echo "file was TOO BIG!";
        }

        if($_FILES["fileUpload"]["error"]){
            echo "looks like there was an error".$_FILES['fileUpload']["error"]."<br>";
            $ready = false;
        }

        $targetPath = "images/".$imageFile;
        $sourcePath = $_FILES["fileUpload"]["tmp_name"];
        if(file_exists("images/".$imageFile)){
            echo "File already there <br>";
            $ready = false;
        }

        if($ready == true){
            move_uploaded_file($sourcePath,$targetPath);
            echo "upload successful!";
        }
    }
?>

Fixed version (ground truth):
<?php
    if(isset($_FILES["fileUpload"]["name"])){
        $imageFile = ($_FILES["fileUpload"]["name"]);
        $imageType = ($_FILES["fileUpload"]["type"]);
        $validext = array("jpeg","jpg","png");
        $fileExt = pathinfo($imageFile, PATHINFO_EXTENSION);
        $ready = false;
        if((($imageType == "image/jpeg") || ($imageType == "image/jpg") || ($imageType == "image/png"))&&in_array($fileExt, $validext)){
            $ready = true;
        }else{
            echo "was not an image<br>";
            exit();
        }

        if($_FILES["fileUpload"]["size"] < 1000000){
            $ready = true;
            echo "file size is ".$_FILES['fileUpload']["size"]."<br>";
        }else{
            echo "file was TOO BIG!";
            exit();
        }

        if($_FILES["fileUpload"]["error"]){
            echo "looks like there was an error".$_FILES['fileUpload']["error"]."<br>";
            $ready = false;
            exit();
        }

        $targetPath = "images/".$imageFile;
        $sourcePath = $_FILES["fileUpload"]["tmp_name"];
        if(file_exists("images/".$imageFile)){
            echo "File already there <br>";
            $ready = false;
            exit();
        }

        if($ready == true){
            move_uploaded_file($sourcePath,$targetPath);
            echo "upload successful!";
        }
    }
?>
Program: CWE-434
Project: CVE-2021-21245
Buggy source:
None

Fixed version (ground truth):
package io.onedev.server.util;

public class FilenameUtils extends org.apache.commons.io.FilenameUtils {

	public static String sanitizeFilename(String fileName) {
		return fileName.replace("..", "_").replace('/', '_').replace('\\', '_');
	}

}
Program: CWE-434
Project: CVE-2021-3915
Buggy source:
None

Fixed version (ground truth):
<?php

namespace BookStack\Util;

use finfo;

/**
 * Helper class to sniff out the mime-type of content resulting in
 * a mime-type that's relatively safe to serve to a browser.
 */
class WebSafeMimeSniffer
{

    /**
     * @var string[]
     */
    protected $safeMimes = [
        'application/json',
        'application/octet-stream',
        'application/pdf',
        'image/bmp',
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'image/avif',
        'image/heic',
        'text/css',
        'text/csv',
        'text/javascript',
        'text/json',
        'text/plain',
        'video/x-msvideo',
        'video/mp4',
        'video/mpeg',
        'video/ogg',
        'video/webm',
        'video/vp9',
        'video/h264',
        'video/av1',
    ];

    /**
     * Sniff the mime-type from the given file content while running the result
     * through an allow-list to ensure a web-safe result.
     * Takes the content as a reference since the value may be quite large.
     */
    public function sniff(string &$content): string
    {
        $fInfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $fInfo->buffer($content) ?: 'application/octet-stream';

        if (in_array($mime, $this->safeMimes)) {
            return $mime;
        }

        [$category] = explode('/', $mime, 2);
        if ($category === 'text') {
            return 'text/plain';
        }

        return 'application/octet-stream';
    }

}
Program: CWE-434
Project: CVE-2021-40324
Buggy source:
None

Fixed version (ground truth):
<?php

namespace BookStack\Util;

use finfo;

/**
 * Helper class to sniff out the mime-type of content resulting in
 * a mime-type that's relatively safe to serve to a browser.
 */
class WebSafeMimeSniffer
{

    /**
     * @var string[]
     */
    protected $safeMimes = [
        'application/json',
        'application/octet-stream',
        'application/pdf',
        'image/bmp',
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'image/avif',
        'image/heic',
        'text/css',
        'text/csv',
        'text/javascript',
        'text/json',
        'text/plain',
        'video/x-msvideo',
        'video/mp4',
        'video/mpeg',
        'video/ogg',
        'video/webm',
        'video/vp9',
        'video/h264',
        'video/av1',
    ];

    /**
     * Sniff the mime-type from the given file content while running the result
     * through an allow-list to ensure a web-safe result.
     * Takes the content as a reference since the value may be quite large.
     */
    public function sniff(string &$content): string
    {
        $fInfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $fInfo->buffer($content) ?: 'application/octet-stream';

        if (in_array($mime, $this->safeMimes)) {
            return $mime;
        }

        [$category] = explode('/', $mime, 2);
        if ($category === 'text') {
            return 'text/plain';
        }

        return 'application/octet-stream';
    }

}
Program: CWE-434
Project: CVE-2022-0472
Buggy source:
<?php

namespace App\Shop\Products\Requests;

use App\Shop\Base\BaseFormRequest;
use Illuminate\Validation\Rule;

class UpdateProductRequest extends BaseFormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'sku' => ['required'],
            'name' => ['required', Rule::unique('products')->ignore($this->segment(3))],
            'quantity' => ['required', 'integer', 'min:0'],
            'price' => ['required', 'numeric', 'min:0'],
            'sale_price' => ['nullable', 'numeric'],
            'weight' => ['nullable', 'numeric', 'min:0']
        ];
    }
}


Fixed version (ground truth):
<?php

namespace App\Shop\Products\Requests;

use App\Shop\Base\BaseFormRequest;
use Illuminate\Validation\Rule;

class UpdateProductRequest extends BaseFormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'sku' => ['required'],
            'name' => ['required', Rule::unique('products')->ignore($this->segment(3))],
            'quantity' => ['required', 'integer', 'min:0'],
            'price' => ['required', 'numeric', 'min:0'],
            'sale_price' => ['nullable', 'numeric'],
            'weight' => ['nullable', 'numeric', 'min:0'],
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'cover' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ];
    }
}
Program: CWE-434
Project: CVE-2022-1033
Buggy source:
<?php

namespace Crater\Http\Requests;

use Crater\Rules\Base64Mime;
use Illuminate\Foundation\Http\FormRequest;

class UploadExpenseReceiptRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'upload_receipt' => [
                'nullable',
                new Base64Mime(['gif', 'jpg', 'png'])
            ]
        ];
    }
}


Fixed version (ground truth):
<?php

namespace Crater\Http\Requests;

use Crater\Rules\Base64Mime;
use Illuminate\Foundation\Http\FormRequest;

class UploadExpenseReceiptRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'attachment_receipt' => [
                'nullable',
                new Base64Mime(['gif', 'jpg', 'png'])
            ]
        ];
    }
}
Program: CWE-862
Project: CVE-2019-10648
Buggy source:
/**
 * Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * https://robocode.sourceforge.io/license/epl-v10.html
 */
package net.sf.robocode.test.robots;


import net.sf.robocode.test.helpers.RobocodeTestBed;
import org.junit.Assert;
import robocode.control.events.TurnEndedEvent;


/**
 * @author Flemming N. Larsen (original)
 */
public class TestConstructorHttpAttack extends RobocodeTestBed {

	private boolean messagedInitialization;
	private boolean messagedAccessDenied;
	
	@Override
	public String getRobotNames() {
		return "tested.robots.ConstructorHttpAttack,sample.Target";
	}

	@Override
	public void onTurnEnded(TurnEndedEvent event) {
		super.onTurnEnded(event);

		final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();

		if (out.contains("An error occurred during initialization")) {
			messagedInitialization = true;	
		}	

		if (out.contains("access denied (java.net.SocketPermission")
				|| out.contains("access denied (\"java.net.SocketPermission\"")) {
			messagedAccessDenied = true;	
		}	
	}

	@Override
	protected void runTeardown() {
		Assert.assertTrue("Error during initialization", messagedInitialization);
		Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied);
	}

	@Override
	protected int getExpectedErrors() {
		return hasJavaNetURLPermission ? 3 : 2; // Security error must be reported as an error
	}
}


Fixed version (ground truth):
/**
 * Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * https://robocode.sourceforge.io/license/epl-v10.html
 */
package net.sf.robocode.test.robots;


import net.sf.robocode.test.helpers.RobocodeTestBed;
import org.junit.Assert;
import robocode.control.events.TurnEndedEvent;


/**
 * @author Flemming N. Larsen (original)
 */
public class TestConstructorHttpAttack extends RobocodeTestBed {

	private boolean messagedInitialization;
	private boolean securityExceptionOccurred;
	
	@Override
	public String getRobotNames() {
		return "tested.robots.ConstructorHttpAttack,sample.Target";
	}

	@Override
	public void onTurnEnded(TurnEndedEvent event) {
		super.onTurnEnded(event);

		final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();

		if (out.contains("An error occurred during initialization")) {
			messagedInitialization = true;	
		}	

		if (out.contains("java.lang.SecurityException:")) {
			securityExceptionOccurred = true;	
		}	
	}

	@Override
	protected void runTeardown() {
		Assert.assertTrue("Error during initialization", messagedInitialization);
		Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred);
	}

	@Override
	protected int getExpectedErrors() {
		return 2;
	}
}