nus-yam/ex-repair huggingface dataset:
Program: CWE-862
Project: CVE-2020-14213
Buggy source:
class Controllers::TicketsControllerPolicy < Controllers::ApplicationControllerPolicy
  permit! %i[import_example import_start], to: 'admin'
  permit! :selector, to: 'admin.*'
  permit! :create, to: ['ticket.agent', 'ticket.customer']
end


Fixed version (ground truth):
class Controllers::TicketsControllerPolicy < Controllers::ApplicationControllerPolicy
  permit! %i[import_example import_start], to: 'admin'
  permit! :selector, to: 'admin.*'
  permit! %i[ticket_customer ticket_history ticket_related ticket_recent ticket_merge ticket_split], to: 'ticket.agent'
  permit! :create, to: ['ticket.agent', 'ticket.customer']
end
Program: CWE-862
Project: CVE-2020-29006
Buggy source:
<?php
App::uses('AppController', 'Controller');

class GalaxyElementsController extends AppController
{
    public $components = array('Session', 'RequestHandler');

    public $paginate = array(
            'limit' => 20,
            'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 events <- no we won't, this is the max a user van view/page.
            'recursive' => -1,
            'order' => array(
                'GalaxyElement.key' => 'ASC'
            )
    );

    public function index($id)
    {
        $this->paginate['conditions'] = array('GalaxyElement.galaxy_cluster_id' => $id);
        $clusters = $this->paginate();
        $this->set('list', $clusters);
        if ($this->request->is('ajax')) {
            $this->layout = 'ajax';
            $this->render('ajax/index');
        }
    }
}


Fixed version (ground truth):
<?php
App::uses('AppController', 'Controller');

class GalaxyElementsController extends AppController
{
    public $components = array('Session', 'RequestHandler');

    public $paginate = array(
            'limit' => 20,
            'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 events <- no we won't, this is the max a user van view/page.
            'recursive' => -1,
            'order' => array(
                'GalaxyElement.key' => 'ASC'
            )
    );

    public function index($clusterId)
    {
        $aclConditions = $this->GalaxyElement->buildClusterConditions($this->Auth->user(), $clusterId);
        $this->paginate['conditions'] = [$aclConditions];
        $this->paginate['contain'] = ['GalaxyCluster' => ['fields' => ['id', 'distribution', 'org_id']]];
        $clusters = $this->paginate();
        $this->set('list', $clusters);
        if ($this->request->is('ajax')) {
            $this->layout = 'ajax';
            $this->render('ajax/index');
        }
    }
}
Program: CWE-862
Project: CVE-2020-29158
Buggy source:
class Ticket::ArticlePolicy < ApplicationPolicy

  def show?
    access?(__method__)
  end

  def create?
    access?(__method__)
  end

  def update?
    return false if !access?(__method__)
    return true if user.permissions?(['ticket.agent', 'admin'])

    not_authorized('ticket.agent or admin permission required')
  end

  def destroy?
    return false if !access?('show?')

    # agents can destroy articles of type 'note'
    # which were created by themselves within the last x minutes

    if !user.permissions?('ticket.agent')
      return not_authorized('agent permission required')
    end

    if record.created_by_id != user.id
      return not_authorized('you can only delete your own notes')
    end

    if record.type.communication?
      return not_authorized('communication articles cannot be deleted')
    end

    if deletable_timeframe? && record.created_at <= deletable_timeframe.ago
      return not_authorized('note is too old to be deleted')
    end

    true
  end

  private

  def deletable_timeframe_setting
    Setting.get('ui_ticket_zoom_article_delete_timeframe')
  end

  def deletable_timeframe?
    deletable_timeframe_setting&.positive?
  end

  def deletable_timeframe
    deletable_timeframe_setting.seconds
  end

  def access?(query)
    return false if record.internal == true && !user.permissions?('ticket.agent')

    ticket = Ticket.lookup(id: record.ticket_id)
    Pundit.authorize(user, ticket, query)
  end
end


Fixed version (ground truth):
class Ticket::ArticlePolicy < ApplicationPolicy

  def show?
    access?(__method__)
  end

  def create?
    access?(__method__)
  end

  def update?
    return false if !access?(__method__)
    return true if user.permissions?(['ticket.agent', 'admin'])

    not_authorized('ticket.agent or admin permission required')
  end

  def destroy?
    return false if !access?('show?')

    # agents can destroy articles of type 'note'
    # which were created by themselves within the last x minutes

    if !user.permissions?('ticket.agent')
      return not_authorized('agent permission required')
    end

    if record.created_by_id != user.id
      return not_authorized('you can only delete your own notes')
    end

    if record.type.communication?
      return not_authorized('communication articles cannot be deleted')
    end

    if deletable_timeframe? && record.created_at <= deletable_timeframe.ago
      return not_authorized('note is too old to be deleted')
    end

    true
  end

  private

  def deletable_timeframe_setting
    Setting.get('ui_ticket_zoom_article_delete_timeframe')
  end

  def deletable_timeframe?
    deletable_timeframe_setting&.positive?
  end

  def deletable_timeframe
    deletable_timeframe_setting.seconds
  end

  def access?(query)
    ticket = Ticket.lookup(id: record.ticket_id)
    return false if record.internal == true && !TicketPolicy.new(user, ticket).agent_read_access?

    Pundit.authorize(user, ticket, query)
  end
end
Program: CWE-862
Project: CVE-2021-21246
Buggy source:
package io.onedev.server.rest;

import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.apache.shiro.authz.UnauthorizedException;
import org.hibernate.criterion.Restrictions;
import org.hibernate.validator.constraints.Email;

import io.onedev.server.entitymanager.UserManager;
import io.onedev.server.model.User;
import io.onedev.server.persistence.dao.EntityCriteria;
import io.onedev.server.rest.jersey.ValidQueryParams;
import io.onedev.server.security.SecurityUtils;

@Path("/users")
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Singleton
public class UserResource {

	private final UserManager userManager;
	
