input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
|---|---|---|
#vulnerable code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
{
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive the same
List results = new ArrayList();
{
final InputStream is = new FileInputStream(output);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
File result = File.createTempFile("dir-result", "");
result.delete();
result.mkdir();
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outfile);
IOUtils.copy(in, out);
out.close();
results.add(outfile);
}
in.close();
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
} else {
out.close();
}
}
// Unarchive the same
List results = new ArrayList();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream o = new FileOutputStream(outfile);
try {
IOUtils.copy(in, o);
} finally {
o.close();
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
} else {
is.close();
}
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 28
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
tempFileOutputStream.close();
outputStream.close();
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
if(tempFileOutputStream != null) {
tempFileOutputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testBzip2Unarchive() throws Exception {
final File output = new File(dir, "test-entpackt.txt");
System.out.println(dir);
final File input = new File(getClass().getClassLoader().getResource("bla.txt.bz2").getFile());
final InputStream is = new FileInputStream(input);
//final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
final CompressorInputStream in = new BZip2CompressorInputStream(is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCBZip2InputStreamClose()
throws Exception
{
final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" );
final File outputFile = getOutputFile( ".tar.bz2" );
final OutputStream output = new FileOutputStream( outputFile );
CompressUtils.copy( input, output );
shutdownStream( input );
shutdownStream( output );
assertTrue( "Check output file exists." , outputFile.exists() );
final InputStream input2 = new FileInputStream( outputFile );
final InputStream packedInput = getPackedInput( input2 );
shutdownStream( packedInput );
try
{
input2.read();
assertTrue("Source input stream is still opened.", false);
} catch ( Exception e )
{
// Read closed stream.
}
forceDelete( outputFile );
}
#location 13
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCBZip2InputStreamClose()
throws Exception
{
final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" );
final File outputFile = getOutputFile( ".tar.bz2" );
final OutputStream output = new FileOutputStream( outputFile );
CompressUtils.copy( input, output );
IOUtils.closeQuietly( input );
IOUtils.closeQuietly( output );
assertTrue( "Check output file exists." , outputFile.exists() );
final InputStream input2 = new FileInputStream( outputFile );
final InputStream packedInput = getPackedInput( input2 );
IOUtils.closeQuietly( packedInput );
try
{
input2.read();
assertTrue("Source input stream is still opened.", false);
} catch ( Exception e )
{
// Read closed stream.
}
forceDelete( outputFile );
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 22
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testJarUnarchive() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();
File o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 27
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testJarUnarchive() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();
File o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is);
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
#location 18
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
final File output2 = new File(dir, "bla2.ar");
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
}
}
ais.close();
aos.close();
is.close();
os.close();
}
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
}
ais.close();
is.close();
}
assertEquals(76, sum);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
assertEquals(282, output.length());
final File output2 = new File(dir, "bla2.ar");
int copied = 0;
int deleted = 0;
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
aos.closeArchiveEntry();
copied++;
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
deleted++;
}
}
ais.close();
aos.close();
is.close();
os.close();
}
assertEquals(1, copied);
assertEquals(1, deleted);
assertEquals(144, output2.length());
long files = 0;
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
files++;
}
ais.close();
is.close();
}
assertEquals(1, files);
assertEquals(76, sum);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testBzipCreation() throws Exception {
final File output = new File(dir, "bla.txt.bz2");
System.out.println(dir);
final File file1 = new File(getClass().getClassLoader().getResource("test.txt").getFile());
final OutputStream out = new FileOutputStream(output);
CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
IOUtils.copy(new FileInputStream(file1), cos);
cos.close();
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testBzipCreation() throws Exception {
final File input = getFile("test.txt");
final File output = new File(dir, "test.txt.bz2");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
IOUtils.copy(new FileInputStream(input), cos);
cos.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 16
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
try {
File temp = File.createTempFile("test", "." + archivename);
final OutputStream stream = new FileOutputStream(temp);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return temp;
} finally {
if (out != null)
out.close();
}
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
File temp = File.createTempFile("test", "." + archivename);
stream = new FileOutputStream(temp);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return temp;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testJarUnarchiveAll() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ArchiveEntry entry = in.getNextEntry();
while (entry != null) {
File archiveEntry = new File(dir, entry.getName());
archiveEntry.getParentFile().mkdirs();
if(entry.isDirectory()){
archiveEntry.mkdir();
entry = in.getNextEntry();
continue;
}
OutputStream out = new FileOutputStream(archiveEntry);
IOUtils.copy(in, out);
out.close();
entry = in.getNextEntry();
}
in.close();
}
#location 21
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testJarUnarchiveAll() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ArchiveEntry entry = in.getNextEntry();
while (entry != null) {
File archiveEntry = new File(dir, entry.getName());
archiveEntry.getParentFile().mkdirs();
if(entry.isDirectory()){
archiveEntry.mkdir();
entry = in.getNextEntry();
continue;
}
OutputStream out = new FileOutputStream(archiveEntry);
IOUtils.copy(in, out);
out.close();
entry = in.getNextEntry();
}
in.close();
is.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
os2.closeArchiveEntry();
}
}
#location 43
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
stream = new FileOutputStream(archive);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
#location 21
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
archiveList = new ArrayList();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
addArchiveEntry(out, "testdata/test1.xml", file1);
addArchiveEntry(out, "testdata/test2.xml", file2);
addArchiveEntry(out, "test/test3.xml", file3);
addArchiveEntry(out, "bla/test4.xml", file4);
addArchiveEntry(out, "bla/test5.xml", file4);
addArchiveEntry(out, "bla/blubber/test6.xml", file4);
addArchiveEntry(out, "test.txt", file5);
addArchiveEntry(out, "something/bla", file6);
addArchiveEntry(out, "test with spaces.txt", file6);
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
FileInputStream in = new FileInputStream(file1);
IOUtils.copy(in, os);
os.closeArchiveEntry();
os.close();
out.close();
in.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
os2.close();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is);
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 31
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is);
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testGzipCreation() throws Exception {
final File output = new File(dir, "bla.gz");
final File file1 = new File(getClass().getClassLoader().getResource("test1.xml").getFile());
final OutputStream out = new FileOutputStream(output);
CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
IOUtils.copy(new FileInputStream(file1), cos);
cos.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testGzipCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.gz");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
IOUtils.copy(new FileInputStream(input), cos);
cos.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
FileOutputStream os = new FileOutputStream(output);
IOUtils.copy(in, os);
is.close();
os.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected void checkArchiveContent(File archive, List expected)
throws Exception {
final InputStream is = new FileInputStream(archive);
try {
final BufferedInputStream buf = new BufferedInputStream(is);
final ArchiveInputStream in =
archive.getName().endsWith(".tar") ? // tar does not autodetect at present
factory.createArchiveInputStream("tar", buf) :
factory.createArchiveInputStream(buf);
this.checkArchiveContent(in, expected);
} finally {
is.close();
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected void checkArchiveContent(File archive, List expected)
throws Exception {
final InputStream is = new FileInputStream(archive);
try {
final BufferedInputStream buf = new BufferedInputStream(is);
final ArchiveInputStream in = factory.createArchiveInputStream(buf);
this.checkArchiveContent(in, expected);
} finally {
is.close();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
{
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive the same
List results = new ArrayList();
{
final InputStream is = new FileInputStream(output);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
File result = File.createTempFile("dir-result", "");
result.delete();
result.mkdir();
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outfile);
IOUtils.copy(in, out);
out.close();
results.add(outfile);
}
in.close();
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
} else {
out.close();
}
}
// Unarchive the same
List results = new ArrayList();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream o = new FileOutputStream(outfile);
try {
IOUtils.copy(in, o);
} finally {
o.close();
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
} else {
is.close();
}
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
#location 10
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
CpioArchiveEntry entry = new CpioArchiveEntry("test1.xml", file1.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
entry = new CpioArchiveEntry("test2.xml", file2.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
stream = new FileOutputStream(archive);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
#location 27
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
archiveList = new ArrayList();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
addArchiveEntry(out, "testdata/test1.xml", file1);
addArchiveEntry(out, "testdata/test2.xml", file2);
addArchiveEntry(out, "test/test3.xml", file3);
addArchiveEntry(out, "bla/test4.xml", file4);
addArchiveEntry(out, "bla/test5.xml", file4);
addArchiveEntry(out, "bla/blubber/test6.xml", file4);
addArchiveEntry(out, "test.txt", file5);
addArchiveEntry(out, "something/bla", file6);
addArchiveEntry(out, "test with spaces.txt", file6);
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 10
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
#location 14
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
CpioArchiveEntry entry = new CpioArchiveEntry("test1.xml", file1.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
entry = new CpioArchiveEntry("test2.xml", file2.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testBzipCreation() throws Exception {
final File input = getFile("test.txt");
final File output = new File(dir, "test.txt.bz2");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
IOUtils.copy(new FileInputStream(input), cos);
cos.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testBzipCreation() throws Exception {
final File input = getFile("test.txt");
final File output = new File(dir, "test.txt.bz2");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
FileInputStream in = new FileInputStream(input);
IOUtils.copy(in, cos);
cos.close();
in.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
final File output2 = new File(dir, "bla2.ar");
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
}
}
ais.close();
aos.close();
is.close();
os.close();
}
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
}
ais.close();
is.close();
}
assertEquals(76, sum);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
assertEquals(282, output.length());
final File output2 = new File(dir, "bla2.ar");
int copied = 0;
int deleted = 0;
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
aos.closeArchiveEntry();
copied++;
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
deleted++;
}
}
ais.close();
aos.close();
is.close();
os.close();
}
assertEquals(1, copied);
assertEquals(1, deleted);
assertEquals(144, output2.length());
long files = 0;
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
files++;
}
ais.close();
is.close();
}
assertEquals(1, files);
assertEquals(76, sum);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testBzip2Unarchive() throws Exception {
final File output = new File(dir, "test-entpackt.txt");
System.out.println(dir);
final File input = new File(getClass().getClassLoader().getResource("bla.txt.bz2").getFile());
final InputStream is = new FileInputStream(input);
//final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
final CompressorInputStream in = new BZip2CompressorInputStream(is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 10
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
{
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive the same
List results = new ArrayList();
{
final InputStream is = new FileInputStream(output);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
File result = File.createTempFile("dir-result", "");
result.delete();
result.mkdir();
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outfile);
IOUtils.copy(in, out);
out.close();
results.add(outfile);
}
in.close();
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
#location 18
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
} else {
out.close();
}
}
// Unarchive the same
List results = new ArrayList();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream o = new FileOutputStream(outfile);
try {
IOUtils.copy(in, o);
} finally {
o.close();
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
} else {
is.close();
}
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected File createEmptyArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
archiveList = new ArrayList();
try {
archive = File.createTempFile("empty", "." + archivename);
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
return archive;
}
#location 11
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected File createEmptyArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
archiveList = new ArrayList();
try {
archive = File.createTempFile("empty", "." + archivename);
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
out.finish();
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
return archive;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
final File output2 = new File(dir, "bla2.ar");
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
}
}
ais.close();
aos.close();
is.close();
os.close();
}
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
}
ais.close();
is.close();
}
assertEquals(76, sum);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
assertEquals(282, output.length());
final File output2 = new File(dir, "bla2.ar");
int copied = 0;
int deleted = 0;
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
aos.closeArchiveEntry();
copied++;
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
deleted++;
}
}
ais.close();
aos.close();
is.close();
os.close();
}
assertEquals(1, copied);
assertEquals(1, deleted);
assertEquals(144, output2.length());
long files = 0;
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
files++;
}
ais.close();
is.close();
}
assertEquals(1, files);
assertEquals(76, sum);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
stream = new FileOutputStream(archive);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
#location 33
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
archiveList = new ArrayList();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
addArchiveEntry(out, "testdata/test1.xml", file1);
addArchiveEntry(out, "testdata/test2.xml", file2);
addArchiveEntry(out, "test/test3.xml", file3);
addArchiveEntry(out, "bla/test4.xml", file4);
addArchiveEntry(out, "bla/test5.xml", file4);
addArchiveEntry(out, "bla/blubber/test6.xml", file4);
addArchiveEntry(out, "test.txt", file5);
addArchiveEntry(out, "something/bla", file6);
addArchiveEntry(out, "test with spaces.txt", file6);
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
{
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive the same
List results = new ArrayList();
{
final InputStream is = new FileInputStream(output);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
File result = File.createTempFile("dir-result", "");
result.delete();
result.mkdir();
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outfile);
IOUtils.copy(in, out);
out.close();
results.add(outfile);
}
in.close();
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
} else {
out.close();
}
}
// Unarchive the same
List results = new ArrayList();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream o = new FileOutputStream(outfile);
try {
IOUtils.copy(in, o);
} finally {
o.close();
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
} else {
is.close();
}
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
#location 36
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
tempFileOutputStream.close();
outputStream.close();
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
if(tempFileOutputStream != null) {
tempFileOutputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testGzipUnarchive() throws Exception {
final File input = getFile("bla.tgz");
final File output = new File(dir, "bla.tar");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("gz", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testGzipUnarchive() throws Exception {
final File input = getFile("bla.tgz");
final File output = new File(dir, "bla.tar");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("gz", is);
FileOutputStream out = new FileOutputStream(output);
IOUtils.copy(in, out);
in.close();
is.close();
out.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
final File output2 = new File(dir, "bla2.ar");
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
}
}
ais.close();
aos.close();
is.close();
os.close();
}
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
}
ais.close();
is.close();
}
assertEquals(76, sum);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
assertEquals(282, output.length());
final File output2 = new File(dir, "bla2.ar");
int copied = 0;
int deleted = 0;
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
aos.closeArchiveEntry();
copied++;
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
deleted++;
}
}
ais.close();
aos.close();
is.close();
os.close();
}
assertEquals(1, copied);
assertEquals(1, deleted);
assertEquals(144, output2.length());
long files = 0;
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
files++;
}
ais.close();
is.close();
}
assertEquals(1, files);
assertEquals(76, sum);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@PreAuthorize("isAuthenticated()")
public String fetchNewToken(Optional<Long> expirationMillis,
Optional<String> optionalUsername) {
SpringUser<ID> springUser = LemonUtils.getSpringUser();
String username = optionalUsername.orElse(springUser.getUsername());
LemonUtils.ensureAuthority(springUser.getUsername().equals(username) ||
springUser.isGoodAdmin(), "com.naturalprogrammer.spring.notGoodAdminOrSameUser");
return LemonSecurityConfig.TOKEN_PREFIX +
jwtService.createToken(JwtService.AUTH_AUDIENCE, username,
expirationMillis.orElse(properties.getJwt().getExpirationMillis()));
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@PreAuthorize("isAuthenticated()")
public String fetchNewToken(Optional<Long> expirationMillis,
Optional<String> optionalUsername) {
UserDto<ID> currentUser = LemonUtils.currentUser();
String username = optionalUsername.orElse(currentUser.getUsername());
LemonUtils.ensureAuthority(currentUser.getUsername().equals(username) ||
currentUser.isGoodAdmin(), "com.naturalprogrammer.spring.notGoodAdminOrSameUser");
return LemonSecurityConfig.TOKEN_PREFIX +
jwtService.createToken(JwtService.AUTH_AUDIENCE, username,
expirationMillis.orElse(properties.getJwt().getExpirationMillis()));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getSessionUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getSessionUser().getUserDto());
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto());
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getBean(SaService.class).userForClient()));
clearAuthenticationAttributes(request);
//log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public U fetchUser(@Valid @Email @NotNull String email) {
SaUser loggedIn = SaUtil.getSessionUser();
U user = userRepository.findByEmail(email);
if (user == null) {
////////////////// throw SaFormException
}
user.setPassword(null);
if (loggedIn == null || loggedIn.getId() != user.getId() && !loggedIn.isAdmin())
user.setEmail("Confidential");
return user;
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public U fetchUser(@Valid @Email @NotNull String email) {
SaUser loggedIn = SaUtil.getSessionUser();
U user = userRepository.findByEmail(email);
if (user == null) {
throw new FormException("email", "userNotFound");
}
user.setPassword(null);
if (loggedIn == null || loggedIn.getId() != user.getId() && !loggedIn.isAdmin())
user.setEmail("Confidential");
return user;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@UserEditPermission
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public String changePassword(U user, @Valid ChangePasswordForm changePasswordForm) {
log.debug("Changing password for user: " + user);
// Get the old password of the logged in user (logged in user may be an ADMIN)
SpringUser<ID> springUser = LemonUtils.getSpringUser();
U loggedIn = userRepository.findById(springUser.getId()).get();
String oldPassword = loggedIn.getPassword();
// checks
LemonUtils.ensureFound(user);
LemonUtils.validate("changePasswordForm.oldPassword",
passwordEncoder.matches(changePasswordForm.getOldPassword(),
oldPassword),
"com.naturalprogrammer.spring.wrong.password").go();
// sets the password
user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword()));
user.setCredentialsUpdatedMillis(System.currentTimeMillis());
userRepository.save(user);
// // after successful commit
// LemonUtils.afterCommit(() -> {
//
// SpringUser<ID> currentUser = LemonUtils.getSpringUser();
//
//// if (currentUser.getId().equals(user.getId())) { // if current-user's password changed,
////
//// log.debug("Logging out ...");
//// LemonUtils.logOut(); // log him out
//// }
// });
//
log.debug("Changed password for user: " + user);
return user.toSpringUser().getUsername();
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@UserEditPermission
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public String changePassword(U user, @Valid ChangePasswordForm changePasswordForm) {
log.debug("Changing password for user: " + user);
// Get the old password of the logged in user (logged in user may be an ADMIN)
UserDto<ID> currentUser = LemonUtils.currentUser();
U loggedIn = userRepository.findById(currentUser.getId()).get();
String oldPassword = loggedIn.getPassword();
// checks
LemonUtils.ensureFound(user);
LemonUtils.validate("changePasswordForm.oldPassword",
passwordEncoder.matches(changePasswordForm.getOldPassword(),
oldPassword),
"com.naturalprogrammer.spring.wrong.password").go();
// sets the password
user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword()));
user.setCredentialsUpdatedMillis(System.currentTimeMillis());
userRepository.save(user);
// // after successful commit
// LemonUtils.afterCommit(() -> {
//
// UserDto<ID> currentUser = LemonUtils.getSpringUser();
//
//// if (currentUser.getId().equals(user.getId())) { // if current-user's password changed,
////
//// log.debug("Logging out ...");
//// LemonUtils.logOut(); // log him out
//// }
// });
//
log.debug("Changed password for user: " + user);
return user.toUserDto().getUsername();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto());
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getBean(SaService.class).userForClient()));
clearAuthenticationAttributes(request);
//log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public SpringUser<ID> loginWithNonce(@Valid NonceForm<ID> nonce, HttpServletResponse response) {
U user = userRepository.findById(nonce.getUserId())
.orElseThrow(MultiErrorException.supplier(
"com.naturalprogrammer.spring.userNotFound"));
if (user.getNonce().equals(nonce.getNonce())) {
user.setNonce(null);
userRepository.save(user);
jwtService.addJwtAuthHeader(response, user.getId().toString(), properties.getJwt().getExpirationMilli());
return user.toSpringUser();
}
throw MultiErrorException.supplier("com.naturalprogrammer.spring.invalidNonce").get();
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public SpringUser<ID> loginWithNonce(@Valid NonceForm<ID> nonce, HttpServletResponse response) {
U user = userRepository.findById(nonce.getUserId())
.orElseThrow(MultiErrorException.supplier(
"com.naturalprogrammer.spring.userNotFound"));
if (user.getNonce().equals(nonce.getNonce())) {
user.setNonce(null);
userRepository.save(user);
jwtService.addJwtAuthHeader(response, user.toSpringUser().getUsername(), properties.getJwt().getExpirationMilli());
return user.toSpringUser();
}
throw MultiErrorException.supplier("com.naturalprogrammer.spring.invalidNonce").get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void hideConfidentialFields() {
password = null; // JsonIgnore didn't work because of JsonIgnore
//verificationCode = null;
//forgotPasswordCode = null;
if (!hasPermission(LemonUtils.getSpringUser(), Permission.EDIT))
email = null;
log.debug("Hid confidential fields for user: " + this);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void hideConfidentialFields() {
password = null; // JsonIgnore didn't work because of JsonIgnore
//verificationCode = null;
//forgotPasswordCode = null;
if (!hasPermission(LemonUtils.currentUser(), Permission.EDIT))
email = null;
log.debug("Hid confidential fields for user: " + this);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public U fetchUser(@Valid @Email @NotBlank String email) {
log.debug("Fetching user by email: " + email);
U user = userRepository.findByEmail(email);
LemonUtil.check("email", user != null,
"com.naturalprogrammer.spring.userNotFound").go();
user.decorate().hideConfidentialFields();
log.debug("Returning user: " + user);
return user;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public U fetchUser(@Valid @Email @NotBlank String email) {
log.debug("Fetching user by email: " + email);
U user = userRepository.findByEmail(email)
.orElseThrow(() -> MultiErrorException.of("email",
"com.naturalprogrammer.spring.userNotFound"));
user.decorate().hideConfidentialFields();
log.debug("Returning user: " + user);
return user;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected String determineTargetUrl(HttpServletRequest request,
HttpServletResponse response) {
SpringUser<ID> springUser = LemonUtils.getSpringUser();
String shortLivedAuthToken = jwtService.createToken(
JwtService.AUTH_AUDIENCE,
springUser.getUsername(),
(long) properties.getJwt().getShortLivedMillis());
String targetUrl = LemonUtils.fetchCookie(request,
HttpCookieOAuth2AuthorizationRequestRepository.LEMON_REDIRECT_URI_COOKIE_PARAM_NAME)
.map(Cookie::getValue)
.orElse(properties.getOauth2AuthenticationSuccessUrl());
HttpCookieOAuth2AuthorizationRequestRepository.deleteCookies(request, response);
return targetUrl + shortLivedAuthToken;
//
// return properties.getApplicationUrl()
// + "/social-login-success?token="
// + shortLivedAuthToken;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
protected String determineTargetUrl(HttpServletRequest request,
HttpServletResponse response) {
UserDto<ID> currentUser = LemonUtils.currentUser();
String shortLivedAuthToken = jwtService.createToken(
JwtService.AUTH_AUDIENCE,
currentUser.getUsername(),
(long) properties.getJwt().getShortLivedMillis());
String targetUrl = LemonUtils.fetchCookie(request,
HttpCookieOAuth2AuthorizationRequestRepository.LEMON_REDIRECT_URI_COOKIE_PARAM_NAME)
.map(Cookie::getValue)
.orElse(properties.getOauth2AuthenticationSuccessUrl());
HttpCookieOAuth2AuthorizationRequestRepository.deleteCookies(request, response);
return targetUrl + shortLivedAuthToken;
//
// return properties.getApplicationUrl()
// + "/social-login-success?token="
// + shortLivedAuthToken;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void resetPassword(String forgotPasswordCode, @Valid @Password String newPassword) {
log.debug("Resetting password ...");
U user = userRepository.findByForgotPasswordCode(forgotPasswordCode);
LemonUtil.check(user != null, "com.naturalprogrammer.spring.invalidLink").go();
user.setPassword(passwordEncoder.encode(newPassword));
user.setForgotPasswordCode(null);
userRepository.save(user);
log.debug("Password reset.");
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void resetPassword(String forgotPasswordCode, @Valid @Password String newPassword) {
log.debug("Resetting password ...");
U user = userRepository
.findByForgotPasswordCode(forgotPasswordCode)
.orElseThrow(() -> MultiErrorException.of(
"com.naturalprogrammer.spring.invalidLink"));
user.setPassword(passwordEncoder.encode(newPassword));
user.setForgotPasswordCode(null);
userRepository.save(user);
log.debug("Password reset.");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@PreAuthorize("hasPermission(#user, 'edit')")
@Validated(BaseUser.UpdateValidation.class)
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public U updateUser(U user, @Valid U updatedUser) {
SaUtil.validate(user != null, "userNotFound");
user.setName(updatedUser.getName());
if (user.isRolesEditable()) {
Set<String> roles = user.getRoles();
if (updatedUser.isUnverified())
roles.add(Role.UNVERIFIED);
else
roles.remove(Role.UNVERIFIED);
if (updatedUser.isAdmin())
roles.add(Role.ADMIN);
else
roles.remove(Role.ADMIN);
if (updatedUser.isBlocked())
roles.add(Role.BLOCKED);
else
roles.remove(Role.BLOCKED);
}
//user.setVersion(updatedUser.getVersion());
userRepository.save(user);
U loggedIn = SaUtil.getLoggedInUser();
if (loggedIn.equals(user)) {
loggedIn.setName(user.getName());
loggedIn.setRoles(user.getRoles());
}
return userForClient(loggedIn);
}
#location 32
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@PreAuthorize("hasPermission(#user, 'edit')")
@Validated(BaseUser.UpdateValidation.class)
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public U updateUser(U user, @Valid U updatedUser) {
SaUtil.validate(user != null, "userNotFound");
SaUtil.validateVersion(user, updatedUser);
U loggedIn = SaUtil.getLoggedInUser();
updateUserFields(user, updatedUser, loggedIn);
userRepository.save(user);
return userForClient(loggedIn);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void forgotPassword(@Valid @Email @NotBlank String email) {
log.debug("Processing forgot password for email: " + email);
final U user = userRepository.findByEmail(email);
LemonUtil.check(user != null, "com.naturalprogrammer.spring.userNotFound").go();
user.setForgotPasswordCode(UUID.randomUUID().toString());
userRepository.save(user);
LemonUtil.afterCommit(() -> {
mailForgotPasswordLink(user);
});
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void forgotPassword(@Valid @Email @NotBlank String email) {
log.debug("Processing forgot password for email: " + email);
U user = userRepository.findByEmail(email)
.orElseThrow(() -> MultiErrorException.of(
"com.naturalprogrammer.spring.userNotFound"));
user.setForgotPasswordCode(UUID.randomUUID().toString());
userRepository.save(user);
LemonUtil.afterCommit(() -> {
mailForgotPasswordLink(user);
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getSessionUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getSessionUser().getUserDto());
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String args[]) throws IOException, ClassNotFoundException {
File obfuscatedFile;
JarFile jarFile = new JarFile(obfuscatedFile = new File("helloWorld-obf.jar"));
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = {new URL("jar:file:" + obfuscatedFile.getAbsolutePath() + "!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls);
Class c = null;
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
// -6 because of .class
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
System.out.println(className);
if (className.equals("Test")) {
c = cl.loadClass(className);
}
}
Objects.requireNonNull(c);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String args[]) {
System.out.println(test());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void transformPost(JObfImpl inst, HashMap<String, ClassNode> nodes) {
if (!enabled.getObject()) return;
HashMap<String, String> mappings = new HashMap<>();
mappings.clear();
List<ClassWrapper> classWrappers = new ArrayList<>();
System.out.println("Building Hierarchy");
for (ClassNode value : nodes.values()) {
ClassWrapper cw = new ClassWrapper(value, false, new byte[0]);
classWrappers.add(cw);
JObfImpl.INSTANCE.buildHierarchy(cw, null);
}
System.out.println("Finished building hierarchy");
long current = System.currentTimeMillis();
JObf.log.info("Generating mappings...");
NameUtils.setup("", "", "", true);
AtomicInteger classCounter = new AtomicInteger();
classWrappers.forEach(classWrapper -> {
boolean excluded = this.excluded(classWrapper);
for (MethodWrapper method : classWrapper.methods) {
method.methodNode.access &= ~Opcodes.ACC_PRIVATE;
method.methodNode.access &= ~Opcodes.ACC_PROTECTED;
method.methodNode.access |= Opcodes.ACC_PUBLIC;
}
for (FieldWrapper fieldWrapper : classWrapper.fields) {
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PRIVATE;
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PROTECTED;
fieldWrapper.fieldNode.access |= Opcodes.ACC_PUBLIC;
}
if (excluded) return;
classWrapper.methods.stream().filter(methodWrapper -> !Modifier.isNative(methodWrapper.methodNode.access)
&& !methodWrapper.methodNode.name.equals("main") && !methodWrapper.methodNode.name.equals("premain")
&& !methodWrapper.methodNode.name.startsWith("<")).forEach(methodWrapper -> {
// if (!excluded) {
// }
if (canRenameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName)) {
this.renameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName, NameUtils.generateMethodName(classWrapper.originalName, methodWrapper.originalDescription));
}
});
classWrapper.fields.forEach(fieldWrapper -> {
// if (!excluded) {
// }
if (canRenameFieldTree(mappings, new HashSet<>(), fieldWrapper, classWrapper.originalName)) {
this.renameFieldTree(new HashSet<>(), fieldWrapper, classWrapper.originalName, NameUtils.generateFieldName(classWrapper.originalName), mappings);
}
});
classWrapper.classNode.access &= ~Opcodes.ACC_PRIVATE;
classWrapper.classNode.access &= ~Opcodes.ACC_PROTECTED;
classWrapper.classNode.access |= Opcodes.ACC_PUBLIC;
putMapping(mappings, classWrapper.originalName, (repackage)
? repackageName + '/' + NameUtils.generateClassName() : NameUtils.generateClassName());
classCounter.incrementAndGet();
});
try {
FileOutputStream outStream = new FileOutputStream("mappings.txt");
PrintStream printStream = new PrintStream(outStream);
for (Map.Entry<String, String> stringStringEntry : mappings.entrySet()) {
printStream.println(stringStringEntry.getKey() + " -> " + stringStringEntry.getValue());
}
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
JObf.log.info(String.format("Finished generating mappings (%dms)", (System.currentTimeMillis() - current)));
JObf.log.info("Applying mappings...");
current = System.currentTimeMillis();
Remapper simpleRemapper = new MemberRemapper(mappings);
for (ClassWrapper classWrapper : classWrappers) {
ClassNode classNode = classWrapper.classNode;
ClassNode copy = new ClassNode();
classNode.accept(new ClassRemapper(copy, simpleRemapper));
for (int i = 0; i < copy.methods.size(); i++) {
classWrapper.methods.get(i).methodNode = copy.methods.get(i);
/*for (AbstractInsnNode insn : methodNode.instructions.toArray()) { // TODO: Fix lambdas + interface
if (insn instanceof InvokeDynamicInsnNode) {
InvokeDynamicInsnNode indy = (InvokeDynamicInsnNode) insn;
if (indy.bsm.getOwner().equals("java/lang/invoke/LambdaMetafactory")) {
Handle handle = (Handle) indy.bsmArgs[1];
String newName = mappings.get(handle.getOwner() + '.' + handle.getName() + handle.getDesc());
if (newName != null) {
indy.name = newName;
indy.bsm = new Handle(handle.getTag(), handle.getOwner(), newName, handle.getDesc(), false);
}
}
}
}*/
}
if (copy.fields != null) {
for (int i = 0; i < copy.fields.size(); i++) {
classWrapper.fields.get(i).fieldNode = copy.fields.get(i);
}
}
classWrapper.classNode = copy;
JObfImpl.classes.remove(classWrapper.originalName + ".class");
JObfImpl.classes.put(classWrapper.classNode.name + ".class", classWrapper.classNode);
// JObfImpl.INSTANCE.getClassPath().put();
// this.getClasses().put(classWrapper.classNode.name, classWrapper);
JObfImpl.INSTANCE.getClassPath().put(classWrapper.classNode.name, classWrapper);
}
JObf.log.info(String.format("Finished applying mappings (%dms)", (System.currentTimeMillis() - current)));
}
#location 79
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void transformPost(JObfImpl inst, HashMap<String, ClassNode> nodes) {
if (!enabled.getObject()) return;
HashMap<String, String> mappings = new HashMap<>();
mappings.clear();
List<ClassWrapper> classWrappers = new ArrayList<>();
JObf.log.info("Building Hierarchy...");
for (ClassNode value : nodes.values()) {
ClassWrapper cw = new ClassWrapper(value, false, new byte[0]);
classWrappers.add(cw);
JObfImpl.INSTANCE.buildHierarchy(cw, null);
}
JObf.log.info("Finished building hierarchy");
long current = System.currentTimeMillis();
JObf.log.info("Generating mappings...");
NameUtils.setup("", "", "", true);
AtomicInteger classCounter = new AtomicInteger();
classWrappers.forEach(classWrapper -> {
boolean excluded = this.excluded(classWrapper);
for (MethodWrapper method : classWrapper.methods) {
method.methodNode.access &= ~Opcodes.ACC_PRIVATE;
method.methodNode.access &= ~Opcodes.ACC_PROTECTED;
method.methodNode.access |= Opcodes.ACC_PUBLIC;
}
for (FieldWrapper fieldWrapper : classWrapper.fields) {
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PRIVATE;
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PROTECTED;
fieldWrapper.fieldNode.access |= Opcodes.ACC_PUBLIC;
}
if (excluded) return;
classWrapper.methods.stream().filter(methodWrapper -> !Modifier.isNative(methodWrapper.methodNode.access)
&& !methodWrapper.methodNode.name.equals("main") && !methodWrapper.methodNode.name.equals("premain")
&& !methodWrapper.methodNode.name.startsWith("<")).forEach(methodWrapper -> {
// if (!excluded) {
// }
if (canRenameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName)) {
this.renameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName, NameUtils.generateMethodName(classWrapper.originalName, methodWrapper.originalDescription));
}
});
classWrapper.fields.forEach(fieldWrapper -> {
// if (!excluded) {
// }
if (canRenameFieldTree(mappings, new HashSet<>(), fieldWrapper, classWrapper.originalName)) {
this.renameFieldTree(new HashSet<>(), fieldWrapper, classWrapper.originalName, NameUtils.generateFieldName(classWrapper.originalName), mappings);
}
});
classWrapper.classNode.access &= ~Opcodes.ACC_PRIVATE;
classWrapper.classNode.access &= ~Opcodes.ACC_PROTECTED;
classWrapper.classNode.access |= Opcodes.ACC_PUBLIC;
putMapping(mappings, classWrapper.originalName, (repackage)
? repackageName + '/' + NameUtils.generateClassName() : NameUtils.generateClassName());
classCounter.incrementAndGet();
});
// try {
// FileOutputStream outStream = new FileOutputStream("mappings.txt");
// PrintStream printStream = new PrintStream(outStream);
//
// for (Map.Entry<String, String> stringStringEntry : mappings.entrySet()) {
// printStream.println(stringStringEntry.getKey() + " -> " + stringStringEntry.getValue());
// }
//
// outStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
JObf.log.info(String.format("Finished generating mappings (%dms)", (System.currentTimeMillis() - current)));
JObf.log.info("Applying mappings...");
current = System.currentTimeMillis();
Remapper simpleRemapper = new MemberRemapper(mappings);
for (ClassWrapper classWrapper : classWrappers) {
ClassNode classNode = classWrapper.classNode;
ClassNode copy = new ClassNode();
classNode.accept(new ClassRemapper(copy, simpleRemapper));
for (int i = 0; i < copy.methods.size(); i++) {
classWrapper.methods.get(i).methodNode = copy.methods.get(i);
/*for (AbstractInsnNode insn : methodNode.instructions.toArray()) { // TODO: Fix lambdas + interface
if (insn instanceof InvokeDynamicInsnNode) {
InvokeDynamicInsnNode indy = (InvokeDynamicInsnNode) insn;
if (indy.bsm.getOwner().equals("java/lang/invoke/LambdaMetafactory")) {
Handle handle = (Handle) indy.bsmArgs[1];
String newName = mappings.get(handle.getOwner() + '.' + handle.getName() + handle.getDesc());
if (newName != null) {
indy.name = newName;
indy.bsm = new Handle(handle.getTag(), handle.getOwner(), newName, handle.getDesc(), false);
}
}
}
}*/
}
if (copy.fields != null) {
for (int i = 0; i < copy.fields.size(); i++) {
classWrapper.fields.get(i).fieldNode = copy.fields.get(i);
}
}
classWrapper.classNode = copy;
JObfImpl.classes.remove(classWrapper.originalName + ".class");
JObfImpl.classes.put(classWrapper.classNode.name + ".class", classWrapper.classNode);
// JObfImpl.INSTANCE.getClassPath().put();
// this.getClasses().put(classWrapper.classNode.name, classWrapper);
JObfImpl.INSTANCE.getClassPath().put(classWrapper.classNode.name, classWrapper);
}
JObf.log.info(String.format("Finished applying mappings (%dms)", (System.currentTimeMillis() - current)));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static BasicAttributeInfo newAttributeInfo(ConstantPool constantPool, short attributeNameIndex) {
BasicAttributeInfo basicAttributeInfo = null;
String attributeName = null;
ConstantPoolInfo constantPoolInfo = constantPool.getCpInfo()[attributeNameIndex - 1];
if (constantPoolInfo instanceof ConstantUtf8Info) {
attributeName = ((ConstantUtf8Info) constantPoolInfo).getValue();
}
if (attributeName.equals("Code")) {
basicAttributeInfo = new Code(constantPool, attributeNameIndex);
} else if (attributeName.equals("ConstantValue")) {
basicAttributeInfo = new ConstantValue(constantPool, attributeNameIndex);
} else if (attributeName.equals("Deprecated")) {
basicAttributeInfo = new Deprecated(constantPool, attributeNameIndex);
} else if (attributeName.equals("Exceptions")) {
basicAttributeInfo = new Exceptions(constantPool, attributeNameIndex);
} else if (attributeName.equals("LineNumberTable")) {
basicAttributeInfo = new LineNumberTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("LocalVariableTable")) {
basicAttributeInfo = new LocalVariableTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("SourceFile")) {
basicAttributeInfo = new SourceFile(constantPool, attributeNameIndex);
} else if (attributeName.equals("Synthetic")) {
basicAttributeInfo = new Synthetic(constantPool, attributeNameIndex);
}
basicAttributeInfo.setAttributeNameIndex(attributeNameIndex);
return basicAttributeInfo;
}
#location 25
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static BasicAttributeInfo newAttributeInfo(ConstantPool constantPool, short attributeNameIndex) {
BasicAttributeInfo basicAttributeInfo = null;
String attributeName = null;
ConstantPoolInfo constantPoolInfo = constantPool.getCpInfo()[attributeNameIndex - 1];
if (constantPoolInfo instanceof ConstantUtf8Info) {
attributeName = ((ConstantUtf8Info) constantPoolInfo).getValue();
}
System.out.println("attributeName = " + attributeName);
if (attributeName.equals("Code")) {
basicAttributeInfo = new Code(constantPool, attributeNameIndex);
} else if (attributeName.equals("ConstantValue")) {
basicAttributeInfo = new ConstantValue(constantPool, attributeNameIndex);
} else if (attributeName.equals("Deprecated")) {
basicAttributeInfo = new Deprecated(constantPool, attributeNameIndex);
} else if (attributeName.equals("Exceptions")) {
basicAttributeInfo = new Exceptions(constantPool, attributeNameIndex);
} else if (attributeName.equals("LineNumberTable")) {
basicAttributeInfo = new LineNumberTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("LocalVariableTable")) {
basicAttributeInfo = new LocalVariableTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("LocalVariableTypeTable")) {
basicAttributeInfo = new LocalVariableTypeTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("SourceFile")) {
basicAttributeInfo = new SourceFile(constantPool, attributeNameIndex);
} else if (attributeName.equals("Synthetic")) {
basicAttributeInfo = new Synthetic(constantPool, attributeNameIndex);
} else if (attributeName.equals("Signature")) {
basicAttributeInfo = new Signature(constantPool, attributeNameIndex);
} else if (attributeName.equals("BootstrapMethods")) {
basicAttributeInfo = new BootstrapMethods(constantPool, attributeNameIndex);
} else if (attributeName.equals("InnerClasses")) {
basicAttributeInfo = new InnerClasses(constantPool, attributeNameIndex);
} else {
basicAttributeInfo = new Unparsed(constantPool, attributeNameIndex);
}
basicAttributeInfo.setAttributeNameIndex(attributeNameIndex);
return basicAttributeInfo;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private String[] fileToStringArray (File f, String encoding)
{
ArrayList<String> wordarray = new ArrayList<String>();
try {
BufferedReader input = null;
if (encoding == null) {
input = new BufferedReader (new FileReader (f));
}
else {
input = new BufferedReader( new InputStreamReader( new FileInputStream(f), encoding ));
}
String line;
while (( line = input.readLine()) != null) {
String[] words = line.split ("\\s+");
for (int i = 0; i < words.length; i++)
wordarray.add (words[i]);
}
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
return (String[]) wordarray.toArray(new String[]{});
}
#location 22
#vulnerability type RESOURCE_LEAK
|
#fixed code
private String[] fileToStringArray (File f, String encoding)
{
try {
return streamToStringArray(new FileInputStream(f), encoding);
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void printState (PrintStream out) {
Alphabet a = instances.getDataAlphabet();
out.println ("#doc pos typeindex type topic");
for (int di = 0; di < topics.length; di++) {
FeatureSequence fs = (FeatureSequence) instances.get(di).getData();
for (int token = 0; token < topics[di].length; token++) {
int type = fs.getIndexAtPosition(token);
out.print(di); out.print(' ');
out.print(token); out.print(' ');
out.print(type); out.print(' ');
out.print(a.lookupObject(type)); out.print(' ');
out.print(topics[di][token]); out.println();
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void printState (PrintStream out) {
Alphabet alphabet = instances.getDataAlphabet();
out.println ("#doc pos typeindex type topic");
for (int doc = 0; doc < topics.size(); doc++) {
FeatureSequence tokenSequence =
(FeatureSequence) instances.get(doc).getData();
FeatureSequence topicSequence =
(FeatureSequence) instances.get(doc).getData();
for (int token = 0; token < topicSequence.getLength(); token++) {
int type = tokenSequence.getIndexAtPosition(token);
int topic = topicSequence.getIndexAtPosition(token);
out.print(doc); out.print(' ');
out.print(token); out.print(' ');
out.print(type); out.print(' ');
out.print(alphabet.lookupObject(type)); out.print(' ');
out.print(topic); out.println();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private String[] fileToStringArray (File f, String encoding)
{
ArrayList<String> wordarray = new ArrayList<String>();
try {
BufferedReader input = null;
if (encoding == null) {
input = new BufferedReader (new FileReader (f));
}
else {
input = new BufferedReader( new InputStreamReader( new FileInputStream(f), encoding ));
}
String line;
while (( line = input.readLine()) != null) {
String[] words = line.split ("\\s+");
for (int i = 0; i < words.length; i++)
wordarray.add (words[i]);
}
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
return (String[]) wordarray.toArray(new String[]{});
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
private String[] fileToStringArray (File f, String encoding)
{
try {
return streamToStringArray(new FileInputStream(f), encoding);
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static HprofByteBuffer createHprofByteBuffer(File dumpFile)
throws IOException {
long fileLen = dumpFile.length();
if (fileLen < MINIMAL_SIZE) {
String errText = "File size is too small";
throw new IOException(errText);
}
try {
if (fileLen < Integer.MAX_VALUE) {
return new HprofMappedByteBuffer(dumpFile);
} else {
return new HprofLongMappedByteBuffer(dumpFile);
}
} catch (IOException ex) {
if (ex.getCause() instanceof OutOfMemoryError) { // can happen on 32bit Windows, since there is only 2G for memory mapped data for whole java process.
return new HprofFileBuffer(dumpFile);
}
throw ex;
}
}
#location 18
#vulnerability type RESOURCE_LEAK
|
#fixed code
static HprofByteBuffer createHprofByteBuffer(File dumpFile)
throws IOException {
long fileLen = dumpFile.length();
if (fileLen < MINIMAL_SIZE) {
String errText = "File size is too small";
throw new IOException(errText);
}
try {
if (fileLen < Integer.MAX_VALUE) {
return new HprofMappedByteBuffer(dumpFile);
} else {
return new HprofLongMappedByteBuffer(dumpFile);
}
} catch (IOException ex) {
if (ex.getCause() instanceof OutOfMemoryError) { // can happen on 32bit Windows, since there is only 2G for memory mapped data for whole java process.
return new PagedFileHprofByteBuffer(new RandomAccessFile(dumpFile, "r"), 4 << 20, 16);
}
throw ex;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static String stringValue(Instance obj) {
if (obj == null) {
return null;
}
if (!"java.lang.String".equals(obj.getJavaClass().getName())) {
throw new IllegalArgumentException("Is not a string: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")");
}
char[] text = null;
int offset = 0;
int len = -1;
for(FieldValue f: obj.getFieldValues()) {
Field ff = f.getField();
if ("value".equals(ff.getName())) {
PrimitiveArrayInstance chars = (PrimitiveArrayInstance) ((ObjectFieldValue)f).getInstance();
text = new char[chars.getLength()];
for(int i = 0; i != text.length; ++i) {
text[i] = ((String)chars.getValues().get(i)).charAt(0);
}
}
// fields below were removed in Java 7
else if ("offset".equals(ff.getName())) {
offset = Integer.valueOf(f.getValue());
}
else if ("count".equals(ff.getName())) {
len = Integer.valueOf(f.getValue());
}
}
if (len < 0) {
len = text.length;
}
return new String(text, offset, len);
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static String stringValue(Instance obj) {
if (obj == null) return null;
if (!"java.lang.String".equals(obj.getJavaClass().getName()))
throw new IllegalArgumentException("Is not a string: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")");
Boolean COMPACT_STRINGS = (Boolean) obj.getJavaClass().getValueOfStaticField("COMPACT_STRINGS");
if (COMPACT_STRINGS == null)
return stringValue_java8(obj); // We're pre Java 9
Object valueInstance = obj.getValueOfField("value");
PrimitiveArrayInstance chars = (PrimitiveArrayInstance) valueInstance;
byte UTF16 = 1;
byte coder = COMPACT_STRINGS ? (Byte) obj.getValueOfField("coder") : UTF16;
int len = chars.getLength() >> coder;
char[] text = new char[len];
List<String> values = (List) chars.getValues();
if (coder == UTF16)
for (int i = 0; i < text.length; i++) {
text[i] = (char)
((Integer.parseInt(values.get(i*2+1)) << 8)
| (Integer.parseInt(values.get(i*2)) & 0xFF));
}
else
for (int i = 0; i < text.length; i++)
text[i] = (char) Integer.parseInt(values.get(i));
return new String(text);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void addNonCachedMetricsListener(CuratorFramework curatorFramework) {
nonCachedMetricsIPRWLock = new InterProcessReadWriteLock(curatorFramework, NON_CACHED_METRICS_LOCK_PATH);
testIPRWLock(curatorFramework, nonCachedMetricsIPRWLock, NON_CACHED_METRICS_LOCK_PATH);
nonCachedMetricsIP = new DistributedAtomicValue(curatorFramework, NON_CACHED_METRICS, new RetryForever(1000));
TreeCacheListener nonCachedMetricsListener = new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
LOG.info("Handling nonCachedMetricsIP event {}", event.getType().toString());
readNonCachedMetricsIP();
}
}
};
try {
TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS);
nonCachedMetricsTreeCache.getListenable().addListener(nonCachedMetricsListener);
nonCachedMetricsTreeCache.start();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void addNonCachedMetricsListener(CuratorFramework curatorFramework) {
nonCachedMetricsIPRWLock = new InterProcessReadWriteLock(curatorFramework, NON_CACHED_METRICS_LOCK_PATH);
testIPRWLock(curatorFramework, nonCachedMetricsIPRWLock, NON_CACHED_METRICS_LOCK_PATH);
nonCachedMetricsIP = new DistributedAtomicValue(curatorFramework, NON_CACHED_METRICS, new RetryForever(1000));
TreeCacheListener nonCachedMetricsListener = new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
LOG.info("Handling nonCachedMetricsIP event {}", event.getType().toString());
readNonCachedMetricsIP();
}
}
};
try (TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS)) {
nonCachedMetricsTreeCache.getListenable().addListener(nonCachedMetricsListener);
nonCachedMetricsTreeCache.start();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@ReadOperation
public HaloMetricResponse HaloMetric() {
HaloMetricResponse haloMetricResponse=new HaloMetricResponse();
MetricResponse jvmThreadsLive=metric("jvm.threads.live",null);
haloMetricResponse.setJvmThreadslive(String.valueOf(jvmThreadsLive.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedHeap=metric("jvm.memory.used", Arrays.asList("area:heap") );
haloMetricResponse.setJvmMemoryUsedHeap(String.valueOf(jvmNemoryUsedHeap.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedNonHeap=metric("jvm.memory.used", Arrays.asList("area:nonheap") );
haloMetricResponse.setJvmMemoryUsedNonHeap(String.valueOf(jvmNemoryUsedNonHeap.getMeasurements().get(0).getValue()));
MetricResponse systemLoadAverage=metric("system.load.average.1m", null );
haloMetricResponse.setSystemloadAverage(String.valueOf(systemLoadAverage.getMeasurements().get(0).getValue()));
MetricResponse heapCommitted=metric("jvm.memory.committed", Arrays.asList("area:heap") );
haloMetricResponse.setHeapCommitted(String.valueOf(heapCommitted.getMeasurements().get(0).getValue()));
MetricResponse nonheapCommitted=metric("jvm.memory.committed", Arrays.asList("area:nonheap") );
haloMetricResponse.setNonheapCommitted(String.valueOf(nonheapCommitted.getMeasurements().get(0).getValue()));
MetricResponse heapMax=metric("jvm.memory.max", Arrays.asList("area:heap") );
haloMetricResponse.setHeapMax(String.valueOf(heapMax.getMeasurements().get(0).getValue()));
getGcinfo(haloMetricResponse);
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getHeapMemoryUsage();
haloMetricResponse.setHeapInit(String.valueOf(memoryUsage.getInit()));
Runtime runtime = Runtime.getRuntime();
haloMetricResponse.setProcessors(String.valueOf(runtime.availableProcessors()));
return haloMetricResponse;
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@ReadOperation
public HaloMetricResponse HaloMetric() {
HaloMetricResponse haloMetricResponse=new HaloMetricResponse();
MetricResponse jvmThreadsLive=metric("jvm.threads.live",null);
haloMetricResponse.setJvmThreadslive(String.valueOf(jvmThreadsLive.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedHeap=metric("jvm.memory.used", Arrays.asList("area:heap") );
haloMetricResponse.setJvmMemoryUsedHeap(String.valueOf(jvmNemoryUsedHeap.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedNonHeap=metric("jvm.memory.used", Arrays.asList("area:nonheap") );
haloMetricResponse.setJvmMemoryUsedNonHeap(String.valueOf(jvmNemoryUsedNonHeap.getMeasurements().get(0).getValue()));
// 2.0 actuator/metrics 中没有这个key
MetricResponse systemLoadAverage=metric("system.load.average.1m", null );
if(systemLoadAverage!=null){
haloMetricResponse.setSystemloadAverage(String.valueOf(systemLoadAverage.getMeasurements().get(0).getValue()));
}
MetricResponse heapCommitted=metric("jvm.memory.committed", Arrays.asList("area:heap") );
haloMetricResponse.setHeapCommitted(String.valueOf(heapCommitted.getMeasurements().get(0).getValue()));
MetricResponse nonheapCommitted=metric("jvm.memory.committed", Arrays.asList("area:nonheap") );
haloMetricResponse.setNonheapCommitted(String.valueOf(nonheapCommitted.getMeasurements().get(0).getValue()));
MetricResponse heapMax=metric("jvm.memory.max", Arrays.asList("area:heap") );
haloMetricResponse.setHeapMax(String.valueOf(heapMax.getMeasurements().get(0).getValue()));
getGcinfo(haloMetricResponse);
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getHeapMemoryUsage();
haloMetricResponse.setHeapInit(String.valueOf(memoryUsage.getInit()));
Runtime runtime = Runtime.getRuntime();
haloMetricResponse.setProcessors(String.valueOf(runtime.availableProcessors()));
return haloMetricResponse;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void track1FormatTest() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("564C42353231313131313131313131313131315E202F2020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("08/2016");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getHolderFirstname()).isNull();
Assertions.assertThat(card.getTrack1().getHolderLastname()).isNull();
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void track1FormatTest() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42353231313131313131313131313131315E202F2020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("08/2016");
Assertions.assertThat(track1.getHolderFirstname()).isNull();
Assertions.assertThat(track1.getHolderLastname()).isNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void track1Test() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("70 75 9F 6C 02 00 01 9F 62 06 00 00 00 38 00 00 9F 63 06 00 00 00 00 E0 E0 56 34 42343131313131313131313131313131313f305e202f5e31373032323031313030333f313030313030303030303030303030303f30303030 9F 64 01 03 9F 65 02 1C 00 9F 66 02 03 F0 9F 6B 13 5566887766556677 D1 81 02 01 00 00 00 00 00 10 0F 9F 67 01 03 90 00"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void track1Test() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42343131313131313131313131313131313F305E202F5E31373032323031313030333F313030313030303030303030303030303F"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void track1FormatNullUser() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("564C42353231313131313131313131313131315E22202020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("08/2016");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getHolderFirstname()).isNull();
Assertions.assertThat(card.getTrack1().getHolderLastname()).isNull();
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void track1FormatNullUser() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42353231313131313131313131313131315E22202020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(track1.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("08/2016");
Assertions.assertThat(track1.getHolderFirstname()).isNull();
Assertions.assertThat(track1.getHolderLastname()).isNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void track1NameTest() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("563A42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F30303030"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getHolderFirstname()).isEqualTo("John");
Assertions.assertThat(card.getTrack1().getHolderLastname()).isEqualTo("Doe");
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void track1NameTest() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getHolderFirstname()).isEqualTo("John");
Assertions.assertThat(track1.getHolderLastname()).isEqualTo("Doe");
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRefs()
{
List<String> failed = TestInference.testAll("tests", false);
String msg = "";
for (String fail : failed)
{
msg += "[failed] " + fail;
}
assertTrue("Some tests failed :\n" + msg, failed == null);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testRefs()
{
List<String> failed = TestInference.testAll("tests", false);
if (failed != null)
{
String msg = "Some tests failed. " +
"\nLook at 'failed_refs.json' in corresponding directories for details.";
msg += "\n----------------------------= FAILED TESTS --------------------------=";
for (String fail : failed)
{
msg += "\n - " + fail;
}
msg += "\n----------------------------------------------------------------------";
fail(msg);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "&";
break;
default:
System.err.println("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "@";
break;
default:
Util.msg("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getFirstNode().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getFirstNode();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getSingle().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getSingle();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void buildTupleType() {
Scope bt = BaseTuple.getTable();
String[] tuple_methods = {
"__add__", "__contains__", "__eq__", "__ge__", "__getnewargs__",
"__gt__", "__iter__", "__le__", "__len__", "__lt__", "__mul__",
"__ne__", "__new__", "__rmul__", "count", "index"
};
for (String m : tuple_methods) {
bt.update(m, newLibUrl("stdtypes"), newFunc(), METHOD);
}
Binding b = bt.update("__getslice__", newDataModelUrl("object.__getslice__"),
newFunc(), METHOD);
b.markDeprecated();
bt.update("__getitem__", newDataModelUrl("object.__getitem__"), newFunc(), METHOD);
bt.update("__iter__", newDataModelUrl("object.__iter__"), newFunc(), METHOD);
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
String[] list(String... names) {
return names;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void setAttrType(@NotNull Type targetType, @NotNull Type v) {
if (targetType.isUnknownType()) {
Analyzer.self.putProblem(this, "Can't set attribute for UnknownType");
return;
}
// new attr, mark the type as "mutated"
if (targetType.table.lookupAttr(attr.id) == null ||
!targetType.table.lookupAttrType(attr.id).equals(v))
{
targetType.setMutated(true);
}
targetType.table.insert(attr.id, attr, v, ATTRIBUTE);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void setAttrType(@NotNull Type targetType, @NotNull Type v) {
if (targetType.isUnknownType()) {
Analyzer.self.putProblem(this, "Can't set attribute for UnknownType");
return;
}
targetType.table.insert(attr.id, attr, v, ATTRIBUTE);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int compareTo(@NotNull Object o) {
return getFirstNode().getStart() - ((Binding)o).getFirstNode().getStart();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public int compareTo(@NotNull Object o) {
return getSingle().getStart() - ((Binding)o).getSingle().getStart();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
boolean checkBindingExist(List<Binding> bs, String name, String file, int start) {
if (bs == null) {
return false;
}
for (Binding b : bs) {
String actualFile = b.getFile();
if (b.getName().equals(name) &&
actualFile.equals(file) &&
b.getStart() == start)
{
return true;
}
}
return false;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
boolean checkBindingExist(List<Binding> bs, String file, int start, int end) {
if (bs == null) {
return false;
}
for (Binding b : bs) {
if (((b.getFile() == null && file == null) ||
(b.getFile() != null && file != null && b.getFile().equals(file))) &&
b.start == start && b.end == end)
{
return true;
}
}
return false;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void restrictNumType(Compare compare, Scope s1, Scope s2) {
List<Node> ops = compare.ops;
if (ops.size() > 0 && ops.get(0) instanceof Op) {
String opname = ((Op) ops.get(0)).name;
Node left = compare.left;
Node right = compare.comparators.get(0);
if (!left.isName()) {
Node tmp = right;
right = left;
left = tmp;
opname = Op.invert(opname);
}
if (left.isName()) {
Name leftName = left.asName();
Type leftType = left.resolve(s1);
Type rightType = right.resolve(s1);
NumType trueType = Analyzer.self.builtins.BaseNum;
NumType falseType = Analyzer.self.builtins.BaseNum;
if (opname.equals("<") || opname.equals("<=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newUpper = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setUpper(newUpper.getUpper());
falseType = new NumType(leftType.asNumType());
falseType.setLower(newUpper.getUpper());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else if (opname.equals(">") || opname.equals(">=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newLower = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setLower(newLower.getLower());
falseType = new NumType(leftType.asNumType());
falseType.setUpper(newLower.getLower());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else {
trueType = leftType.asNumType();
}
Binding b = s1.lookup(leftName.id).get(0);
s1.update(leftName.id, new Binding(leftName.id, b.getNode(), trueType, Binding.Kind.SCOPE));
s2.update(leftName.id, new Binding(leftName.id, b.getNode(), falseType, Binding.Kind.SCOPE));
}
}
}
#location 46
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void restrictNumType(Compare compare, Scope s1, Scope s2) {
List<Node> ops = compare.ops;
if (ops.size() > 0 && ops.get(0) instanceof Op) {
Op op = ((Op) ops.get(0));
String opname = op.name;
if (op.isNumberComparisonOp()) {
Node left = compare.left;
Node right = compare.comparators.get(0);
if (!left.isName()) {
Node tmp = right;
right = left;
left = tmp;
opname = Op.invert(opname);
}
if (left.isName()) {
Name leftName = left.asName();
Type leftType = left.resolve(s1);
Type rightType = right.resolve(s1);
NumType trueType = Analyzer.self.builtins.BaseNum;
NumType falseType = Analyzer.self.builtins.BaseNum;
if (opname.equals("<") || opname.equals("<=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newUpper = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setUpper(newUpper.getUpper());
falseType = new NumType(leftType.asNumType());
falseType.setLower(newUpper.getUpper());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else if (opname.equals(">") || opname.equals(">=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newLower = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setLower(newLower.getLower());
falseType = new NumType(leftType.asNumType());
falseType.setUpper(newLower.getLower());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
}
Node loc;
List<Binding> bs = s1.lookup(leftName.id);
if (bs != null && bs.size() > 0) {
loc = bs.get(0).getNode();
} else {
loc = leftName;
}
s1.update(leftName.id, new Binding(leftName.id, loc, trueType, Binding.Kind.SCOPE));
s2.update(leftName.id, new Binding(leftName.id, loc, falseType, Binding.Kind.SCOPE));
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Nullable
public Process startInterpreter(String pythonExe) {
String jsonizeStr;
Process p;
try {
InputStream jsonize =
Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(dumpPythonResource);
jsonizeStr = _.readWholeStream(jsonize);
} catch (Exception e) {
_.die("Failed to open resource file:" + dumpPythonResource);
return null;
}
try {
FileWriter fw = new FileWriter(jsonizer);
fw.write(jsonizeStr);
fw.close();
} catch (Exception e) {
_.die("Failed to write into: " + jsonizer);
return null;
}
try {
ProcessBuilder builder = new ProcessBuilder(pythonExe, "-i", jsonizer);
builder.redirectErrorStream(true);
builder.redirectError(new File(parserLog));
builder.redirectOutput(new File(parserLog));
builder.environment().remove("PYTHONPATH");
p = builder.start();
} catch (Exception e) {
_.die("Failed to start Python");
return null;
}
return p;
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Nullable
public Process startInterpreter(String pythonExe) {
Process p;
try {
URL url = Thread.currentThread().getContextClassLoader().getResource(dumpPythonResource);
FileUtils.copyURLToFile(url, new File(jsonizer));
} catch (Exception e) {
_.die("Failed to copy resource file:" + dumpPythonResource);
return null;
}
try {
ProcessBuilder builder = new ProcessBuilder(pythonExe, "-i", jsonizer);
builder.redirectErrorStream(true);
builder.redirectError(new File(parserLog));
builder.redirectOutput(new File(parserLog));
builder.environment().remove("PYTHONPATH");
p = builder.start();
} catch (Exception e) {
_.die("Failed to start Python");
return null;
}
return p;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void bindIter(@NotNull Scope s, Node target, @NotNull Node iter, Binding.Kind kind) {
Type iterType = Node.resolveExpr(iter, s);
if (iterType.isListType()) {
bind(s, target, iterType.asListType().getElementType(), kind);
} else if (iterType.isTupleType()) {
bind(s, target, iterType.asTupleType().toListType().getElementType(), kind);
} else {
List<Binding> ents = iterType.getTable().lookupAttr("__iter__");
for (Binding ent : ents) {
if (ent == null || !ent.getType().isFuncType()) {
if (!iterType.isUnknownType()) {
iter.addWarning("not an iterable type: " + iterType);
}
bind(s, target, Indexer.idx.builtins.unknown, kind);
} else {
bind(s, target, ent.getType().asFuncType().getReturnType(), kind);
}
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void bindIter(@NotNull Scope s, Node target, @NotNull Node iter, Binding.Kind kind) {
Type iterType = Node.resolveExpr(iter, s);
if (iterType.isListType()) {
bind(s, target, iterType.asListType().getElementType(), kind);
} else if (iterType.isTupleType()) {
bind(s, target, iterType.asTupleType().toListType().getElementType(), kind);
} else {
List<Binding> ents = iterType.getTable().lookupAttr("__iter__");
if (ents != null) {
for (Binding ent : ents) {
if (ent.getType().isFuncType()) {
bind(s, target, ent.getType().asFuncType().getReturnType(), kind);
} else {
iter.addWarning("not an iterable type: " + iterType);
bind(s, target, Indexer.idx.builtins.unknown, kind);
}
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@NotNull
@Override
public Type transform(State s) {
Type ltype = transformExpr(left, s);
Type rtype;
// boolean operations
if (op == Op.And) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS1());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() && rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() || rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State falseState = State.merge(ltype.asBool().getS2(), rtype.asBool().getS2());
return new BoolType(rtype.asBool().getS1(), falseState);
} else {
return Analyzer.self.builtins.BaseBool;
}
}
if (op == Op.Or) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS2());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() || rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() && rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State trueState = State.merge(ltype.asBool().getS1(), rtype.asBool().getS1());
return new BoolType(trueState, rtype.asBool().getS2());
} else {
return Analyzer.self.builtins.BaseBool;
}
}
rtype = transformExpr(right, s);
if (ltype.isUnknownType() || rtype.isUnknownType()) {
return Analyzer.self.builtins.unknown;
}
// Don't do specific things about string types at the moment
if (ltype == Analyzer.self.builtins.BaseStr && rtype == Analyzer.self.builtins.BaseStr) {
return Analyzer.self.builtins.BaseStr;
}
// try to figure out actual result
if (ltype.isNumType() && rtype.isNumType()) {
NumType leftNum = ltype.asNumType();
NumType rightNum = rtype.asNumType();
if (op == Op.Add) {
return NumType.add(leftNum, rightNum);
}
if (op == Op.Sub) {
return NumType.sub(leftNum, rightNum);
}
if (op == Op.Mul) {
return NumType.mul(leftNum, rightNum);
}
if (op == Op.Div) {
return NumType.div(leftNum, rightNum);
}
// comparison
if (op == Op.Lt || op == Op.Gt) {
Node leftNode = left;
NumType trueType, falseType;
Op op1 = op;
if (!left.isName()) {
leftNode = right;
NumType tmpNum = rightNum;
rightNum = leftNum;
leftNum = tmpNum;
op1 = Op.invert(op1);
}
if (op1 == Op.Lt) {
if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l < r, then l's upper bound is r's upper bound
trueType = new NumType(leftNum);
trueType.setUpper(rightNum.getUpper());
// false branch: if l > r, then l's lower bound is r's lower bound
falseType = new NumType(leftNum);
falseType.setLower(rightNum.getLower());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
if (op1 == Op.Gt) {
if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// undecided, need to transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l > r, then l's lower bound is r's lower bound
trueType = new NumType(leftNum);
trueType.setLower(rightNum.getLower());
// false branch: if l < r, then l's upper bound is r's upper bound
falseType = new NumType(leftNum);
falseType.setUpper(rightNum.getUpper());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
}
}
Analyzer.self.putProblem(this, "operator " + op + " cannot be applied on operands " + ltype + " and " + rtype);
return ltype;
}
#location 115
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@NotNull
@Override
public Type transform(State s) {
Type ltype = transformExpr(left, s);
Type rtype;
// boolean operations
if (op == Op.And) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS1());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() && rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() || rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State falseState = State.merge(ltype.asBool().getS2(), rtype.asBool().getS2());
return new BoolType(rtype.asBool().getS1(), falseState);
} else {
return Analyzer.self.builtins.BaseBool;
}
}
if (op == Op.Or) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS2());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() || rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() && rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State trueState = State.merge(ltype.asBool().getS1(), rtype.asBool().getS1());
return new BoolType(trueState, rtype.asBool().getS2());
} else {
return Analyzer.self.builtins.BaseBool;
}
}
rtype = transformExpr(right, s);
if (ltype.isUnknownType() || rtype.isUnknownType()) {
return Analyzer.self.builtins.unknown;
}
// Don't do specific things about string types at the moment
if (ltype == Analyzer.self.builtins.BaseStr && rtype == Analyzer.self.builtins.BaseStr) {
return Analyzer.self.builtins.BaseStr;
}
// try to figure out actual result
if (ltype.isIntType() && rtype.isIntType()) {
IntType leftNum = ltype.asIntType();
IntType rightNum = rtype.asIntType();
if (op == Op.Add) {
return IntType.add(leftNum, rightNum);
}
if (op == Op.Sub) {
return IntType.sub(leftNum, rightNum);
}
if (op == Op.Mul) {
return IntType.mul(leftNum, rightNum);
}
if (op == Op.Div) {
return IntType.div(leftNum, rightNum);
}
// comparison
if (op == Op.Lt || op == Op.Gt) {
Node leftNode = left;
IntType trueType, falseType;
Op op1 = op;
if (!left.isName()) {
leftNode = right;
IntType tmpNum = rightNum;
rightNum = leftNum;
leftNum = tmpNum;
op1 = Op.invert(op1);
}
if (op1 == Op.Lt) {
if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l < r, then l's upper bound is r's upper bound
trueType = new IntType(leftNum);
trueType.setUpper(rightNum.getUpper());
// false branch: if l > r, then l's lower bound is r's lower bound
falseType = new IntType(leftNum);
falseType.setLower(rightNum.getLower());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
if (op1 == Op.Gt) {
if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// undecided, need to transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l > r, then l's lower bound is r's lower bound
trueType = new IntType(leftNum);
trueType.setLower(rightNum.getLower());
// false branch: if l < r, then l's upper bound is r's upper bound
falseType = new IntType(leftNum);
falseType.setUpper(rightNum.getUpper());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
}
}
Analyzer.self.putProblem(this, "operator " + op + " cannot be applied on operands " + ltype + " and " + rtype);
return ltype;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void buildFunctionType() {
Scope t = BaseFunction.getTable();
for (String s : list("func_doc", "__doc__", "func_name", "__name__", "__module__")) {
t.update(s, new Url(DATAMODEL_URL), BaseStr, ATTRIBUTE);
}
Binding b = synthetic(t, "func_closure", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
b.markReadOnly();
synthetic(t, "func_code", new Url(DATAMODEL_URL), unknown(), ATTRIBUTE);
synthetic(t, "func_defaults", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
synthetic(t, "func_globals", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
synthetic(t, "func_dict", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
// Assume any function can become a method, for simplicity.
for (String s : list("__func__", "im_func")) {
synthetic(t, s, new Url(DATAMODEL_URL), new FunType(), METHOD);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
String[] list(String... names) {
return names;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public String loadData() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
this.loaded = true;
br.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#location 15
#vulnerability type RESOURCE_LEAK
|
#fixed code
public String loadData() {
try (BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
this.loaded = true;
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws UnsupportedAudioFileException, IOException {
Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
Audio.playSound(Audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);
System.out.println("Press Enter key to stop the program...");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.read();
Audio.stopService();
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, InterruptedException {
Audio audio = Audio.getInstance();
audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);
System.out.println("Press Enter key to stop the program...");
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
br.read();
}
audio.stopService();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testSelectAlbum() {
AlbumListPage albumListPage = new AlbumListPage(new WebClient());
AlbumPage albumPage = albumListPage.selectAlbum("21");
assertTrue(albumPage.isAt());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testSelectAlbum() {
AlbumPage albumPage = albumListPage.selectAlbum("21");
albumPage.navigateToPage();
assertTrue(albumPage.isAt());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Map<String, String> map = (Map<String, String>) objIn.readObject();
objIn.close();
fileIn.close();
return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map
.get("lengthMeters")), Integer.parseInt(map.get("weightTons")));
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
Map<String, String> map = null;
try (FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream objIn = new ObjectInputStream(fileIn)) {
map = (Map<String, String>) objIn.readObject();
}
return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map.get("lengthMeters")),
Integer.parseInt(map.get("weightTons")));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testSelectAlbum() {
AlbumListPage albumListPage = new AlbumListPage(new WebClient());
AlbumPage albumPage = albumListPage.selectAlbum("21");
assertTrue(albumPage.isAt());
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testSelectAlbum() {
AlbumPage albumPage = albumListPage.selectAlbum("21");
albumPage.navigateToPage();
assertTrue(albumPage.isAt());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void renameMailbox(MailFolder existingFolder, String newName) throws FolderException {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
}
#location 27
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void renameMailbox(MailFolder existingFolder, String newName) {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void run() {
initServerSocket();
// Notify everybody that we're ready to accept connections
synchronized (startupMonitor) {
startupMonitor.notifyAll();
}
if (log.isDebugEnabled()) {
log.debug("Started " + getName());
}
// Handle connections
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
handleClientSocket(clientSocket);
}
} catch (IOException ignored) {
//ignored
if (log.isTraceEnabled()) {
log.trace("Error while processing client socket for " + getName(), ignored);
}
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void run() {
try {
initServerSocket();
if (log.isDebugEnabled()) {
log.debug("Started " + getName());
}
// Handle connections
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
handleClientSocket(clientSocket);
}
} catch (IOException ignored) {
//ignored
if (log.isTraceEnabled()) {
log.trace("Error while processing client socket for " + getName(), ignored);
}
}
}
} finally {
closeServerSocket();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testSearch() throws Exception {
GreenMailUser user = greenMail.setUser("to1@localhost", "pwd");
assertNotNull(greenMail.getImap());
MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
Flags fooFlags = new Flags();
fooFlags.add("foo");
storeSearchTestMessages(greenMail.getImap().createSession(), folder, fooFlags);
greenMail.waitForIncomingEmail(2);
final Store store = greenMail.getImap().createStore();
store.connect("to1@localhost", "pwd");
try {
Folder imapFolder = store.getFolder("INBOX");
imapFolder.open(Folder.READ_WRITE);
Message[] imapMessages = imapFolder.getMessages();
assertTrue(null != imapMessages && imapMessages.length == 2);
Message m0 = imapMessages[0];
Message m1 = imapMessages[1];
assertTrue(m0.getFlags().contains(Flags.Flag.ANSWERED));
// Search flags
imapMessages = imapFolder.search(new FlagTerm(new Flags(Flags.Flag.ANSWERED), true));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FlagTerm(fooFlags, true));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getFlags().contains("foo"));
imapMessages = imapFolder.search(new FlagTerm(fooFlags, false));
assertEquals(1, imapMessages.length);
assertTrue(!imapMessages[0].getFlags().contains(fooFlags));
// Search header ids
String id = m0.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
id = m1.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search FROM
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from3@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search TO
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to3@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search Subject
imapMessages = imapFolder.search(new SubjectTerm("test0Search"));
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("TeSt0Search")); // Case insensitive
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("0S"));
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("not found"));
assertEquals(0, imapMessages.length);
imapMessages = imapFolder.search(new SubjectTerm("test"));
assertTrue(imapMessages.length == 2);
//Search OrTerm - Search Subject which contains String1 OR String2
imapMessages = imapFolder.search(new OrTerm(new SubjectTerm("test0Search"),new SubjectTerm("String2")));
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
//Search AndTerm - Search Subject which contains String1 AND String2
imapMessages = imapFolder.search(new AndTerm(new SubjectTerm("test0Search"),new SubjectTerm("test1Search")));
assertTrue(imapMessages.length == 1);
assertTrue(imapMessages[0] == m1);
// Content
final String pattern = "\u00e4\u03A0";
imapMessages = imapFolder.search(new SubjectTerm(pattern));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getSubject().contains(pattern));
} finally {
store.close();
}
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testSearch() throws Exception {
GreenMailUser user = greenMail.setUser("to1@localhost", "pwd");
assertNotNull(greenMail.getImap());
MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
Flags fooFlags = new Flags();
fooFlags.add("foo");
storeSearchTestMessages(greenMail.getImap().createSession(), folder, fooFlags);
greenMail.waitForIncomingEmail(2);
final Store store = greenMail.getImap().createStore();
store.connect("to1@localhost", "pwd");
try {
Folder imapFolder = store.getFolder("INBOX");
imapFolder.open(Folder.READ_WRITE);
Message[] imapMessages = imapFolder.getMessages();
assertEquals(4, imapMessages.length);
Message m0 = imapMessages[0];
assertTrue(m0.getSubject().startsWith("#0"));
Message m1 = imapMessages[1];
assertTrue(m1.getSubject().startsWith("#1"));
Message m2 = imapMessages[2];
assertTrue(m2.getSubject().startsWith("#2"));
Message m3 = imapMessages[3];
assertTrue(m3.getSubject().startsWith("#3"));
assertTrue(m0.getFlags().contains(Flags.Flag.ANSWERED));
// Search flags
imapMessages = imapFolder.search(new FlagTerm(new Flags(Flags.Flag.ANSWERED), true));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FlagTerm(fooFlags, true));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getFlags().contains("foo"));
imapMessages = imapFolder.search(new FlagTerm(fooFlags, false));
assertEquals(3, imapMessages.length);
assertTrue(!imapMessages[0].getFlags().contains(fooFlags));
assertTrue(!imapMessages[1].getFlags().contains(fooFlags));
assertTrue(!imapMessages[2].getFlags().contains(fooFlags));
// Search header ids
String id = m0.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
id = m1.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search FROM
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from3@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search TO
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to3@localhost")));
assertEquals(3, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search Subject
imapMessages = imapFolder.search(new SubjectTerm("test0Search"));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("TeSt0Search")); // Case insensitive
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("0S"));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("not found"));
assertEquals(0, imapMessages.length);
imapMessages = imapFolder.search(new SubjectTerm("test"));
assertEquals(2, imapMessages.length);
//Search OrTerm - Search Subject which contains test0Search OR nonexistent
imapMessages = imapFolder.search(new OrTerm(new SubjectTerm("test0Search"), new SubjectTerm("nonexistent")));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
// OrTerm : two matching sub terms
imapMessages = imapFolder.search(new OrTerm(new SubjectTerm("foo"), new SubjectTerm("bar")));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m2);
assertTrue(imapMessages[1] == m3);
// OrTerm : no matching
imapMessages = imapFolder.search(new AndTerm(new SubjectTerm("nothing"), new SubjectTerm("nil")));
assertEquals(0, imapMessages.length);
//Search AndTerm - Search Subject which contains test0Search AND test1Search
imapMessages = imapFolder.search(new AndTerm(new SubjectTerm("test0Search"), new SubjectTerm("test1Search")));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0] == m1);
// Content
final String pattern = "\u00e4\u03A0";
imapMessages = imapFolder.search(new SubjectTerm(pattern));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getSubject().contains(pattern));
} finally {
store.close();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void run() {
try {
try {
serverSocket = openServerSocket();
setRunning(true);
synchronized (this) {
this.notifyAll();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
final ProtocolHandler handler = createProtocolHandler(clientSocket);
addHandler(handler);
new Thread(new Runnable() {
@Override
public void run() {
handler.run(); // NOSONAR
// Make sure to deregister, see https://github.com/greenmail-mail-test/greenmail/issues/18
removeHandler(handler);
}
}).start();
}
} catch (IOException ignored) {
//ignored
if(log.isTraceEnabled()) {
log.trace("Error while processing socket", ignored);
}
}
}
} finally {
quit();
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void run() {
try {
serverSocket = openServerSocket();
setRunning(true);
synchronized (this) {
this.notifyAll();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
final ProtocolHandler handler = createProtocolHandler(clientSocket);
addHandler(handler);
new Thread(new Runnable() {
@Override
public void run() {
handler.run(); // NOSONAR
// Make sure to deregister, see https://github.com/greenmail-mail-test/greenmail/issues/18
removeHandler(handler);
}
}).start();
}
} catch (IOException ignored) {
//ignored
if(log.isTraceEnabled()) {
log.trace("Error while processing socket", ignored);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void readDotTerminatedContent(BufferedReader in)
throws IOException {
content = workspace.getTmpFile();
Writer data = content.getWriter();
PrintWriter dataWriter = new InternetPrintWriter(data);
while (true) {
String line = in.readLine();
if (line == null)
throw new EOFException("Did not receive <CRLF>.<CRLF>");
if (".".equals(line)) {
dataWriter.close();
break;
} else if (line.startsWith(".")) {
dataWriter.println(line.substring(1));
} else {
dataWriter.println(line);
}
}
try {
message = GreenMailUtil.newMimeMessage(content.getAsString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#location 20
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void readDotTerminatedContent(BufferedReader in)
throws IOException {
StringBuilder buf = new StringBuilder();
while (true) {
String line = in.readLine();
if (line == null)
throw new EOFException("Did not receive <CRLF>.<CRLF>");
if (".".equals(line)) {
break;
} else if (line.startsWith(".")) {
println(buf, line.substring(1));
} else {
println(buf, line);
}
}
content = buf.toString();
try {
message = GreenMailUtil.newMimeMessage(content);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authEnabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(true);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authEnabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(true);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void handleBodyFetch(MimeMessage mimeMessage,
String sectionSpecifier,
String partial,
StringBuilder response) throws IOException, MessagingException {
if (sectionSpecifier.length() == 0) {
// TODO - need to use an InputStream from the response here.
ByteArrayOutputStream bout = new ByteArrayOutputStream();
mimeMessage.writeTo(bout);
byte[] bytes = bout.toByteArray();
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("HEADER".equalsIgnoreCase(sectionSpecifier)) {
Enumeration<?> inum = mimeMessage.getAllHeaderLines();
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS.NOT")) {
String[] excludeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS.NOT".length());
Enumeration<?> inum = mimeMessage.getNonMatchingHeaderLines(excludeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS ")) {
String[] includeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS ".length());
Enumeration<?> inum = mimeMessage.getMatchingHeaderLines(includeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.endsWith("MIME")) {
String[] strs = sectionSpecifier.trim().split("\\.");
int partNumber = Integer.parseInt(strs[0]) - 1;
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
byte[] bytes = GreenMailUtil.getHeaderAsBytes(mp.getBodyPart(partNumber));
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("TEXT".equalsIgnoreCase(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
if (log.isDebugEnabled()) {
log.debug("Fetching body part for section specifier " + sectionSpecifier +
" and mime message (contentType=" + mimeMessage.getContentType());
}
String contentType = mimeMessage.getContentType();
if (contentType.startsWith("text/plain") && "1".equals(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
BodyPart part = null;
String[] nestedIdx = sectionSpecifier.split("\\.");
for (String idx : nestedIdx) {
int partNumber = Integer.parseInt(idx) - 1;
if (null == part) {
part = mp.getBodyPart(partNumber);
} else {
// Content must be multipart
part = ((Multipart) part.getContent()).getBodyPart(partNumber);
}
}
byte[] bytes = GreenMailUtil.getBodyAsBytes(part);
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
}
}
}
#location 53
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void handleBodyFetch(MimeMessage mimeMessage,
String sectionSpecifier,
String partial,
StringBuilder response) throws IOException, MessagingException {
if (sectionSpecifier.length() == 0) {
// TODO - need to use an InputStream from the response here.
ByteArrayOutputStream bout = new ByteArrayOutputStream();
mimeMessage.writeTo(bout);
byte[] bytes = bout.toByteArray();
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("HEADER".equalsIgnoreCase(sectionSpecifier)) {
Enumeration<?> inum = mimeMessage.getAllHeaderLines();
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS.NOT")) {
String[] excludeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS.NOT".length());
Enumeration<?> inum = mimeMessage.getNonMatchingHeaderLines(excludeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS ")) {
String[] includeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS ".length());
Enumeration<?> inum = mimeMessage.getMatchingHeaderLines(includeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.endsWith("MIME")) {
String[] strs = sectionSpecifier.trim().split("\\.");
int partNumber = Integer.parseInt(strs[0]) - 1;
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
byte[] bytes = GreenMailUtil.getHeaderAsBytes(mp.getBodyPart(partNumber));
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("TEXT".equalsIgnoreCase(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
if (log.isDebugEnabled()) {
log.debug("Fetching body part for section specifier " + sectionSpecifier +
" and mime message (contentType=" + mimeMessage.getContentType());
}
String contentType = mimeMessage.getContentType();
if (contentType.toLowerCase().startsWith("text/plain") && "1".equals(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
BodyPart part = null;
// Find part by number spec, eg "1" or "2.1" or "4.3.1" ...
String spec = sectionSpecifier;
int dotIdx = spec.indexOf('.');
String pre = dotIdx < 0 ? spec : spec.substring(0, dotIdx);
while (null != pre && NUMBER_MATCHER.matcher(pre).matches()) {
int partNumber = Integer.parseInt(pre) - 1;
if (null == part) {
part = mp.getBodyPart(partNumber);
} else {
// Content must be multipart
part = ((Multipart) part.getContent()).getBodyPart(partNumber);
}
dotIdx = spec.indexOf('.');
if (dotIdx > 0) { // Another sub part index?
spec = spec.substring(dotIdx + 1);
pre = spec.substring(0, dotIdx);
} else {
pre = null;
}
}
if (null == part) {
throw new IllegalStateException("Got null for " + sectionSpecifier);
}
// A bit optimistic to only cover theses cases ... TODO
if ("message/rfc822".equalsIgnoreCase(part.getContentType())) {
handleBodyFetch((MimeMessage) part.getContent(), spec, partial, response);
} else if ("TEXT".equalsIgnoreCase(spec)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
byte[] bytes = GreenMailUtil.getBodyAsBytes(part);
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public long appendMessage(MimeMessage message,
Flags flags,
Date receivedDate) {
long uid = nextUid;
nextUid++;
try {
message.setFlags(flags, true);
message.setFlag(Flags.Flag.RECENT, true);
} catch (MessagingException e) {
throw new IllegalStateException("Can not set flags", e);
}
StoredMessage storedMessage = new StoredMessage(message,
receivedDate, uid);
int newMsn;
synchronized (mailMessages) {
mailMessages.add(storedMessage);
newMsn = mailMessages.size();
}
// Notify all the listeners of the new message
synchronized (_mailboxListeners) {
for (FolderListener _mailboxListener : _mailboxListeners) {
_mailboxListener.added(newMsn);
}
}
return uid;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public long appendMessage(MimeMessage message,
Flags flags,
Date receivedDate) {
final long uid = nextUid.getAndIncrement();
try {
message.setFlags(flags, true);
message.setFlag(Flags.Flag.RECENT, true);
} catch (MessagingException e) {
throw new IllegalStateException("Can not set flags", e);
}
StoredMessage storedMessage = new StoredMessage(message,
receivedDate, uid);
int newMsn;
synchronized (mailMessages) {
mailMessages.add(storedMessage);
newMsn = mailMessages.size();
}
// Notify all the listeners of the new message
synchronized (_mailboxListeners) {
for (FolderListener _mailboxListener : _mailboxListeners) {
_mailboxListener.added(newMsn);
}
}
return uid;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authPlain() throws IOException, MessagingException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo(
"-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 21
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlain() throws IOException {
withConnection((printStream, reader) -> {
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
try {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
} catch (UserException e) {
throw new IllegalStateException(e);
}
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void renameMailbox(MailFolder existingFolder, String newName) throws FolderException {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
}
#location 29
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void renameMailbox(MailFolder existingFolder, String newName) {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authDisabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(false);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authDisabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(false);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 13
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.