nus-yam/ex-repair huggingface dataset:
Program: CWE-22
Project: CVE-2018-1002201
Buggy source:
None

Fixed version (ground truth):
package org.zeroturnaround.zip;

/**
 *    Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com>
 *
 *    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.
 */
import java.io.File;

import junit.framework.TestCase;

public class DirectoryTraversalMaliciousTest extends TestCase {
  /*
   * This is the contents of the file. There is one evil file that tries to get out of the
   * target.
   *
   * $ unzip -t zip-slip.zip
   * Archive: zip-slip.zip
   * testing: good.txt OK
   * testing: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt OK
   * No errors detected in compressed data of zip-slip.zip.
   */
  private static final File badFile = new File("src/test/resources/zip-malicious-traversal.zip");
  private static final File badFileBackslashes = new File("src/test/resources/zip-malicious-traversal-backslashes.zip");

  public void testUnpackDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.unpack(badFile, tmpDir);
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }

  public void testUnwrapDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.iterate(badFileBackslashes, new ZipUtil.BackslashUnpacker(tmpDir));
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }
}
Program: CWE-22
Project: CVE-2018-1002203
Buggy source:
None

Fixed version (ground truth):
package org.zeroturnaround.zip;

/**
 *    Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com>
 *
 *    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.
 */
import java.io.File;

import junit.framework.TestCase;

public class DirectoryTraversalMaliciousTest extends TestCase {
  /*
   * This is the contents of the file. There is one evil file that tries to get out of the
   * target.
   *
   * $ unzip -t zip-slip.zip
   * Archive: zip-slip.zip
   * testing: good.txt OK
   * testing: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt OK
   * No errors detected in compressed data of zip-slip.zip.
   */
  private static final File badFile = new File("src/test/resources/zip-malicious-traversal.zip");
  private static final File badFileBackslashes = new File("src/test/resources/zip-malicious-traversal-backslashes.zip");

  public void testUnpackDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.unpack(badFile, tmpDir);
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }

  public void testUnwrapDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.iterate(badFileBackslashes, new ZipUtil.BackslashUnpacker(tmpDir));
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }
}
Program: CWE-22
Project: CVE-2018-1002204
Buggy source:
None

Fixed version (ground truth):
package org.zeroturnaround.zip;

/**
 *    Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com>
 *
 *    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.
 */
import java.io.File;

import junit.framework.TestCase;

public class DirectoryTraversalMaliciousTest extends TestCase {
  /*
   * This is the contents of the file. There is one evil file that tries to get out of the
   * target.
   *
   * $ unzip -t zip-slip.zip
   * Archive: zip-slip.zip
   * testing: good.txt OK
   * testing: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt OK
   * No errors detected in compressed data of zip-slip.zip.
   */
  private static final File badFile = new File("src/test/resources/zip-malicious-traversal.zip");
  private static final File badFileBackslashes = new File("src/test/resources/zip-malicious-traversal-backslashes.zip");

  public void testUnpackDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.unpack(badFile, tmpDir);
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }

  public void testUnwrapDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.iterate(badFileBackslashes, new ZipUtil.BackslashUnpacker(tmpDir));
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }
}
Program: CWE-22
Project: CVE-2018-1002205
Buggy source:
None

Fixed version (ground truth):
package org.zeroturnaround.zip;

/**
 *    Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com>
 *
 *    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.
 */
import java.io.File;

import junit.framework.TestCase;

public class DirectoryTraversalMaliciousTest extends TestCase {
  /*
   * This is the contents of the file. There is one evil file that tries to get out of the
   * target.
   *
   * $ unzip -t zip-slip.zip
   * Archive: zip-slip.zip
   * testing: good.txt OK
   * testing: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt OK
   * No errors detected in compressed data of zip-slip.zip.
   */
  private static final File badFile = new File("src/test/resources/zip-malicious-traversal.zip");
  private static final File badFileBackslashes = new File("src/test/resources/zip-malicious-traversal-backslashes.zip");

  public void testUnpackDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.unpack(badFile, tmpDir);
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }

  public void testUnwrapDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.iterate(badFileBackslashes, new ZipUtil.BackslashUnpacker(tmpDir));
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }
}
Program: CWE-22
Project: CVE-2018-1002206
Buggy source:
None

Fixed version (ground truth):
package org.zeroturnaround.zip;

/**
 *    Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com>
 *
 *    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.
 */
import java.io.File;

import junit.framework.TestCase;

public class DirectoryTraversalMaliciousTest extends TestCase {
  /*
   * This is the contents of the file. There is one evil file that tries to get out of the
   * target.
   *
   * $ unzip -t zip-slip.zip
   * Archive: zip-slip.zip
   * testing: good.txt OK
   * testing: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt OK
   * No errors detected in compressed data of zip-slip.zip.
   */
  private static final File badFile = new File("src/test/resources/zip-malicious-traversal.zip");
  private static final File badFileBackslashes = new File("src/test/resources/zip-malicious-traversal-backslashes.zip");