	@Inject
	public UserResource(UserManager userManager) {
		this.userManager = userManager;
	}
	
	@ValidQueryParams
	@GET
	public Response query(@QueryParam("name") String name, @Email @QueryParam("email") String email, 
			@QueryParam("offset") Integer offset, @QueryParam("count") Integer count, @Context UriInfo uriInfo) {
    	if (!SecurityUtils.isAdministrator())
    		throw new UnauthorizedException("Unauthorized access to user profiles");
    	
    	EntityCriteria<User> criteria = EntityCriteria.of(User.class);
    	if (name != null)
    		criteria.add(Restrictions.eq("name", name));
		if (email != null)
			criteria.add(Restrictions.eq("email", email));
		
    	if (offset == null)
    		offset = 0;
    	
    	if (count == null || count > RestConstants.PAGE_SIZE) 
    		count = RestConstants.PAGE_SIZE;

    	Collection<User> users = userManager.query(criteria, offset, count);
		
		return Response.ok(users, RestConstants.JSON_UTF8).build();
	}
	
    @GET
    @Path("/{userId}")
    public User get(@PathParam("userId") Long userId) {
    	return userManager.load(userId);
    }
    
}


Fixed version (ground truth):
None
Program: CWE-862
Project: CVE-2021-21307
Buggy source:
<?xml version="1.0" encoding="UTF-8"?>
<project default="core" basedir="." name="Lucee" xmlns:artifact="antlib:org.apache.maven.artifact.ant">

  <property name="version" value="5.3.8.88-SNAPSHOT"/>

  <path id="maven-ant-tasks.classpath" path="../ant/lib/maven-ant-tasks-2.1.3.jar" />
  <typedef resource="org/apache/maven/artifact/ant/antlib.xml"
           uri="antlib:org.apache.maven.artifact.ant"
           classpathref="maven-ant-tasks.classpath" />

  <import file="../ant/build-core.xml"/>


  <target name="withTestcases">
    <property name="testcases" value="true"/>
  </target>

  <target name="setEnv">
      <artifact:pom id="pom" file="pom.xml" />

      <!-- dependecies -->
      <artifact:dependencies filesetId="mydeps" pomRefId="pom" />
      <pathconvert property="dependencies" refid="mydeps"/>

      <property name="runtime_classpath" value="${java.class.path}:${dependencies}"/>
      <property name="outputDir" location="target/classes"/>
      <property name="target" location="target"/>
      <property name="baseDir" location=".."/>
      <property name="rootDir" location=".."/>

      <delete dir="${target}"/>
      <mkdir dir="${outputDir}"/>
  </target>

  <target name="core" depends="withTestcases,setEnv,buildLoaderAnt" description="build only Lucee itself">

      <delete dir="${outputDir}"/>
  </target>


  <target name="fast" depends="setEnv,buildLoaderAnt" description="build only Lucee itself">

      <delete dir="${outputDir}"/>
  </target>

</project>

Fixed version (ground truth):
<?xml version="1.0" encoding="UTF-8"?>
<project default="core" basedir="." name="Lucee" xmlns:artifact="antlib:org.apache.maven.artifact.ant">

  <property name="version" value="5.3.8.89-SNAPSHOT"/>

  <path id="maven-ant-tasks.classpath" path="../ant/lib/maven-ant-tasks-2.1.3.jar" />
  <typedef resource="org/apache/maven/artifact/ant/antlib.xml"
           uri="antlib:org.apache.maven.artifact.ant"
           classpathref="maven-ant-tasks.classpath" />

  <import file="../ant/build-core.xml"/>


  <target name="withTestcases">
    <property name="testcases" value="true"/>
  </target>

  <target name="setEnv">
      <artifact:pom id="pom" file="pom.xml" />

      <!-- dependecies -->
      <artifact:dependencies filesetId="mydeps" pomRefId="pom" />
      <pathconvert property="dependencies" refid="mydeps"/>

      <property name="runtime_classpath" value="${java.class.path}:${dependencies}"/>
      <property name="outputDir" location="target/classes"/>
      <property name="target" location="target"/>
      <property name="baseDir" location=".."/>
      <property name="rootDir" location=".."/>

      <delete dir="${target}"/>
      <mkdir dir="${outputDir}"/>
  </target>

  <target name="core" depends="withTestcases,setEnv,buildLoaderAnt" description="build only Lucee itself">

      <delete dir="${outputDir}"/>
  </target>


  <target name="fast" depends="setEnv,buildLoaderAnt" description="build only Lucee itself">

      <delete dir="${outputDir}"/>
  </target>

</project>
Program: CWE-476
Project: CVE-2016-7130
Buggy source:
None

Fixed version (ground truth):
--TEST--
Bug #72750: wddx_deserialize null dereference
--SKIPIF--
<?php
if (!extension_loaded('wddx')) {
    die('skip. wddx not available');
}
?>
--FILE--
<?php

$xml = <<< XML
<?xml version='1.0'?>
<!DOCTYPE wddxPacket SYSTEM 'wddx_0100.dtd'>
<wddxPacket version='1.0'>
<header/>
        <data>
                <struct>
                     <var name='aBinary'>
                         <binary length='11'>\\tYmluYXJRhdGE=</binary>
                     </var>
                 </struct>
        </data>
</wddxPacket>
XML;

$array = wddx_deserialize($xml);
var_dump($array);
?>
--EXPECT--
array(1) {
  ["aBinary"]=>
  string(0) ""
}
Program: CWE-476
Project: CVE-2016-7131
Buggy source:
None

Fixed version (ground truth):
--TEST--
Bug #72799: wddx_deserialize null dereference in php_wddx_pop_element
--SKIPIF--
<?php
if (!extension_loaded('wddx')) {
    die('skip. wddx not available');
}
?>
--FILE--
<?php