  public void testUnpackDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.unpack(badFile, tmpDir);
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }

  public void testUnwrapDoesntLeaveTarget() throws Exception {
    File file = File.createTempFile("temp", null);
    File tmpDir = file.getParentFile();

    try {
      ZipUtil.iterate(badFileBackslashes, new ZipUtil.BackslashUnpacker(tmpDir));
      fail();
    }
    catch (ZipException e) {
      assertTrue(true);
    }
  }
}
Program: CWE-22
Project: CVE-2018-20303
Buggy source:
// Copyright 2018 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package tool

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func Test_IsSameSiteURLPath(t *testing.T) {
	Convey("Check if a path belongs to the same site", t, func() {
		testCases := []struct {
			url    string
			expect bool
		}{
			{"//github.com", false},
			{"http://github.com", false},
			{"https://github.com", false},
			{"/\\github.com", false},

			{"/admin", true},
			{"/user/repo", true},
		}

		for _, tc := range testCases {
			So(IsSameSiteURLPath(tc.url), ShouldEqual, tc.expect)
		}
	})
}

func Test_SanitizePath(t *testing.T) {
	Convey("Sanitize malicious user-defined path", t, func() {
		testCases := []struct {
			path   string
			expect string
		}{
			{"../../../../../../../../../data/gogs/data/sessions/a/9/a9f0ab6c3ef63dd8", "data/gogs/data/sessions/a/9/a9f0ab6c3ef63dd8"},

			{"data/sessions/a/9/a9f0ab6c3ef63dd8", "data/sessions/a/9/a9f0ab6c3ef63dd8"},
		}
		for _, tc := range testCases {
			So(SanitizePath(tc.path), ShouldEqual, tc.expect)
		}
	})
}


Fixed version (ground truth):
// Copyright 2018 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package tool

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func Test_IsSameSiteURLPath(t *testing.T) {
	Convey("Check if a path belongs to the same site", t, func() {
		testCases := []struct {
			url    string
			expect bool
		}{
			{"//github.com", false},
			{"http://github.com", false},
			{"https://github.com", false},
			{"/\\github.com", false},

			{"/admin", true},
			{"/user/repo", true},
		}

		for _, tc := range testCases {
			So(IsSameSiteURLPath(tc.url), ShouldEqual, tc.expect)
		}
	})
}

func Test_SanitizePath(t *testing.T) {
	Convey("Sanitize malicious user-defined path", t, func() {
		testCases := []struct {
			path   string
			expect string
		}{
			{"../../../../../../../../../data/gogs/data/sessions/a/9/a9f0ab6c3ef63dd8", "data/gogs/data/sessions/a/9/a9f0ab6c3ef63dd8"},
			{"data/gogs/../../../../../../../../../data/sessions/a/9/a9f0ab6c3ef63dd8", "data/gogs/data/sessions/a/9/a9f0ab6c3ef63dd8"},

			{"data/sessions/a/9/a9f0ab6c3ef63dd8", "data/sessions/a/9/a9f0ab6c3ef63dd8"},
		}
		for _, tc := range testCases {
			So(SanitizePath(tc.path), ShouldEqual, tc.expect)
		}
	})
}
Program: CWE-22
Project: CVE-2018-3715
Buggy source:
{
  "name": "glance",
  "version": "3.0.3",
  "description": "disposable fileserver",
  "main": "index.js",
  "bin": {
    "glance": "./bin/glance.js"
  },
  "scripts": {
    "lint": "standard index.js test/index.js bin/glance.js",
    "test": "node test/index.js && npm run lint"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/jarofghosts/glance.git"
  },
  "keywords": [
    "file",
    "server",
    "utility",
    "util",
    "fileserver"
  ],
  "author": "jesse keane",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/jarofghosts/glance/issues"
  },
  "preferGlobal": true,
  "dependencies": {
    "bash-color": "0.0.3",
    "filed": "0.1.0",
    "html-ls": "1.0.0",
    "nopt": "3.0.4",
    "utils-fs-exists": "1.0.1",
    "xtend": "4.0.0"
  },
  "devDependencies": {
    "eslint": "1.5.1",
    "eslint-config-standard": "4.4.0",
    "eslint-config-standard-react": "^1.1.0",
    "eslint-plugin-react": "^3.4.2",
    "eslint-plugin-standard": "1.3.1",
    "standard": "5.3.1",
    "tape": "4.2.0"
  }
}


Fixed version (ground truth):
{
  "name": "glance",
  "version": "3.0.3",
  "description": "disposable fileserver",
  "main": "index.js",
  "bin": {
    "glance": "./bin/glance.js"
  },
  "scripts": {
    "lint": "standard index.js test/index.js bin/glance.js",
    "test": "node test/index.js && npm run lint"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/jarofghosts/glance.git"
  },
  "keywords": [
    "file",
    "server",
    "utility",
    "util",
    "fileserver"
  ],
  "author": "jesse keane",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/jarofghosts/glance/issues"
  },
  "preferGlobal": true,
  "dependencies": {
    "bash-color": "0.0.3",
    "filed": "0.1.0",
    "html-ls": "1.0.0",
    "mime": "1.2.6",
    "nopt": "3.0.4",
    "utils-fs-exists": "1.0.1",
    "xtend": "4.0.0"
  },
  "devDependencies": {
    "eslint": "1.5.1",
    "eslint-config-standard": "4.4.0",
    "eslint-config-standard-react": "^1.1.0",
    "eslint-plugin-react": "^3.4.2",
    "eslint-plugin-standard": "1.3.1",
    "standard": "5.3.1",
    "tape": "4.2.0"
  }
}
Program: CWE-22
Project: CVE-2019-20916
Buggy source:
None

Fixed version (ground truth):
Prevent ``pip install <url>`` from permitting directory traversal if e.g.
a malicious server sends a ``Content-Disposition`` header with a filename
containing ``../`` or ``..\\``.
Program: CWE-22
Project: CVE-2020-15908
Buggy source:
None

Fixed version (ground truth):
hello.txt
Program: CWE-22
Project: CVE-2020-26299
Buggy source:
const bunyan = require('bunyan');
const fs = require('fs');
const FtpServer = require('../src');

const server = new FtpServer({
  log: bunyan.createLogger({name: 'test', level: 'trace'}),
  url: 'ftp://127.0.0.1:8880',
  pasv_url: '192.168.1.1',
  pasv_min: 8881,
  greeting: ['Welcome', 'to', 'the', 'jungle!'],
  tls: {
    key: fs.readFileSync(`${process.cwd()}/test/cert/server.key`),
    cert: fs.readFileSync(`${process.cwd()}/test/cert/server.crt`),
    ca: fs.readFileSync(`${process.cwd()}/test/cert/server.csr`)
  },
  file_format: 'ep',
  anonymous: 'sillyrabbit'
});
server.on('login', ({username, password}, resolve, reject) => {
  if (username === 'test' && password === 'test' || username === 'anonymous') {
    resolve({root: require('os').homedir()});
  } else reject('Bad username or password');
});
server.listen();


Fixed version (ground truth):
const bunyan = require('bunyan');
const fs = require('fs');
const FtpServer = require('../src');

const server = new FtpServer({
  log: bunyan.createLogger({name: 'test', level: 'trace'}),
  url: 'ftp://127.0.0.1:8880',
  pasv_url: '192.168.1.1',
  pasv_min: 8881,
  greeting: ['Welcome', 'to', 'the', 'jungle!'],
  tls: {
    key: fs.readFileSync(`${__dirname}/cert/server.key`),
    cert: fs.readFileSync(`${__dirname}/cert/server.crt`),
    ca: fs.readFileSync(`${__dirname}/cert/server.csr`)
  },
  file_format: 'ep',
  anonymous: 'sillyrabbit'
});
server.on('login', ({username, password}, resolve, reject) => {
  if (username === 'test' && password === 'test' || username === 'anonymous') {
    resolve({root: __dirname});
  } else reject('Bad username or password');
});
server.listen();
Program: CWE-22
Project: CVE-2020-36193
Buggy source:
None

Fixed version (ground truth):
--TEST--
tests writes to out-of-path filenames
--SKIPIF--
--FILE--
<?php
require_once dirname(__FILE__) . '/setup.php.inc';
$tar = new Archive_Tar(dirname(__FILE__) . '/out_of_path_symlink.tar');
$tar->extract();
$phpunit->assertErrors(array(array('package' => 'PEAR_Error', 'message' => "Out-of-path file extraction {symlink --> /tmp/}")), 'after 1');
$phpunit->assertFileNotExists('symlink/whatever-filename', 'Out-of-path filename should not have succeeded');
echo 'tests done';
?>
--CLEAN--
<?php
@unlink("symlink");
?>
--EXPECT--
tests done
Program: CWE-22
Project: CVE-2021-21234
Buggy source:
language: java
jdk:
  - oraclejdk8

after_success:
  - ./gradlew lib:jacocoTestReport lib:coveralls

Fixed version (ground truth):
language: java
jdk:
  - openjdk8

after_success:
  - ./gradlew lib:jacocoTestReport lib:coveralls
Program: CWE-22
Project: CVE-2021-23407
Buggy source:
﻿namespace elFinder.Net.Core.Models.Command
{
    public class PutCommand : TargetCommand
    {
        public string Content { get; set; }
        public string Encoding { get; set; }
    }
}


Fixed version (ground truth):
﻿namespace elFinder.Net.Core.Models.Command
{
    public class PutCommand : TargetCommand
    {
        public string Content { get; set; }
        public string Encoding { get; set; }

        public PathInfo ContentPath { get; set; }
    }
}
Program: CWE-22
Project: CVE-2021-32633
Buggy source:
from ..expression import getEngine
from . import testHTMLTests


class ChameleonAqPageTemplate(testHTMLTests.AqPageTemplate):
    def pt_getEngine(self):
        return getEngine()


class ChameleonTalesExpressionTests(testHTMLTests.HTMLTests):
    def setUp(self):
        super().setUp()
        # override with templates using chameleon TALES expressions
        self.folder.laf = ChameleonAqPageTemplate()
        self.folder.t = ChameleonAqPageTemplate()

    # override ``PREFIX`` to be able to account for
    #   small differences between ``zope.tales`` and ``chameleon.tales``
    #   expressions (e.g. the ``zope.tales`` ``not`` expression
    #   returns ``int``, that of ``chameleon.tales`` ``bool``
    PREFIX = "CH_"