$xml = <<<XML
<?xml version='1.0'?>
<!DOCTYPE wddxPacket SYSTEM 'wddx_0100.dtd'>
<wddxPacket version="1.0">
    <var name="XXXX">
        <boolean value="1">
            <dateTime>1998-06-12T04:32:12+00</dateTime>
        </boolean>
    </var>
</wddxPacket>
XML;

$array = wddx_deserialize($xml);
var_dump($array);
?>
--EXPECT--
NULL
Program: CWE-476
Project: CVE-2016-7132
Buggy source:
None

Fixed version (ground truth):
--TEST--
Bug #72799: wddx_deserialize null dereference in php_wddx_pop_element
--SKIPIF--
<?php
if (!extension_loaded('wddx')) {
    die('skip. wddx not available');
}
?>
--FILE--
<?php

$xml = <<<XML
<?xml version='1.0'?>
<!DOCTYPE wddxPacket SYSTEM 'wddx_0100.dtd'>
<wddxPacket version="1.0">
    <var name="XXXX">
        <boolean value="1">
            <dateTime>1998-06-12T04:32:12+00</dateTime>
        </boolean>
    </var>
</wddxPacket>
XML;

$array = wddx_deserialize($xml);
var_dump($array);
?>
--EXPECT--
NULL
Program: CWE-476
Project: CVE-2016-9934
Buggy source:
--TEST--
Bug #45901 (wddx_serialize_value crash with SimpleXMLElement object)
--SKIPIF--
<?php
if (!extension_loaded("wddx")) print "skip";
if (!extension_loaded("simplexml")) print "skip SimpleXML not present";
?>
--FILE--
<?php

$xml = new SimpleXMLElement('<data></data>');
$xml->addChild('test');
echo wddx_serialize_value($xml, 'Variables') . "\n";
echo "DONE";
?>
--EXPECTF--
<wddxPacket version='1.0'><header><comment>Variables</comment></header><data><struct><var name='php_class_name'><string>SimpleXMLElement</string></var><var name='test'><struct><var name='php_class_name'><string>SimpleXMLElement</string></var></struct></var></struct></data></wddxPacket>
DONE

Fixed version (ground truth):
--TEST--
Bug #45901 (wddx_serialize_value crash with SimpleXMLElement object)
--SKIPIF--
<?php
if (!extension_loaded("wddx")) print "skip";
if (!extension_loaded("simplexml")) print "skip SimpleXML not present";
?>
--FILE--
<?php

$xml = new SimpleXMLElement('<data></data>');
$xml->addChild('test');
echo wddx_serialize_value($xml, 'Variables') . "\n";
echo "DONE";
?>
--EXPECTF--

Warning: wddx_serialize_value(): Class SimpleXMLElement can not be serialized in %sbug45901.php on line %d
<wddxPacket version='1.0'><header><comment>Variables</comment></header><data></data></wddxPacket>
DONE
Program: CWE-476
Project: CVE-2017-10965
Buggy source:
--TEST--
Bug #45901 (wddx_serialize_value crash with SimpleXMLElement object)
--SKIPIF--
<?php
if (!extension_loaded("wddx")) print "skip";
if (!extension_loaded("simplexml")) print "skip SimpleXML not present";
?>
--FILE--
<?php

$xml = new SimpleXMLElement('<data></data>');
$xml->addChild('test');
echo wddx_serialize_value($xml, 'Variables') . "\n";
echo "DONE";
?>
--EXPECTF--
<wddxPacket version='1.0'><header><comment>Variables</comment></header><data><struct><var name='php_class_name'><string>SimpleXMLElement</string></var><var name='test'><struct><var name='php_class_name'><string>SimpleXMLElement</string></var></struct></var></struct></data></wddxPacket>
DONE

Fixed version (ground truth):
--TEST--
Bug #45901 (wddx_serialize_value crash with SimpleXMLElement object)
--SKIPIF--
<?php
if (!extension_loaded("wddx")) print "skip";
if (!extension_loaded("simplexml")) print "skip SimpleXML not present";
?>
--FILE--
<?php

$xml = new SimpleXMLElement('<data></data>');
$xml->addChild('test');
echo wddx_serialize_value($xml, 'Variables') . "\n";
echo "DONE";
?>
--EXPECTF--

Warning: wddx_serialize_value(): Class SimpleXMLElement can not be serialized in %sbug45901.php on line %d
<wddxPacket version='1.0'><header><comment>Variables</comment></header><data></data></wddxPacket>
DONE
Program: CWE-476
Project: CVE-2017-9250
Buggy source:
None

Fixed version (ground truth):
// Copyright JS Foundation and other contributors, http://js.foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'\
'
Program: CWE-476
Project: CVE-2018-14553
Buggy source:
None

Fixed version (ground truth):
/**
 * Cloning an image should exactly reproduce all style related data
 */


#include <string.h>
#include "gd.h"
#include "gdtest.h"


int main()
{
    gdImagePtr im, clone;
    int style[] = {0, 0, 0};

    im = gdImageCreate(8, 8);
    gdImageSetStyle(im, style, sizeof(style)/sizeof(style[0]));

    clone = gdImageClone(im);
    gdTestAssert(clone != NULL);

    gdTestAssert(clone->styleLength == im->styleLength);
    gdTestAssert(clone->stylePos == im->stylePos);
    gdTestAssert(!memcmp(clone->style, im->style, sizeof(style)/sizeof(style[0])));

    gdImageDestroy(clone);
    gdImageDestroy(im);

    return gdNumFailures();
}
Program: CWE-476
Project: CVE-2019-19242
Buggy source:
2d53a30cc23e53033af8e8666457654db5dcc453ed6cd176ce1d0bff4f528159

Fixed version (ground truth):
8b12e95fec7ce6e0de82a04ca3dfcf1a8e62e233b7382aa28a8a9be6e862b1af
Program: CWE-476
Project: CVE-2020-26213
Buggy source:
// +build !windows

package errors

import "syscall"

// Abort will terminate & sends SIGTERM to process
func Abort(i ...int) {
	pgid, err := syscall.Getpgid(syscall.Getpid())
	if err != nil {
		Exit(err.Error())
	}

	// nolint:errcheck
	syscall.Kill(-pgid, syscall.SIGTERM)
}


Fixed version (ground truth):
// +build !windows

package errors

import (
	"os"
	"syscall"
)

// Abort will terminate & sends SIGTERM to process
func Abort(i ...int) {
	if _, err := os.Stat("/.dockerenv"); err == nil {
		os.Exit(i[0])
	}

	pgid, err := syscall.Getpgid(syscall.Getpid())
	if err != nil {
		Exit(err.Error())
	}

	// nolint:errcheck
	syscall.Kill(-pgid, syscall.SIGTERM)
}
Program: CWE-287
Project: CVE-2019-12530
Buggy source:
<?php

// /bin/cat /proc/loadavg | /usr/bin/awk '{print $1","$2","$3}'

$cores = exec('/bin/grep -c ^processor /proc/cpuinfo');

$loadavg = exec('/bin/cat /proc/loadavg | /usr/bin/awk \'{print $2}\'');

$load = round(($loadavg*100)/$cores ,1);

//$load = $perc;	

if($cores == 1) {
	$ncores = '1 core'; }
else {
	$ncores = $cores.' cores'; }	

//echo $load."% &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(5 min)";

echo $load."% &nbsp;&nbsp;&nbsp;&nbsp;(".$ncores.")";	
	
if($load > 90) { $corl = "progress-bar-danger"; }

if($load >= 60 and $load <= 90) { $corl = "progress-bar-warning"; } 

if($load > 51 and $load < 60) { $corl = "progress-bar"; }

if($load > 0 and $load <= 50) { $corl = "progress-bar-success"; }	


?>

Fixed version (ground truth):
<?php

Session::checkLoginUser();
Session::checkRight("profile", READ);

$cores = exec('/bin/grep -c ^processor /proc/cpuinfo');

$loadavg = exec('/bin/cat /proc/loadavg | /usr/bin/awk \'{print $2}\'');

$load = round(($loadavg*100)/$cores ,1);


if($cores == 1) {
	$ncores = '1 core'; }
else {
	$ncores = $cores.' cores'; }	

//echo $load."% &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(5 min)";

echo $load."% &nbsp;&nbsp;&nbsp;&nbsp;(".$ncores.")";	
	
if($load > 90) { $corl = "progress-bar-danger"; }

if($load >= 60 and $load <= 90) { $corl = "progress-bar-warning"; } 

if($load > 51 and $load < 60) { $corl = "progress-bar"; }

if($load > 0 and $load <= 50) { $corl = "progress-bar-success"; }	


?>
Program: CWE-287
Project: CVE-2021-21329
Buggy source:
None

Fixed version (ground truth):
# Generated by Django 3.0.5 on 2020-08-10 11:11

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import pyotp


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('authentication', '0003_passwordresettoken'),
    ]

    operations = [
        migrations.AlterField(
            model_name='passwordresettoken',
            name='issued',
            field=models.DateTimeField(auto_now_add=True),
        ),
        migrations.CreateModel(
            name='TOTPDevice',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('last_used', models.DateTimeField(null=True)),
                ('totp_secret', models.CharField(default=pyotp.random_base32, max_length=16, null=True)),
                ('verified', models.BooleanField(default=False)),
                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='totp_device', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='BackupCode',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.CharField(max_length=8)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='backup_codes', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'unique_together': {('user', 'code')},
            },
        ),
    ]
Program: CWE-287
Project: CVE-2021-39165
Buggy source:
<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Models\Traits;

use Illuminate\Database\Eloquent\Builder;

/**
 * This is the searchable trait.
 *
 * @author James Brooks <james@alt-three.com>
 */