Fixed version (ground truth):
import unittest

from ..expression import getEngine
from . import testHTMLTests


class ChameleonAqPageTemplate(testHTMLTests.AqPageTemplate):
    def pt_getEngine(self):
        return getEngine()


class ChameleonTalesExpressionTests(testHTMLTests.HTMLTests):
    def setUp(self):
        super().setUp()
        # override with templates using chameleon TALES expressions
        self.folder.laf = ChameleonAqPageTemplate()
        self.folder.t = ChameleonAqPageTemplate()

    # override ``PREFIX`` to be able to account for
    #   small differences between ``zope.tales`` and ``chameleon.tales``
    #   expressions (e.g. the ``zope.tales`` ``not`` expression
    #   returns ``int``, that of ``chameleon.tales`` ``bool``
    PREFIX = "CH_"

    @unittest.skip('The test in the base class relies on a Zope context with'
                   ' the "random" module available in expressions')
    def test_underscore_traversal(self):
        pass
Program: CWE-22
Project: CVE-2021-32804
Buggy source:
None

Fixed version (ground truth):
// unix absolute paths are also absolute on win32, so we use this for both
const { isAbsolute, parse } = require('path').win32

// returns [root, stripped]
module.exports = path => {
  let r = ''
  while (isAbsolute(path)) {
    // windows will think that //x/y/z has a "root" of //x/y/
    const root = path.charAt(0) === '/' ? '/' : parse(path).root
    path = path.substr(root.length)
    r += root
  }
  return [r, path]
}
Program: CWE-22
Project: CVE-2021-32814
Buggy source:
[package]
name = "tsh"
version = "0.5.0"
authors = ["Sayan Nandan <ohsayan@outlook.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libtdb = {path = "../libtdb"}
tokio = {version = "0.3.6", features = ["full"]}
bytes = "0.6.0"
regex = "1.4.2"
lazy_static = "1.4.0"
clap = {version = "2.33.3", features=["yaml"]}

Fixed version (ground truth):
[package]
name = "tsh"
version = "0.5.0"
authors = ["Sayan Nandan <ohsayan@outlook.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libtdb = {path = "../libtdb"}
tokio = {version = "1.2.0", features = ["full"]}
bytes = "1.0.1"
regex = "1.4.3"
lazy_static = "1.4.0"
clap = {version = "2.33.3", features=["yaml"]}
Program: CWE-22
Project: CVE-2021-32840
Buggy source:
None

Fixed version (ground truth):
﻿using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Tar;
using static ICSharpCode.SharpZipLib.Tests.TestSupport.Utils;
using NUnit.Framework;

namespace ICSharpCode.SharpZipLib.Tests.Tar
{
	[TestFixture]
	public class TarArchiveTests
	{
		[Test]
		[Category("Tar")]
		[Category("CreatesTempFile")]
		public void ExtractingContentsWithNonTraversalPathSucceeds()
		{
			Assert.DoesNotThrow(() => ExtractTarOK("output", "test-good", allowTraverse: false));
		}
		
		[Test]
		[Category("Tar")]
		[Category("CreatesTempFile")]
		public void ExtractingContentsWithExplicitlyAllowedTraversalPathSucceeds()
		{
			Assert.DoesNotThrow(() => ExtractTarOK("output", "../file", allowTraverse: true));
		}
		
		[Test]
		[Category("Tar")]
		[Category("CreatesTempFile")]
		[TestCase("output", "../file")]
		[TestCase("output", "../output.txt")]
		public void ExtractingContentsWithDisallowedPathsFails(string outputDir, string fileName)
		{
			Assert.Throws<InvalidNameException>(() => ExtractTarOK(outputDir, fileName, allowTraverse: false));
		}
		
		public void ExtractTarOK(string outputDir, string fileName, bool allowTraverse)
		{
			var fileContent = Encoding.UTF8.GetBytes("file content");
			using var tempDir = new TempDir();
			
			var tempPath = tempDir.Fullpath;
			var extractPath = Path.Combine(tempPath, outputDir);
			var expectedOutputFile = Path.Combine(extractPath, fileName);

			using var archiveStream = new MemoryStream();
			
			Directory.CreateDirectory(extractPath);

			using (var tos = new TarOutputStream(archiveStream, Encoding.UTF8){IsStreamOwner = false})
			{
				var entry = TarEntry.CreateTarEntry(fileName);
				entry.Size = fileContent.Length;
				tos.PutNextEntry(entry);
				tos.Write(fileContent, 0, fileContent.Length);
				tos.CloseEntry();
			}

			archiveStream.Position = 0;

			using (var ta = TarArchive.CreateInputTarArchive(archiveStream, Encoding.UTF8))
			{
				ta.ProgressMessageEvent += (archive, entry, message) 
					=> TestContext.WriteLine($"{entry.Name} {entry.Size} {message}");
				ta.ExtractContents(extractPath, allowTraverse);
			}

			Assert.That(File.Exists(expectedOutputFile));
		}
	}
}
Program: CWE-22
Project: CVE-2021-34363
Buggy source:
import tarfile
import os
from thefuck.utils import for_app
from thefuck.shells import shell


tar_extensions = ('.tar', '.tar.Z', '.tar.bz2', '.tar.gz', '.tar.lz',
                  '.tar.lzma', '.tar.xz', '.taz', '.tb2', '.tbz', '.tbz2',
                  '.tgz', '.tlz', '.txz', '.tz')


def _is_tar_extract(cmd):
    if '--extract' in cmd:
        return True

    cmd = cmd.split()

    return len(cmd) > 1 and 'x' in cmd[1]


def _tar_file(cmd):
    for c in cmd:
        for ext in tar_extensions:
            if c.endswith(ext):
                return (c, c[0:len(c) - len(ext)])


@for_app('tar')
def match(command):
    return ('-C' not in command.script
            and _is_tar_extract(command.script)
            and _tar_file(command.script_parts) is not None)


def get_new_command(command):
    dir = shell.quote(_tar_file(command.script_parts)[1])
    return shell.and_('mkdir -p {dir}', '{cmd} -C {dir}') \
        .format(dir=dir, cmd=command.script)


def side_effect(old_cmd, command):
    with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive:
        for file in archive.getnames():
            try:
                os.remove(file)
            except OSError:
                # does not try to remove directories as we cannot know if they
                # already existed before
                pass


Fixed version (ground truth):
import tarfile
import os
from thefuck.utils import for_app
from thefuck.shells import shell


tar_extensions = ('.tar', '.tar.Z', '.tar.bz2', '.tar.gz', '.tar.lz',
                  '.tar.lzma', '.tar.xz', '.taz', '.tb2', '.tbz', '.tbz2',
                  '.tgz', '.tlz', '.txz', '.tz')


def _is_tar_extract(cmd):
    if '--extract' in cmd:
        return True

    cmd = cmd.split()

    return len(cmd) > 1 and 'x' in cmd[1]


def _tar_file(cmd):
    for c in cmd:
        for ext in tar_extensions:
            if c.endswith(ext):
                return (c, c[0:len(c) - len(ext)])


@for_app('tar')
def match(command):
    return ('-C' not in command.script
            and _is_tar_extract(command.script)
            and _tar_file(command.script_parts) is not None)


def get_new_command(command):
    dir = shell.quote(_tar_file(command.script_parts)[1])
    return shell.and_('mkdir -p {dir}', '{cmd} -C {dir}') \
        .format(dir=dir, cmd=command.script)


def side_effect(old_cmd, command):
    with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive:
        for file in archive.getnames():
            if not os.path.abspath(file).startswith(os.getcwd()):
                # it's unsafe to overwrite files outside of the current directory
                continue

            try:
                os.remove(file)
            except OSError:
                # does not try to remove directories as we cannot know if they
                # already existed before
                pass
Program: CWE-22
Project: CVE-2021-39109
Buggy source:
{
  "name": "atlasboard",
  "version": "1.1.8",
  "ignore": [
    "**/.*",
    "node_modules",
    "assets/third-party",
    "test",
    "tests"
  ],
  "dependencies": {
    "jquery": "~2.1.3",
    "underscore": "~1.8.3",
    "moment": "^2.29.1",
    "gridster": "~0.5.6",
    "spinjs": "~2.0.2",
    "rickshaw": "~1.5.1"
  }
}


Fixed version (ground truth):
{
  "name": "atlasboard",
  "version": "1.1.9",
  "ignore": [
    "**/.*",
    "node_modules",
    "assets/third-party",
    "test",
    "tests"
  ],
  "dependencies": {
    "jquery": "~2.1.3",
    "underscore": "~1.8.3",
    "moment": "^2.29.1",
    "gridster": "~0.5.6",
    "spinjs": "~2.0.2",
    "rickshaw": "~1.5.1"
  }
}
Program: CWE-22
Project: CVE-2021-43813
Buggy source:
None

Fixed version (ground truth):
+++
title = "Release notes for Grafana 7.5.12"
[_build]
list = false
+++

<!-- Auto generated by update changelog github action -->

# Release notes for Grafana 7.5.12

### Bug fixes

- **Security**: Fixes CVE-2021-43813 and CVE-2021-PENDING. For more information, see our [blog](https://grafana.com/blog/2021/12/10/grafana-8.3.2-and-7.5.12-released-with-moderate-severity-security-fix/)
Program: CWE-22
Project: CVE-2022-1992
Buggy source:
// Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package pathutil

import (
	"path"
	"strings"
)

// Clean cleans up given path and returns a relative path that goes straight down.
func Clean(p string) string {
	return strings.Trim(path.Clean("/"+p), "/")
}


Fixed version (ground truth):
// Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package pathutil

import (
	"path"
	"strings"
)

// Clean cleans up given path and returns a relative path that goes straight
// down to prevent path traversal.
func Clean(p string) string {
	p = strings.ReplaceAll(p, `\`, "/")
	return strings.Trim(path.Clean("/"+p), "/")
}
Program: CWE-22
Project: CVE-2022-24774
Buggy source:
2.0.0


Fixed version (ground truth):
2.0.1
Program: CWE-352
Project: CVE-2012-5622
Buggy source:
class ApplicationController < ActionController::Base
  include Console::Rescue

  protect_from_forgery
end


Fixed version (ground truth):
class ApplicationController < ActionController::Base
  include Console::Rescue

  protect_from_forgery

  protected
    def handle_unverified_request
      raise Console::AccessDenied, "Request authenticity token does not match session #{session.inspect}"
    end
end
Program: CWE-352
Project: CVE-2013-4881
Buggy source:
<?
	$admin->requireLevel(1);
	$id = $admin->createUser($_POST);	
	
	if (!$id) {
		$_SESSION["bigtree_admin"]["create_user"] = $_POST;
		$admin->growl("Users","Creation Failed","error");
		BigTree::redirect(ADMIN_ROOT."users/add/");
	}

	$admin->growl("Users","Added User");
	BigTree::redirect(ADMIN_ROOT."users/edit/$id/");
?>

Fixed version (ground truth):
<?
	if ($_SERVER["HTTP_REFERER"] != ADMIN_ROOT."users/add/") {
?>
<div class="container">
	<section>
		<p>To create a user, please access the <a href="<?=ADMIN_ROOT?>users/add/">Add User</a> page.</p>
	</section>
</div>
<?
	} else {
		$admin->requireLevel(1);
		$id = $admin->createUser($_POST);	
		
		if (!$id) {
			$_SESSION["bigtree_admin"]["create_user"] = $_POST;
			$admin->growl("Users","Creation Failed","error");
			BigTree::redirect(ADMIN_ROOT."users/add/");
		}
	
		$admin->growl("Users","Added User");
		BigTree::redirect(ADMIN_ROOT."users/edit/$id/");
	}
?>
Program: CWE-352
Project: CVE-2013-5313
Buggy source:
<?
	$admin->requireLevel(1);
	$id = $admin->createUser($_POST);	
	
	if (!$id) {
		$_SESSION["bigtree_admin"]["create_user"] = $_POST;
		$admin->growl("Users","Creation Failed","error");
		BigTree::redirect(ADMIN_ROOT."users/add/");
	}

	$admin->growl("Users","Added User");
	BigTree::redirect(ADMIN_ROOT."users/edit/$id/");
?>

Fixed version (ground truth):
<?
	if ($_SERVER["HTTP_REFERER"] != ADMIN_ROOT."users/add/") {
?>
<div class="container">
	<section>
		<p>To create a user, please access the <a href="<?=ADMIN_ROOT?>users/add/">Add User</a> page.</p>
	</section>
</div>
<?
	} else {
		$admin->requireLevel(1);
		$id = $admin->createUser($_POST);	
		
		if (!$id) {
			$_SESSION["bigtree_admin"]["create_user"] = $_POST;
			$admin->growl("Users","Creation Failed","error");
			BigTree::redirect(ADMIN_ROOT."users/add/");
		}
	
		$admin->growl("Users","Added User");
		BigTree::redirect(ADMIN_ROOT."users/edit/$id/");
	}
?>
Program: CWE-352
Project: CVE-2014-0168
Buggy source:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright 2009-2013 Roland Huss
  ~
  ~ 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.
  -->

<restrict>

  <cors>
    <allow-origin>*</allow-origin>
  </cors>

</restrict>


Fixed version (ground truth):
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright 2009-2013 Roland Huss
  ~
  ~ 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.
  -->

<restrict>

  <cors>
    <allow-origin>*</allow-origin>

  </cors>

</restrict>
Program: CWE-352
Project: CVE-2015-4619
Buggy source:
module Spina
  class ApplicationController < ActionController::Base
    include ApplicationHelper

    private

    def current_ability
      @current_ability ||= Ability.new(current_user)
    end

    def current_theme
      @current_theme = ::Spina.themes.first
    end
    helper_method :current_theme

    def current_user
      @current_user ||= User.where(id: session[:user_id]).first if session[:user_id]
    end
    helper_method :current_user

    def current_account
      @current_account ||= Account.first
    end
    helper_method :current_account
  end
end


Fixed version (ground truth):
module Spina
  class ApplicationController < ActionController::Base
    protect_from_forgery
    
    include ApplicationHelper

    private

    def current_ability
      @current_ability ||= Ability.new(current_user)
    end

    def current_theme
      @current_theme = ::Spina.themes.first
    end
    helper_method :current_theme

    def current_user
      @current_user ||= User.where(id: session[:user_id]).first if session[:user_id]
    end
    helper_method :current_user

    def current_account
      @current_account ||= Account.first
    end
    helper_method :current_account
  end
end
Program: CWE-352
Project: CVE-2015-5081
Buggy source:
module Spina
  class ApplicationController < ActionController::Base
    include ApplicationHelper

    private

    def current_ability
      @current_ability ||= Ability.new(current_user)
    end

    def current_theme
      @current_theme = ::Spina.themes.first
    end
    helper_method :current_theme

    def current_user
      @current_user ||= User.where(id: session[:user_id]).first if session[:user_id]
    end
    helper_method :current_user

    def current_account
      @current_account ||= Account.first
    end
    helper_method :current_account
  end
end


Fixed version (ground truth):
module Spina
  class ApplicationController < ActionController::Base
    protect_from_forgery
    
    include ApplicationHelper

    private

    def current_ability
      @current_ability ||= Ability.new(current_user)
    end

    def current_theme
      @current_theme = ::Spina.themes.first
    end
    helper_method :current_theme

    def current_user
      @current_user ||= User.where(id: session[:user_id]).first if session[:user_id]
    end
    helper_method :current_user

    def current_account
      @current_account ||= Account.first
    end
    helper_method :current_account
  end
end
Program: CWE-352
Project: CVE-2015-5395
Buggy source:
/* UIxMailAccountActions.h - this file is part of SOGo
 *
 * Copyright (C) 2007-2013 Inverse inc.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#ifndef UIXMAILACCOUNTACTIONS_H
#define UIXMAILACCOUNTACTIONS_H


@class WOResponse;

@interface UIxMailAccountActions : WODirectAction
{
}

- (WOResponse *) listMailboxesAction;

@end

#endif /* UIXMAILACCOUNTACTIONS_H */


Fixed version (ground truth):
/* UIxMailAccountActions.h - this file is part of SOGo
 *
 * Copyright (C) 2007-2016 Inverse inc.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#ifndef UIXMAILACCOUNTACTIONS_H
#define UIXMAILACCOUNTACTIONS_H

#import <UI/Common/SOGoDirectAction.h>

@class WOResponse;

@interface UIxMailAccountActions : SOGoDirectAction
{
}

- (WOResponse *) listMailboxesAction;

@end

#endif /* UIXMAILACCOUNTACTIONS_H */
Program: CWE-352
Project: CVE-2017-1000008
Buggy source:
{% extends "layouts" ~ DIR ~ "default.twig" %}

{% block content %}
<div class="user_controls standalone">
<h2>{{ "Controls" | translate }}</h2>
<form action="{{ url('controls') }}" method="post" accept-charset="UTF-8">
<label for="full_name">{{ "Full name" | translate }}</label>
<input type="text" name="full_name" value="{{ visitor.full_name | fix(true) }}" id="full_name" maxlength="250">
<label for="email">{{ "Email" | translate }}</label>
<input type="email" name="email" value="{{ visitor.email | fix(true) }}" id="email" maxlength="128">
<label for="website">{{ "Website" | translate }}</label>
<input type="url" name="website" value="{{ visitor.website | fix(true) }}" id="website" maxlength="128">
<label for="new_password1">{{ "New password?" | translate }}</label>
<input type="password" name="new_password1" value="" id="new_password1" maxlength="128">
<label for="new_password2">{{ "Confirm" | translate }}</label>
<input type="password" name="new_password2" value="" id="new_password2" maxlength="128">
{{ trigger.call("user_controls") }}
<div class="doaction">
<button name="submit" type="submit" id="submit" tabindex="4">{{ "Update" | translate }}</button>
</div>
</form>
</div>
{% endblock %}


Fixed version (ground truth):
{% extends "layouts" ~ DIR ~ "default.twig" %}

{% block content %}
<div class="user_controls standalone">
<h2>{{ "Controls" | translate }}</h2>
<form action="{{ url('controls') }}" method="post" accept-charset="UTF-8">
<label for="full_name">{{ "Full name" | translate }}</label>
<input type="text" name="full_name" value="{{ visitor.full_name | fix(true) }}" id="full_name" maxlength="250">
<label for="email">{{ "Email" | translate }}</label>
<input type="email" name="email" value="{{ visitor.email | fix(true) }}" id="email" maxlength="128">
<label for="website">{{ "Website" | translate }}</label>
<input type="url" name="website" value="{{ visitor.website | fix(true) }}" id="website" maxlength="128">
<label for="new_password1">{{ "New password?" | translate }}</label>
<input type="password" name="new_password1" value="" id="new_password1" maxlength="128">
<label for="new_password2">{{ "Confirm" | translate }}</label>
<input type="password" name="new_password2" value="" id="new_password2" maxlength="128">
{{ trigger.call("user_controls") }}
<div class="doaction">
<button name="submit" type="submit" id="submit" tabindex="4">{{ "Update" | translate }}</button>
</div>
<input type="hidden" name="hash" value="{{ ip | token }}" id="hash">
</form>
</div>
{% endblock %}
Program: CWE-352
Project: CVE-2017-15733
Buggy source:
<?php

/**
 * AJAX: handles an attachment with the given id.
 *
 * PHP Version 5.5
 *
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/.
 *
 * @category  phpMyFAQ
 *
 * @author    Anatoliy Belsky <anatoliy.belsky@mayflower.de>
 * @copyright 2010-2017 phpMyFAQ Team
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
 *
 * @link      http://www.phpmyfaq.de
 * @since     2010-12-20
 */
if (!defined('IS_VALID_PHPMYFAQ')) {
    $protocol = 'http';
    if (isset($_SERVER['HTTPS']) && strtoupper($_SERVER['HTTPS']) === 'ON') {
        $protocol = 'https';
    }
    header('Location: '.$protocol.'://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']));
    exit();
}

$ajaxAction = PMF_Filter::filterInput(INPUT_GET, 'ajaxaction', FILTER_SANITIZE_STRING);
$attId = PMF_Filter::filterInput(INPUT_GET, 'attId', FILTER_VALIDATE_INT);

$att = PMF_Attachment_Factory::create($attId);

if ($att) {
    switch ($ajaxAction) {
        case 'delete':
            if ($att->delete()) {
                print $PMF_LANG['msgAttachmentsDeleted'];
            } else {
                print $PMF_LANG['ad_att_delfail'];
            }
            break;
    }
}


Fixed version (ground truth):
<?php

/**
 * AJAX: handles an attachment with the given id.
 *
 * PHP Version 5.5
 *
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/.
 *
 * @category  phpMyFAQ
 * @author    Anatoliy Belsky <anatoliy.belsky@mayflower.de>
 * @copyright 2010-2017 phpMyFAQ Team
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
 * @link      http://www.phpmyfaq.de
 * @since     2010-12-20
 */
if (!defined('IS_VALID_PHPMYFAQ')) {
    $protocol = 'http';
    if (isset($_SERVER['HTTPS']) && strtoupper($_SERVER['HTTPS']) === 'ON') {
        $protocol = 'https';
    }
    header('Location: '.$protocol.'://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']));
    exit();
}

$ajaxAction = PMF_Filter::filterInput(INPUT_GET, 'ajaxaction', FILTER_SANITIZE_STRING);
$attId = PMF_Filter::filterInput(INPUT_GET, 'attId', FILTER_VALIDATE_INT);
$csrfToken = PMF_Filter::filterInput(INPUT_GET, 'csrf', FILTER_SANITIZE_STRING);

$att = PMF_Attachment_Factory::create($attId);

if ($att) {
    switch ($ajaxAction) {
        case 'delete':

            if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $csrfToken) {
                echo $PMF_LANG['err_NotAuth'];
                exit(1);
            }

            if ($att->delete()) {
                echo $PMF_LANG['msgAttachmentsDeleted'];
            } else {
                echo $PMF_LANG['ad_att_delfail'];
            }
            break;
    }
}
Program: CWE-352
Project: CVE-2017-5473
Buggy source:
--
-- (C) 2013-17 - ntop.org
--

dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"

sendHTTPHeader('text/html; charset=iso-8859-1')

if(haveAdminPrivileges()) then
   username = _GET["username"]
   full_name = _GET["full_name"]
   password = _GET["password"]
   confirm_password = _GET["confirm_password"]
   host_role = _GET["host_role"]
   networks = _GET["allowed_networks"]
   allowed_interface = _GET["allowed_interface"]
   
   if(username == nil or full_name == nil or password == nil or confirm_password == nil or host_role == nil or networks == nil or allowed_interface == nil) then
      print ("{ \"result\" : -1, \"message\" : \"Invalid parameters\" }")
      return
   end
   
   if(password ~= confirm_password) then
      print ("{ \"result\" : -1, \"message\" : \"Passwords do not match: typo?\" }")
      return
   end
   
   if(ntop.addUser(username, full_name, password, host_role, networks, getInterfaceName(allowed_interface))) then
      print ("{ \"result\" : 0, \"message\" : \"User added successfully\" }")
   else
      print ("{ \"result\" : -1, \"message\" : \"Error while adding new user\" }")
   end
end


Fixed version (ground truth):
--
-- (C) 2013-17 - ntop.org
--

dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"

sendHTTPHeader('text/html; charset=iso-8859-1')

if(_GET["csrf"] ~= nil) then
if(haveAdminPrivileges()) then
   username = _GET["username"]
   full_name = _GET["full_name"]
   password = _GET["password"]
   confirm_password = _GET["confirm_password"]
   host_role = _GET["host_role"]
   networks = _GET["allowed_networks"]
   allowed_interface = _GET["allowed_interface"]
   
   if(username == nil or full_name == nil or password == nil or confirm_password == nil or host_role == nil or networks == nil or allowed_interface == nil) then
      print ("{ \"result\" : -1, \"message\" : \"Invalid parameters\" }")
      return
   end
   
   if(password ~= confirm_password) then
      print ("{ \"result\" : -1, \"message\" : \"Passwords do not match: typo?\" }")
      return
   end
   
   if(ntop.addUser(username, full_name, password, host_role, networks, getInterfaceName(allowed_interface))) then
      print ("{ \"result\" : 0, \"message\" : \"User added successfully\" }")
   else
      print ("{ \"result\" : -1, \"message\" : \"Error while adding new user\" }")
   end
end
end
Program: CWE-352
Project: CVE-2017-6819
Buggy source:
<?php
/**
 * The WordPress version string
 *
 * @global string $wp_version
 */
$wp_version = '4.8-alpha-40183';

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

/**
 * Holds the TinyMCE version
 *
 * @global string $tinymce_version
 */
$tinymce_version = '4403-20160901';

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

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


Fixed version (ground truth):
<?php
/**
 * The WordPress version string
 *
 * @global string $wp_version
 */
$wp_version = '4.8-alpha-40195';

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

/**
 * Holds the TinyMCE version
 *
 * @global string $tinymce_version
 */
$tinymce_version = '4403-20160901';

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

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