trait SearchableTrait
{
    /**
     * Adds a search scope.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param array                                 $search
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch(Builder $query, array $search = [])
    {
        if (empty($search)) {
            return $query;
        }

        if (!array_intersect(array_keys($search), $this->searchable)) {
            return $query;
        }

        return $query->where($search);
    }
}


Fixed version (ground truth):
<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Models\Traits;

use Illuminate\Database\Eloquent\Builder;

/**
 * This is the searchable trait.
 *
 * @author James Brooks <james@alt-three.com>
 */
trait SearchableTrait
{
    /**
     * Adds a search scope.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param array                                 $search
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch(Builder $query, array $search = [])
    {
        if (empty($search)) {
            return $query;
        }

        $allowed_search = array_intersect_key($search, array_flip($this->searchable));
        if (! $allowed_search) {
            return $query;
        }

        return $query->where($allowed_search);
    }
}
Program: CWE-287
Project: CVE-2021-45890
Buggy source:
package com.nexblocks.authguard.service.exceptions.codes;

public enum ErrorCode {
    ACCOUNT_DOES_NOT_EXIST("AC.011"),
    ACCOUNT_DUPLICATE_EMAILS("AC.031"),
    ACCOUNT_DUPLICATE_PHONE_NUMBER("AC.032"),
    ACCOUNT_EMAIL_REQUIRED("AC.032"),
    ACCOUNT_PHONE_NUMBER_REQUIRED("AC.032"),

    APP_DOES_NOT_EXIST("AP.011"),

    API_KEY_DOES_NOT_EXIST("AK.011"),

    PERMISSION_DOES_NOT_EXIST("PR.011"),
    PERMISSION_ALREADY_EXIST("PR.012"),

    ROLE_DOES_NOT_EXIST("RL.011"),
    ROLE_ALREADY_EXISTS("RL.012"),

    CREDENTIALS_DOES_NOT_EXIST("CD.011"),
    IDENTIFIER_ALREADY_EXISTS("CD.012"),
    IDENTIFIER_DOES_NOT_EXIST("CD.013"),

    IDEMPOTENCY_ERROR("ID.0.12"),

    EXPIRED_TOKEN("TK.021"),
    INVALID_TOKEN("TK.022"),

    UNKNOWN_EXCHANGE("AT.021"),
    UNSUPPORTED_SCHEME("AT.022"),
    INVALID_AUTHORIZATION_FORMAT("AT.023"),
    INVALID_ADDITIONAL_INFORMATION_TYPE("AT.024"),
    TOKEN_EXPIRED_OR_DOES_NOT_EXIST("AT.025"),
    TOKEN_GENERATION_FAILED("AT.031"),
    ACCOUNT_IS_LOCKED("AT.032"),
    GENERIC_AUTH_FAILURE("AT.039"),

    UNSUPPORTED_JWT_ALGORITHM("JT.021"),
    ENCRYPTION_NOT_SUPPORTED("JT.022"),

    PASSWORDS_DO_NOT_MATCH("PW.021"),
    INVALID_PASSWORD("PW.022"),

    LDAP_MULTIPLE_PASSWORD_ENTRIES("LD.021"),
    LDAP_ERROR("LD.031"),

    MISSING_REQUEST_QUERY("RQ.011"),
    INVALID_REQUEST_QUERY("RQ.012");

    private final String code;

    ErrorCode(final String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}


Fixed version (ground truth):
package com.nexblocks.authguard.service.exceptions.codes;

public enum ErrorCode {
    ACCOUNT_DOES_NOT_EXIST("AC.011"),
    ACCOUNT_DUPLICATE_EMAILS("AC.031"),
    ACCOUNT_DUPLICATE_PHONE_NUMBER("AC.032"),
    ACCOUNT_EMAIL_REQUIRED("AC.032"),
    ACCOUNT_PHONE_NUMBER_REQUIRED("AC.032"),

    APP_DOES_NOT_EXIST("AP.011"),

    API_KEY_DOES_NOT_EXIST("AK.011"),

    PERMISSION_DOES_NOT_EXIST("PR.011"),
    PERMISSION_ALREADY_EXIST("PR.012"),

    ROLE_DOES_NOT_EXIST("RL.011"),
    ROLE_ALREADY_EXISTS("RL.012"),

    CREDENTIALS_DOES_NOT_EXIST("CD.011"),
    IDENTIFIER_ALREADY_EXISTS("CD.012"),
    IDENTIFIER_DOES_NOT_EXIST("CD.013"),

    IDEMPOTENCY_ERROR("ID.0.12"),

    EXPIRED_TOKEN("TK.021"),
    INVALID_TOKEN("TK.022"),

    UNKNOWN_EXCHANGE("AT.021"),
    UNSUPPORTED_SCHEME("AT.022"),
    INVALID_AUTHORIZATION_FORMAT("AT.023"),
    INVALID_ADDITIONAL_INFORMATION_TYPE("AT.024"),
    TOKEN_EXPIRED_OR_DOES_NOT_EXIST("AT.025"),
    TOKEN_GENERATION_FAILED("AT.031"),
    ACCOUNT_IS_LOCKED("AT.032"),
    INACTIVE_IDENTIFIER("AT.033"),
    GENERIC_AUTH_FAILURE("AT.039"),

    UNSUPPORTED_JWT_ALGORITHM("JT.021"),
    ENCRYPTION_NOT_SUPPORTED("JT.022"),

    PASSWORDS_DO_NOT_MATCH("PW.021"),
    INVALID_PASSWORD("PW.022"),

    LDAP_MULTIPLE_PASSWORD_ENTRIES("LD.021"),
    LDAP_ERROR("LD.031"),

    MISSING_REQUEST_QUERY("RQ.011"),
    INVALID_REQUEST_QUERY("RQ.012");

    private final String code;

    ErrorCode(final String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}
Program: CWE-287
Project: CVE-2022-23220
Buggy source:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
 "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
  <action id="org.freedesktop.pkexec.usbview">
    <description>Run USBview</description>
    <message>Authentication is required to view USB bus</message>
    <icon_name>usbview_icon</icon_name>
    <defaults>
      <allow_any>yes</allow_any>
      <allow_inactive>yes</allow_inactive>
      <allow_active>auth_admin_keep</allow_active>
    </defaults>
    <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/usbview</annotate>
    <annotate key="org.freedesktop.policykit.exec.allow_gui">TRUE</annotate>
  </action>
</policyconfig>


Fixed version (ground truth):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
 "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
  <action id="org.freedesktop.pkexec.usbview">
    <description>Run USBview</description>
    <message>Authentication is required to view USB bus</message>
    <icon_name>usbview_icon</icon_name>
    <defaults>
      <allow_any>no</allow_any>
      <allow_inactive>no</allow_inactive>
      <allow_active>auth_admin_keep</allow_active>
    </defaults>
    <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/usbview</annotate>
    <annotate key="org.freedesktop.policykit.exec.allow_gui">TRUE</annotate>
  </action>
</policyconfig>
Program: CWE-287
Project: CVE-2022-24857
Buggy source:
None

Fixed version (ground truth):
from django.apps import AppConfig


class TwoFactorConfig(AppConfig):
    name = 'mfa'
    verbose_name = 'Multi Factor Authentication'

    def ready(self):
        from .admin import patch_admin
        patch_admin()
Program: CWE-287
Project: CVE-2022-35928
Buggy source:
cmake_minimum_required(VERSION 3.9)

string(TIMESTAMP PACKAGE_DATE %Y-%m-%dT%H:%M:%SZ UTC)
add_definitions( -DPACKAGE_NAME="aescrypt" )
add_definitions( -DPACKAGE_VERSION="1.0.0" )
add_definitions( -DPACKAGE_DATE="${PACKAGE_DATE}" )

set( HEADER_FILES
   password.h
   aes.h
   aesrandom.h
   sha256.h
   util.h
   keyfile.h )

set( COMMON_SOURCE_FILES
   aes.c
   aesrandom.c
   sha256.c
   util.c
   keyfile.c
   password.c )

add_executable( aescrypt aescrypt.c ${COMMON_SOURCE_FILES} )
add_executable( aescrypt_keygen aescrypt_keygen.c ${COMMON_SOURCE_FILES} )


Fixed version (ground truth):
string(TIMESTAMP PACKAGE_DATE %Y-%m-%dT%H:%M:%SZ UTC)

# Build a version number into the binary library
configure_file(version.h.in version.h @ONLY)

add_executable(aescrypt
   aescrypt.c
   aes.c
   aesrandom.c
   sha256.c
   util.c
   keyfile.c
   password.c)
target_compile_definitions(aescrypt PRIVATE ENABLE_ICONV)

target_include_directories(aescrypt
    PRIVATE
        $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>)

add_executable(aescrypt_keygen
   aescrypt_keygen.c
   aes.c
   aesrandom.c
   sha256.c
   util.c
   keyfile.c
   password.c)

target_include_directories(aescrypt_keygen
   PRIVATE
       $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>)

# Install target and associated include files
install(TARGETS aescrypt aescrypt_keygen)
Program: CWE-190
Project: CVE-2016-10168
Buggy source:
LIST(APPEND TESTS_FILES
	bug_289
	bug00309
	gd2_empty_file
	gd2_im2im
	gd2_null
	php_bug_72339
	gd2_read
	gd2_read_corrupt
	too_few_image_data
)

ADD_GD_TESTS()


Fixed version (ground truth):
LIST(APPEND TESTS_FILES
	bug_289
	bug00309
	bug00354
	gd2_empty_file
	gd2_im2im
	gd2_null
	php_bug_72339
	gd2_read
	gd2_read_corrupt
	too_few_image_data
)

ADD_GD_TESTS()
Program: CWE-190
Project: CVE-2016-5096
Buggy source:
None

Fixed version (ground truth):
--TEST--
Bug #72114 (Integer underflow / arbitrary null write in fread/gzread)
--FILE--
<?php
ini_set('memory_limit', "2500M");
$fp = fopen("/dev/zero", "r");
fread($fp, 2147483648);
?>
Done
--EXPECTF--
Warning: fread(): Length parameter must be no more than 2147483647 in %s/bug72114.php on line %d
Done
Program: CWE-190
Project: CVE-2016-5766
Buggy source:
None

Fixed version (ground truth):
--TEST--
Bug #72339 Integer Overflow in _gd2GetHeader() resulting in heap overflow 
--SKIPIF--
<?php if (!function_exists("imagecreatefromgd2")) print "skip"; ?>
--FILE--
<?php imagecreatefromgd2(dirname(__FILE__) . DIRECTORY_SEPARATOR . "bug72339.gd"); ?>
--EXPECTF--	
Warning: imagecreatefromgd2(): gd warning: product of memory allocation multiplication would exceed INT_MAX, failing operation gracefully
 in %sbug72339.php on line %d

Warning: imagecreatefromgd2(): '%sbug72339.gd' is not a valid GD2 file in %sbug72339.php on line %d
Program: CWE-190
Project: CVE-2016-6871
Buggy source:
None

Fixed version (ground truth):
<?php

$intMaxPre = PHP_INT_MAX - 1;
$stringNormal = 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ';

$number_bccomp_10 = bccomp("2015.5", $stringNormal, $intMaxPre);
var_dump($number_bccomp_10);
Program: CWE-190
Project: CVE-2016-6872
Buggy source:
None

Fixed version (ground truth):
<?php

$stringLarge = str_repeat('*', 300289);
$arrayLarge = array_fill(0, 49981, '*');
$string_implode_2 = implode($stringLarge, $arrayLarge);
Program: CWE-190
Project: CVE-2016-9557
Buggy source:
# All directories
core
*.o
*.a
*.la
*.lo
.deps
.libs
Makefile
Makefile.in
*.trs
*.log

# Top-level directory
/autom4te.cache
/ac_aux
/aclocal.m4
/config.log
/config.status
/configure
/jasper.spec
/libtool

# ac_m4 directory
/ac_m4/libtool.m4
/ac_m4/ltoptions.m4
/ac_m4/ltsugar.m4
/ac_m4/ltversion.m4
/ac_m4/lt~obsolete.m4

# pkgconfig directory
/pkgconfig/jasper.pc

# /src/appl directory
/src/appl/imgcmp
/src/appl/imginfo
/src/appl/jasper
/src/appl/jiv
/src/appl/tmrdemo

# ./src/libjasper/include/jasper directory
/src/libjasper/include/jasper/jas_config.h
/src/libjasper/include/jasper/jas_config.h.in
/src/libjasper/include/jasper/jas_config.h.in~
/src/libjasper/include/jasper/stamp-h1


Fixed version (ground truth):
# All directories
core
*.o
*.a
*.la
*.lo
.deps
.libs
Makefile
Makefile.in
*.trs
*.log

# Top-level directory
/autom4te.cache
/ac_aux
/aclocal.m4
/config.log
/config.status
/configure
/jasper.spec
/libtool

# ac_m4 directory
/ac_m4/libtool.m4
/ac_m4/ltoptions.m4
/ac_m4/ltsugar.m4
/ac_m4/ltversion.m4
/ac_m4/lt~obsolete.m4

# pkgconfig directory
/pkgconfig/jasper.pc

# /src/appl directory
/src/appl/imgcmp
/src/appl/imginfo
/src/appl/jasper
/src/appl/jiv
/src/appl/tmrdemo

# ./src/libjasper/include/jasper directory
/src/libjasper/include/jasper/jas_config.h
/src/libjasper/include/jasper/jas_pconf.h
/src/libjasper/include/jasper/jas_pconf.h.in
/src/libjasper/include/jasper/jas_pconf.h.in~
/src/libjasper/include/jasper/stamp-h1
Program: CWE-190
Project: CVE-2018-20545
Buggy source:
/*
 *  Imaging tools for cacaview and img2irc
 *  Copyright (c) 2003-2012 Sam Hocevar <sam@hocevar.net>
 *                All Rights Reserved
 *
 *  This program is free software. It comes without any warranty, to
 *  the extent permitted by applicable law. You can redistribute it
 *  and/or modify it under the terms of the Do What the Fuck You Want
 *  to Public License, Version 2, as published by Sam Hocevar. See
 *  http://www.wtfpl.net/ for more details.
 */

struct image
{
    char *pixels;
    unsigned int w, h;
    struct caca_dither *dither;
    void *priv;
};

/* Local functions */
extern struct image * load_image(char const *);
extern void unload_image(struct image *);



Fixed version (ground truth):
/*
 *  Imaging tools for cacaview and img2irc
 *  Copyright © 2003—2018 Sam Hocevar <sam@hocevar.net>
 *              All Rights Reserved
 *
 *  This program is free software. It comes without any warranty, to
 *  the extent permitted by applicable law. You can redistribute it
 *  and/or modify it under the terms of the Do What the Fuck You Want
 *  to Public License, Version 2, as published by the WTFPL Task Force.
 *  See http://www.wtfpl.net/ for more details.
 */

struct image
{
    char *pixels;
    size_t w, h;
    struct caca_dither *dither;
    void *priv;
};

/* Local functions */
extern struct image * load_image(char const *);
extern void unload_image(struct image *);
Program: CWE-190
Project: CVE-2020-12135
Buggy source:
/** @file env.h */

/*    Copyright 2009-2012 10gen Inc.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/* Header for generic net.h */
#ifndef MONGO_ENV_H_
#define MONGO_ENV_H_

#include "mongo.h"

MONGO_EXTERN_C_START

/* This is a no-op in the generic implementation. */
int mongo_env_set_socket_op_timeout( mongo *conn, int millis );
int mongo_env_read_socket( mongo *conn, void *buf, int len );
int mongo_env_write_socket( mongo *conn, const void *buf, int len );
int mongo_env_socket_connect( mongo *conn, const char *host, int port );

/* Initialize socket services */
MONGO_EXPORT int mongo_env_sock_init( void );

/* Close a socket */
MONGO_EXPORT int mongo_env_close_socket( int socket );

MONGO_EXTERN_C_END
#endif


Fixed version (ground truth):
/** @file env.h */

/*    Copyright 2009-2012 10gen Inc.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/* Header for generic net.h */
#ifndef MONGO_ENV_H_
#define MONGO_ENV_H_

#include "mongo.h"

MONGO_EXTERN_C_START

/* This is a no-op in the generic implementation. */
int mongo_env_set_socket_op_timeout( mongo *conn, int millis );
int mongo_env_read_socket( mongo *conn, void *buf, size_t len );
int mongo_env_write_socket( mongo *conn, const void *buf, size_t len );
int mongo_env_socket_connect( mongo *conn, const char *host, int port );

/* Initialize socket services */
MONGO_EXPORT int mongo_env_sock_init( void );

/* Close a socket */
MONGO_EXPORT int mongo_env_close_socket( int socket );

MONGO_EXTERN_C_END
#endif
Program: CWE-190
Project: CVE-2022-0961
Buggy source:
<?php
namespace MicroweberPackages\Post\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest 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.s
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
           // 'title' => 'required', // todo with multilanguage
        ];

        return $rules;
    }
}


Fixed version (ground truth):
<?php
namespace MicroweberPackages\Post\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest 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.s
     *
     * @return array
     */
    public function rules()
    {
        // todo with multilanguage

        $rules = [
            'title' => 'required|max:500',
            'url' => 'max:500',
            'description' => 'max:500',
            'content_meta_title' => 'max:500',
            'content_meta_keywords' => 'max:500',
            'original_link' => 'max:500',
        ];

        return $rules;
    }
}
Program: CWE-190
Project: CVE-2022-0968
Buggy source:
<?php

namespace MicroweberPackages\User\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserUpdateRequest extends FormRequest
{

    /**
     * Get the validation rules that apply to the request.s
     *
     * @return array
     */
    public function rules()
    {

        $ignore = Rule::unique('users')->ignore($this->id ?? 0, 'id');

        return [
            'email' => [
                $ignore,
            ],
            'username' => [
                $ignore,
            ],

        ];

    }
}


Fixed version (ground truth):
<?php

namespace MicroweberPackages\User\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserUpdateRequest extends FormRequest
{

    /**
     * Get the validation rules that apply to the request.s
     *
     * @return array
     */
    public function rules()
    {

        $ignore = Rule::unique('users')->ignore($this->id ?? 0, 'id');

        return [
            'first_name'=>'max:500',
            'last_name'=>'max:500',
            'phone'=>'max:500',
            'email' => [
                $ignore,
                'max:500'
            ],
            'username' => [
                $ignore,
                'max:500'
            ],
        ];

    }
}
Program: CWE-502
Project: CVE-2018-6331
Buggy source:
None

Fixed version (ground truth):
/*
 * Copyright 2013-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.facebook.buck.parser;

import com.facebook.buck.parser.thrift.RemoteDaemonicParserState;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.util.HashSet;
import java.util.Set;

/** A ObjectInputStream that will deserialize only RemoteDaemonicParserState. */
public class ParserStateObjectInputStream extends ObjectInputStream {

  private Set<String> whitelist;

  public ParserStateObjectInputStream(InputStream inputStream) throws IOException {
    super(inputStream);

    whitelist = new HashSet<>();
    whitelist.add(RemoteDaemonicParserState.class.getName());
  }

  @Override
  protected Class<?> resolveClass(ObjectStreamClass desc)
      throws IOException, ClassNotFoundException {
    if (!whitelist.contains(desc.getName())) {
      throw new InvalidClassException(desc.getName(), "Can't deserialize this class");
    }
    return super.resolveClass(desc);
  }
}
Program: CWE-502
Project: CVE-2021-33806
Buggy source:
package net.bdew.lib.multiblock.data

import net.bdew.lib.multiblock.network.MsgOutputCfgPayload
import net.minecraft.nbt.CompoundNBT
import sun.reflect.generics.reflectiveObjects.NotImplementedException

abstract class OutputConfig {
  def id: String
  def read(t: CompoundNBT): Unit
  def write(t: CompoundNBT): Unit
  def handleConfigPacket(m: MsgOutputCfgPayload): Unit
}

class OutputConfigInvalid extends OutputConfig {
  override val id: String = "invalid"
  def read(t: CompoundNBT): Unit = {}
  def write(t: CompoundNBT): Unit = throw new NotImplementedException
  def handleConfigPacket(m: MsgOutputCfgPayload): Unit = throw new NotImplementedException
}

object OutputConfigManager {
  var loaders = Map.empty[String, () => OutputConfig]
  def register(id: String, loader: () => OutputConfig): Unit = loaders += id -> loader
  def create(id: String): OutputConfig = loaders.get(id).map(_.apply()).getOrElse(new OutputConfigInvalid)

  register("fluid", () => new OutputConfigFluid)
  register("power", () => new OutputConfigPower)
  register("items", () => new OutputConfigItems)
}

Fixed version (ground truth):
package net.bdew.lib.multiblock.data

import net.bdew.lib.multiblock.network.MsgOutputCfg
import net.minecraft.nbt.CompoundNBT
import sun.reflect.generics.reflectiveObjects.NotImplementedException

abstract class OutputConfig {
  def id: String
  def read(t: CompoundNBT): Unit
  def write(t: CompoundNBT): Unit
  def handleConfigPacket(m: MsgOutputCfg): Unit
}

class OutputConfigInvalid extends OutputConfig {
  override val id: String = "invalid"
  def read(t: CompoundNBT): Unit = {}
  def write(t: CompoundNBT): Unit = throw new NotImplementedException
  def handleConfigPacket(m: MsgOutputCfg): Unit = throw new NotImplementedException
}

object OutputConfigManager {
  var loaders = Map.empty[String, () => OutputConfig]
  def register(id: String, loader: () => OutputConfig): Unit = loaders += id -> loader
  def create(id: String): OutputConfig = loaders.get(id).map(_.apply()).getOrElse(new OutputConfigInvalid)

  register("fluid", () => new OutputConfigFluid)
  register("power", () => new OutputConfigPower)
  register("items", () => new OutputConfigItems)
}
Program: CWE-502
Project: CVE-2022-1032
Buggy source:
<?php

namespace Crater\Http\Controllers\V1\Admin\Modules;

use Crater\Http\Controllers\Controller;
use Crater\Space\ModuleInstaller;
use Illuminate\Http\Request;

class UnzipModuleController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        $this->authorize('manage modules');

        $path = ModuleInstaller::unzip($request->module, $request->path);

        return response()->json([
            'success' => true,
            'path' => $path
        ]);
    }
}


Fixed version (ground truth):
<?php

namespace Crater\Http\Controllers\V1\Admin\Modules;

use Crater\Http\Controllers\Controller;
use Crater\Http\Requests\UnzipUpdateRequest;
use Crater\Space\ModuleInstaller;

class UnzipModuleController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Crater\Http\Requests\UnzipUpdateRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(UnzipUpdateRequest $request)
    {
        $this->authorize('manage modules');

        $path = ModuleInstaller::unzip($request->module, $request->path);

        return response()->json([
            'success' => true,
            'path' => $path
        ]);
    }
}
Program: CWE-502
Project: CVE-2022-21647
Buggy source:
<?php

namespace Crater\Http\Controllers\V1\Admin\Modules;

use Crater\Http\Controllers\Controller;
use Crater\Space\ModuleInstaller;
use Illuminate\Http\Request;

class UnzipModuleController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        $this->authorize('manage modules');

        $path = ModuleInstaller::unzip($request->module, $request->path);

        return response()->json([
            'success' => true,
            'path' => $path
        ]);
    }
}


Fixed version (ground truth):
<?php

namespace Crater\Http\Controllers\V1\Admin\Modules;

use Crater\Http\Controllers\Controller;
use Crater\Http\Requests\UnzipUpdateRequest;
use Crater\Space\ModuleInstaller;

class UnzipModuleController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Crater\Http\Requests\UnzipUpdateRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(UnzipUpdateRequest $request)
    {
        $this->authorize('manage modules');

        $path = ModuleInstaller::unzip($request->module, $request->path);

        return response()->json([
            'success' => true,
            'path' => $path
        ]);
    }
}
Program: CWE-77
Project: CVE-2014-9682
Buggy source:
{
  "name": "dns-sync",
  "version": "0.1.0",
  "description": "dns-sync",
  "main": "index.js",
  "scripts": {
    "test": "make test"
  },
  "homepage": "https://github.com/skoranga/node-dns-sync",
  "repository": {
    "type": "git",
    "url": "git@github.com:skoranga/node-dns-sync.git"
  },
  "keywords": [
    "dns sync",
    "server startup",
    "nodejs"
  ],
  "author": "Sanjeev Koranga",
  "license": "MIT",
  "readmeFilename": "README.md",
  "dependencies": {
    "debug" : "~0.7",
    "shelljs": "~0.2"
  },
  "devDependencies": {
    "mocha" : "~1",
    "jshint" : "*"
  }
}


Fixed version (ground truth):
{
  "name": "dns-sync",
  "version": "0.1.1",
  "description": "dns-sync",
  "main": "index.js",
  "scripts": {
    "test": "make test"
  },
  "homepage": "https://github.com/skoranga/node-dns-sync",
  "repository": {
    "type": "git",
    "url": "git@github.com:skoranga/node-dns-sync.git"
  },
  "keywords": [
    "dns sync",
    "server startup",
    "nodejs"
  ],
  "author": "Sanjeev Koranga",
  "license": "MIT",
  "readmeFilename": "README.md",
  "dependencies": {
    "debug" : "^2",
    "shelljs": "~0.3"
  },
  "devDependencies": {
    "mocha" : "^1",
    "jshint" : "^2"
  }
}