output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code @Test public void testEmptyInput() throws Exception { final ExtendedBufferedReader br = getBufferedReader(""); assertEquals(END_OF_STREAM, br.read()); assertEquals(END_OF_STREAM, br.lookAhead()); assertEquals(END_OF_STREAM, br.getLastChar()); assertNull(br.readLine()); assertEquals(0, br.read(new char[10], 0, 0)); br.close(); }
#vulnerable code @Test public void testEmptyInput() throws Exception { final ExtendedBufferedReader br = getBufferedReader(""); assertEquals(END_OF_STREAM, br.read()); assertEquals(END_OF_STREAM, br.lookAhead()); assertEquals(END_OF_STREAM, br.getLastChar()); assertNull(br.readLine()); assertEquals(0, br.read(new char[10], 0, 0)); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br.close(); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); br.close(); }
#vulnerable code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEndOfFileBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
#vulnerable code @Test public void testEndOfFileBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCSVFile() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName+" require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for(int i=1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=",2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])){ format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName+" unexpected option: "+option); } } line = readTestData(); // get string version of format assertEquals(testName+" Expected format ", line, format.toString()); // Now parse the file and compare against the expected results // We use a buffered reader internally so no need to create one here. final CSVParser parser = CSVParser.parse(new File(BASE, split[0]), format); for(final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count+":"+parsed); } parser.close(); }
#vulnerable code @Test public void testCSVFile() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName+" require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for(int i=1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=",2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])){ format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName+" unexpected option: "+option); } } line = readTestData(); // get string version of format assertEquals(testName+" Expected format ", line, format.toString()); // Now parse the file and compare against the expected results // We use a buffered reader internally so no need to create one here. final CSVParser parser = CSVParser.parse(new File(BASE, split[0]), format); for(final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count+":"+parsed); } } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testSkip0() throws Exception { ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.skip(0)); assertEquals(0, br.skip(1)); br = getEBR(""); assertEquals(0, br.skip(1)); br = getEBR("abcdefg"); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(1, br.skip(1)); assertEquals('b', br.lookAhead()); assertEquals('b', br.read()); assertEquals(3, br.skip(3)); assertEquals('f', br.lookAhead()); assertEquals(2, br.skip(5)); assertTrue(br.readLine() == null); br = getEBR("12345"); assertEquals(5, br.skip(5)); assertTrue (br.lookAhead() == ExtendedBufferedReader.END_OF_STREAM); }
#vulnerable code public void testSkip0() throws Exception { br = getEBR(""); assertEquals(0, br.skip(0)); assertEquals(0, br.skip(1)); br = getEBR(""); assertEquals(0, br.skip(1)); br = getEBR("abcdefg"); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(1, br.skip(1)); assertEquals('b', br.lookAhead()); assertEquals('b', br.read()); assertEquals(3, br.skip(3)); assertEquals('f', br.lookAhead()); assertEquals(2, br.skip(5)); assertTrue(br.readLine() == null); br = getEBR("12345"); assertEquals(5, br.skip(5)); assertTrue (br.lookAhead() == ExtendedBufferedReader.END_OF_STREAM); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); }
#vulnerable code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertTrue(br.readLine() == null); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertTrue(br.readLine() == null); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertTrue(br.readLine() == null); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(Arrays.asList(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); printer.close(); }
#vulnerable code @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(Arrays.asList(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEmptyFile() throws Exception { final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); assertNull(parser.nextRecord()); }
#vulnerable code @Test public void testEmptyFile() throws Exception { final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); assertNull(parser.nextRecord()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void testCSVLexer(final boolean newToken, String test) throws Exception { Token token = new Token(); String dynamic = ""; for (int i = 0; i < max; i++) { final ExtendedBufferedReader input = new ExtendedBufferedReader(getReader()); Lexer lexer = null; if (test.startsWith("CSVLexer")) { dynamic="!"; lexer = getLexerCtor(test).newInstance(new Object[]{format, input}); } else { lexer = new CSVLexer(format, input); } int count = 0; int fields = 0; long t0 = System.currentTimeMillis(); do { if (newToken) { token = new Token(); } else { token.reset(); } lexer.nextToken(token); switch(token.type) { case EOF: break; case EORECORD: fields++; count++; break; case INVALID: throw new IOException("invalid parse sequence"); case TOKEN: fields++; break; } } while (!token.type.equals(Token.Type.EOF)); Stats s = new Stats(count, fields); input.close(); show(lexer.getClass().getSimpleName()+dynamic+" "+(newToken ? "new" : "reset"), s, t0); } show(); }
#vulnerable code private static void testCSVLexer(final boolean newToken, String test) throws Exception { Token token = new Token(); for (int i = 0; i < max; i++) { final BufferedReader reader = getReader(); Lexer lexer = new CSVLexer(format, new ExtendedBufferedReader(reader)); int count = 0; int fields = 0; long t0 = System.currentTimeMillis(); do { if (newToken) { token = new Token(); } else { token.reset(); } lexer.nextToken(token); switch(token.type) { case EOF: break; case EORECORD: fields++; count++; break; case INVALID: throw new IOException("invalid parse sequence"); case TOKEN: fields++; break; } } while (!token.type.equals(Token.Type.EOF)); Stats s = new Stats(count, fields); reader.close(); show(test, s, t0); } show(); } #location 31 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDelimiterIsWhitespace() throws IOException { final String code = "one\ttwo\t\tfour \t five\t six"; final Lexer parser = getLexer(code, CSVFormat.TDF); assertThat(parser.nextToken(new Token()), matches(TOKEN, "one")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "two")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "four")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "five")); assertThat(parser.nextToken(new Token()), matches(EOF, "six")); }
#vulnerable code @Test public void testDelimiterIsWhitespace() throws IOException { final String code = "one\ttwo\t\tfour \t five\t six"; final Lexer parser = getLexer(code, CSVFormat.TDF); assertTokenEquals(TOKEN, "one", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "two", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "four", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "five", parser.nextToken(new Token())); assertTokenEquals(EOF, "six", parser.nextToken(new Token())); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); printer.close(); }
#vulnerable code @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); printer.close(); }
#vulnerable code @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEmptyLineBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
#vulnerable code @Test public void testEmptyLineBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {""} }; for (final String code : codes) { final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNextToken3Escaping() throws IOException { /* file: a,\,,b * \,, */ String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; CSVFormat format = CSVFormat.DEFAULT.withEscape('\\').withEmptyLinesIgnored(false); assertTrue(format.isEscaping()); Lexer parser = getLexer(code, format); assertTokenEquals(TOKEN, "a", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "b\\", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "\nc", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "d\r", parser.nextToken(new Token())); assertTokenEquals(EOF, "e", parser.nextToken(new Token())); }
#vulnerable code @Test public void testNextToken3Escaping() throws IOException { /* file: a,\,,b * \,, */ String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\n"; CSVFormat format = CSVFormat.DEFAULT.withEscape('\\'); assertTrue(format.isEscaping()); Lexer parser = getLexer(code, format); assertTokenEquals(TOKEN, "a", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "b\\", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "\nc", parser.nextToken(new Token())); assertTokenEquals(EOF, "d\n", parser.nextToken(new Token())); assertTokenEquals(EOF, "", parser.nextToken(new Token())); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } parser.close(); } }
#vulnerable code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void testParseCommonsCSV() throws Exception { for (int i = 0; i < max; i++) { final BufferedReader reader = getReader(); final CSVParser parser = new CSVParser(reader, format); final long t0 = System.currentTimeMillis(); final Stats s = iterate(parser); reader.close(); show("CSV", s, t0); parser.close(); } show(); }
#vulnerable code private static void testParseCommonsCSV() throws Exception { for (int i = 0; i < max; i++) { final BufferedReader reader = getReader(); final CSVParser parser = new CSVParser(reader, format); final long t0 = System.currentTimeMillis(); final Stats s = iterate(parser); reader.close(); show("CSV", s, t0); } show(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDefaultFormat() throws IOException { String code = "" + "a,b\n" // 1) + "\"\n\",\" \"\n" // 2) + "\"\",#\n" // 2) ; String[][] res = { {"a", "b"}, {"\n", " "}, {"", "#"}, }; CSVFormat format = CSVFormat.DEFAULT; assertEquals(CSVFormat.DISABLED, format.getCommentStart()); CSVParser parser = new CSVParser(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); assertTrue(CSVPrinterTest.equals(res, records)); String[][] res_comments = { {"a", "b"}, {"\n", " "}, {""}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser = new CSVParser(code, format); records = parser.getRecords(); assertTrue(CSVPrinterTest.equals(res_comments, records)); }
#vulnerable code @Test public void testDefaultFormat() throws IOException { String code = "" + "a,b\n" // 1) + "\"\n\",\" \"\n" // 2) + "\"\",#\n" // 2) ; String[][] res = { {"a", "b"}, {"\n", " "}, {"", "#"}, }; CSVFormat format = CSVFormat.DEFAULT; assertEquals(CSVFormat.DISABLED, format.getCommentStart()); CSVParser parser = new CSVParser(code, format); String[][] tmp = parser.getRecords(); assertTrue(tmp.length > 0); if (!CSVPrinterTest.equals(res, tmp)) { assertTrue(false); } String[][] res_comments = { {"a", "b"}, {"\n", " "}, {""}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser = new CSVParser(code, format); tmp = parser.getRecords(); if (!CSVPrinterTest.equals(res_comments, tmp)) { assertTrue(false); } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception { final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); final Iterator<CSVRecord> itr1 = parser.iterator(); final Iterator<CSVRecord> itr2 = parser.iterator(); final CSVRecord first = itr1.next(); assertEquals("a", first.get(0)); assertEquals("b", first.get(1)); assertEquals("c", first.get(2)); final CSVRecord second = itr2.next(); assertEquals("d", second.get(0)); assertEquals("e", second.get(1)); assertEquals("f", second.get(2)); parser.close(); }
#vulnerable code @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception { final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); final Iterator<CSVRecord> itr1 = parser.iterator(); final Iterator<CSVRecord> itr2 = parser.iterator(); final CSVRecord first = itr1.next(); assertEquals("a", first.get(0)); assertEquals("b", first.get(1)); assertEquals("c", first.get(2)); final CSVRecord second = itr2.next(); assertEquals("d", second.get(0)); assertEquals("e", second.get(1)); assertEquals("f", second.get(2)); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } }
#vulnerable code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBackslashEscaping2() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. String code = "" + " , , \n" // 1) + " \t , , \n" // 2) + " // , /, , /,\n" // 3) + ""; String[][] res = { {" ", " ", " "}, // 1 {" \t ", " ", " "}, // 2 {" / ", " , ", " ,"}, // 3 }; CSVFormat format = new CSVFormat(',', CSVFormat.DISABLED, CSVFormat.DISABLED, '/', false, false, true, "\r\n", null); CSVParser parser = new CSVParser(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); assertTrue(CSVPrinterTest.equals(res, records)); }
#vulnerable code @Test public void testBackslashEscaping2() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. String code = "" + " , , \n" // 1) + " \t , , \n" // 2) + " // , /, , /,\n" // 3) + ""; String[][] res = { {" ", " ", " "}, // 1 {" \t ", " ", " "}, // 2 {" / ", " , ", " ,"}, // 3 }; CSVFormat format = new CSVFormat(',', CSVFormat.DISABLED, CSVFormat.DISABLED, '/', false, false, true, true, "\r\n", null); CSVParser parser = new CSVParser(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); assertTrue(CSVPrinterTest.equals(res, records)); } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void parse() throws IOException { final BufferedReader br = new BufferedReader(getTestInput()); String s = null; int totcomment = 0; int totrecs = 0; boolean lastWasComment = false; while((s=br.readLine()) != null) { if (s.startsWith("#")) { if (!lastWasComment) { // comments are merged totcomment++; } lastWasComment = true; } else { totrecs++; lastWasComment = false; } } br.close(); CSVFormat format = CSVFormat.DEFAULT; // format = format.withAllowMissingColumnNames(false); format = format.withCommentMarker('#'); format = format.withDelimiter(','); format = format.withEscape('\\'); format = format.withHeader("author", "title", "publishDate"); format = format.withHeaderComments("headerComment"); format = format.withNullString("NULL"); format = format.withIgnoreEmptyLines(true); format = format.withIgnoreSurroundingSpaces(true); format = format.withQuote('"'); format = format.withQuoteMode(QuoteMode.ALL); format = format.withRecordSeparator('\n'); format = format.withSkipHeaderRecord(false); // final CSVParser parser = format.parse(getTestInput()); int comments = 0; int records = 0; for (final CSVRecord csvRecord : parser) { records++; if (csvRecord.hasComment()) { comments++; } } // Comment lines are concatenated, in this example 4 lines become 2 comments. Assert.assertEquals(totcomment, comments); Assert.assertEquals(totrecs, records); // records includes the header }
#vulnerable code @Test public void parse() throws IOException { final File csvData = new File("src/test/resources/csv-167/sample1.csv"); final BufferedReader br = new BufferedReader(new FileReader(csvData)); String s = null; int totcomment = 0; int totrecs = 0; boolean lastWasComment = false; while((s=br.readLine()) != null) { if (s.startsWith("#")) { if (!lastWasComment) { // comments are merged totcomment++; } lastWasComment = true; } else { totrecs++; lastWasComment = false; } } br.close(); CSVFormat format = CSVFormat.DEFAULT; // format = format.withAllowMissingColumnNames(false); format = format.withCommentMarker('#'); format = format.withDelimiter(','); format = format.withEscape('\\'); format = format.withHeader("author", "title", "publishDate"); format = format.withHeaderComments("headerComment"); format = format.withNullString("NULL"); format = format.withIgnoreEmptyLines(true); format = format.withIgnoreSurroundingSpaces(true); format = format.withQuote('"'); format = format.withQuoteMode(QuoteMode.ALL); format = format.withRecordSeparator('\n'); format = format.withSkipHeaderRecord(false); // final CSVParser parser = CSVParser.parse(csvData, Charset.defaultCharset(), format); int comments = 0; int records = 0; for (final CSVRecord csvRecord : parser) { // System.out.println(csvRecord.isComment() + "[" + csvRecord.toString() + "]"); records++; if (csvRecord.hasComment()) { comments++; } } // Comment lines are concatenated, in this example 4 lines become 2 comments. Assert.assertEquals(totcomment, comments); Assert.assertEquals(totrecs, records); // records includes the header } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testLineFeedEndings() throws IOException { final String code = "foo\nbaar,\nhello,world\n,kanu"; final CSVParser parser = CSVParser.parseString(code); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); }
#vulnerable code @Test public void testLineFeedEndings() throws IOException { final String code = "foo\nbaar,\nhello,world\n,kanu"; final CSVParser parser = new CSVParser(new StringReader(code)); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } parser.close(); }
#vulnerable code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); parser.close(); }
#vulnerable code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); final CSVPrinter printer = new CSVPrinter(sw, format); printer.printRecord("a", null, "b"); printer.close(); final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); final Iterable<CSVRecord> iterable = format.parse(new StringReader(csvString)); final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); ((CSVParser) iterable).close(); }
#vulnerable code @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); final CSVPrinter printer = new CSVPrinter(sw, format); printer.printRecord("a", null, "b"); printer.close(); final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); final Iterable<CSVRecord> iterable = format.parse(new StringReader(csvString)); final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); printer.close(); }
#vulnerable code @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getBufferedReader("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); }
#vulnerable code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetRecords() throws IOException { CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } }
#vulnerable code @Test public void testGetRecords() throws IOException { CSVParser parser = new CSVParser(new StringReader(code)); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br.close(); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); br.close(); }
#vulnerable code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); }
#vulnerable code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEmptyLineBehaviourCSV() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
#vulnerable code @Test public void testEmptyLineBehaviourCSV() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = CSVParser.parseString(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); }
#vulnerable code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = new CSVParser(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEndOfFileBehaviorCSV() throws Exception { String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } } }
#vulnerable code @Test public void testEndOfFileBehaviorCSV() throws Exception { String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); }
#vulnerable code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCarriageReturnEndings() throws IOException { final String code = "foo\rbaar,\rhello,world\r,kanu"; final CSVParser parser = CSVParser.parseString(code); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); }
#vulnerable code @Test public void testCarriageReturnEndings() throws IOException { final String code = "foo\rbaar,\rhello,world\r,kanu"; final CSVParser parser = new CSVParser(new StringReader(code)); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExcelFormat1() throws IOException { final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; final String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } }
#vulnerable code @Test public void testExcelFormat1() throws IOException { final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; final String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void parseAlterColumn(final Parser parser, final PgTable table) { parser.expectOptional("COLUMN"); final String columnName = parser.parseIdentifier(); if (parser.expectOptional("SET")) { if (parser.expectOptional("STATISTICS")) { final PgColumn column = table.getColumn(columnName); column.setStatistics(parser.parseInteger()); } else if (parser.expectOptional("DEFAULT")) { final String defaultValue = parser.getExpression(); if (table.containsColumn(columnName)) { final PgColumn column = table.getColumn(columnName); column.setDefaultValue(defaultValue); } else { throw new ParserException("Cannot find column '" + columnName + " 'in table '" + table.getName() + "'"); } } else if (parser.expectOptional("STORAGE")) { final PgColumn column = table.getColumn(columnName); if (parser.expectOptional("PLAIN")) { column.setStorage("PLAIN"); } else if (parser.expectOptional("EXTERNAL")) { column.setStorage("EXTERNAL"); } else if (parser.expectOptional("EXTENDED")) { column.setStorage("EXTENDED"); } else if (parser.expectOptional("MAIN")) { column.setStorage("MAIN"); } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } }
#vulnerable code private static void parseAlterColumn(final Parser parser, final PgTable table) { parser.expectOptional("COLUMN"); final String columnName = parser.parseIdentifier(); if (parser.expectOptional("SET")) { if (parser.expectOptional("STATISTICS")) { final PgColumn col = table.getColumn(columnName); col.setStatistics(parser.parseInteger()); } else if (parser.expectOptional("DEFAULT")) { final String defaultValue = parser.getExpression(); if (table.containsColumn(columnName)) { final PgColumn column = table.getColumn(columnName); column.setDefaultValue(defaultValue); } else { throw new ParserException("Cannot find column '" + columnName + " 'in table '" + table.getName() + "'"); } } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "VIEW"); final String viewName = parser.parseIdentifier(); final String schemaName = ParserUtils.getSchemaName(viewName, database); final String objectName = ParserUtils.getObjectName(viewName); final PgView view = database.getSchema(schemaName).getView(objectName); while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parser.expectOptional("COLUMN"); final String columnName = ParserUtils.getObjectName(parser.parseIdentifier()); if (parser.expectOptional("SET", "DEFAULT")) { final String expression = parser.getExpression(); view.addColumnDefaultValue(columnName, expression); } else if (parser.expectOptional("DROP", "DEFAULT")) { view.removeColumnDefaultValue(columnName); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("OWNER", "TO")) { // we do not support OWNER TO so just consume the output parser.getExpression(); } else { parser.throwUnsupportedCommand(); } } }
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "VIEW"); final String viewName = parser.parseIdentifier(); final PgView view = database.getSchema( ParserUtils.getSchemaName(viewName, database)).getView( ParserUtils.getObjectName(viewName)); while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parser.expectOptional("COLUMN"); final String columnName = ParserUtils.getObjectName(parser.parseIdentifier()); if (parser.expectOptional("SET", "DEFAULT")) { final String expression = parser.getExpression(); view.addColumnDefaultValue(columnName, expression); } else if (parser.expectOptional("DROP", "DEFAULT")) { view.removeColumnDefaultValue(columnName); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("OWNER", "TO")) { // we do not support OWNER TO so just consume the output parser.getExpression(); } else { parser.throwUnsupportedCommand(); } } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void parse(final PgDatabase database, final String command) { String line = command; final Matcher matcher = PATTERN_TABLE_NAME.matcher(line); final String tableName; if (matcher.find()) { tableName = matcher.group(1).trim(); line = ParserUtils.removeSubString( line, matcher.start(), matcher.end()); } else { throw new ParserException( ParserException.CANNOT_PARSE_COMMAND + line); } final PgTable table = new PgTable(ParserUtils.getObjectName(tableName)); final String schemaName = ParserUtils.getSchemaName(tableName, database); final PgSchema schema = database.getSchema(schemaName); if (schema == null) { throw new RuntimeException( "Cannot get schema '" + schemaName + "'. Need to issue 'CREATE SCHEMA " + schemaName + ";' before 'CREATE TABLE " + tableName + "...;'?"); } schema.addTable(table); parseRows(table, ParserUtils.removeLastSemicolon(line)); }
#vulnerable code public static void parse(final PgDatabase database, final String command) { String line = command; final Matcher matcher = PATTERN_TABLE_NAME.matcher(line); final String tableName; if (matcher.find()) { tableName = matcher.group(1).trim(); line = ParserUtils.removeSubString( line, matcher.start(), matcher.end()); } else { throw new ParserException( ParserException.CANNOT_PARSE_COMMAND + line); } final PgTable table = new PgTable(ParserUtils.getObjectName(tableName)); database.getSchema(ParserUtils.getSchemaName(tableName, database)).addTable( table); parseRows(table, ParserUtils.removeLastSemicolon(line)); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "TABLE"); parser.expectOptional("ONLY"); final String tableName = parser.parseIdentifier(); final String schemaName = ParserUtils.getSchemaName(tableName, database); final PgSchema schema = database.getSchema(schemaName); final String objectName = ParserUtils.getObjectName(tableName); final PgTable table = schema.getTable(objectName); if (table == null) { final PgView view = schema.getView(objectName); if (view != null) { parseView(parser, view); return; } } while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parseAlterColumn(parser, table); } else if (parser.expectOptional("CLUSTER", "ON")) { table.setClusterIndexName(parser.parseIdentifier()); } else if (parser.expectOptional("OWNER", "TO")) { // we do not parse this one so we just consume the expression parser.getExpression(); } else if (parser.expectOptional("ADD")) { if (parser.expectOptional("FOREIGN", "KEY")) { parseAddForeignKey(parser, table); } else if (parser.expectOptional("CONSTRAINT")) { parseAddConstraint(parser, table); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("ENABLE")) { parseEnable(parser); } else if (parser.expectOptional("DISABLE")) { parseDisable(parser); } else { parser.throwUnsupportedCommand(); } if (parser.expectOptional(";")) { break; } else { parser.expect(","); } } }
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "TABLE"); parser.expectOptional("ONLY"); final String tableName = parser.parseIdentifier(); final PgTable table = database.getSchema( ParserUtils.getSchemaName(tableName, database)).getTable( ParserUtils.getObjectName(tableName)); while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parseAlterColumn(parser, table); } else if (parser.expectOptional("CLUSTER", "ON")) { table.setClusterIndexName(parser.parseIdentifier()); } else if (parser.expectOptional("OWNER", "TO")) { // we do not parse this one so we just consume the expression parser.getExpression(); } else if (parser.expectOptional("ADD")) { if (parser.expectOptional("FOREIGN", "KEY")) { parseAddForeignKey(parser, table); } else if (parser.expectOptional("CONSTRAINT")) { parseAddConstraint(parser, table); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("ENABLE")) { parseEnable(parser); } else if (parser.expectOptional("DISABLE")) { parseDisable(parser); } else { parser.throwUnsupportedCommand(); } if (parser.expectOptional(";")) { break; } else { parser.expect(","); } } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE"); parser.expectOptional("OR", "REPLACE"); parser.expect("FUNCTION"); final String functionName = parser.parseIdentifier(); final String schemaName = ParserUtils.getSchemaName(functionName, database); final PgFunction function = new PgFunction(); function.setName(ParserUtils.getObjectName(functionName)); database.getSchema(schemaName).addFunction(function); parser.expect("("); while (!parser.expectOptional(")")) { final String mode; if (parser.expectOptional("IN")) { mode = "IN"; } else if (parser.expectOptional("OUT")) { mode = "OUT"; } else if (parser.expectOptional("INOUT")) { mode = "INOUT"; } else if (parser.expectOptional("VARIADIC")) { mode = "VARIADIC"; } else { mode = null; } final int position = parser.getPosition(); String argumentName = null; String dataType = parser.parseDataType(); final int position2 = parser.getPosition(); if (!parser.expectOptional(")") && !parser.expectOptional(",") && !parser.expectOptional("=") && !parser.expectOptional("DEFAULT")) { parser.setPosition(position); argumentName = parser.parseIdentifier(); dataType = parser.parseDataType(); } else { parser.setPosition(position2); } final String defaultExpression; if (parser.expectOptional("=") || parser.expectOptional("DEFAULT")) { defaultExpression = parser.getExpression(); } else { defaultExpression = null; } final PgFunction.Argument argument = new PgFunction.Argument(); argument.setDataType(dataType); argument.setDefaultExpression(defaultExpression); argument.setMode(mode); argument.setName(argumentName); function.addArgument(argument); if (parser.expectOptional(")")) { break; } else { parser.expect(","); } } function.setBody(parser.getRest()); }
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE"); parser.expectOptional("OR", "REPLACE"); parser.expect("FUNCTION"); final String functionName = parser.parseIdentifier(); final PgFunction function = new PgFunction(); function.setName(ParserUtils.getObjectName(functionName)); database.getSchema(ParserUtils.getSchemaName( functionName, database)).addFunction(function); parser.expect("("); while (!parser.expectOptional(")")) { final String mode; if (parser.expectOptional("IN")) { mode = "IN"; } else if (parser.expectOptional("OUT")) { mode = "OUT"; } else if (parser.expectOptional("INOUT")) { mode = "INOUT"; } else if (parser.expectOptional("VARIADIC")) { mode = "VARIADIC"; } else { mode = null; } final int position = parser.getPosition(); String argumentName = null; String dataType = parser.parseDataType(); final int position2 = parser.getPosition(); if (!parser.expectOptional(")") && !parser.expectOptional(",") && !parser.expectOptional("=") && !parser.expectOptional("DEFAULT")) { parser.setPosition(position); argumentName = parser.parseIdentifier(); dataType = parser.parseDataType(); } else { parser.setPosition(position2); } final String defaultExpression; if (parser.expectOptional("=") || parser.expectOptional("DEFAULT")) { defaultExpression = parser.getExpression(); } else { defaultExpression = null; } final PgFunction.Argument argument = new PgFunction.Argument(); argument.setDataType(dataType); argument.setDefaultExpression(defaultExpression); argument.setMode(mode); argument.setName(argumentName); function.addArgument(argument); if (parser.expectOptional(")")) { break; } else { parser.expect(","); } } function.setBody(parser.getRest()); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE", "TRIGGER"); final PgTrigger trigger = new PgTrigger(); trigger.setName(parser.parseIdentifier()); if (parser.expectOptional("BEFORE")) { trigger.setBefore(true); } else if (parser.expectOptional("AFTER")) { trigger.setBefore(false); } boolean first = true; while (true) { if (!first && !parser.expectOptional("OR")) { break; } if (parser.expectOptional("INSERT")) { trigger.setOnInsert(true); } else if (parser.expectOptional("UPDATE")) { trigger.setOnUpdate(true); } else if (parser.expectOptional("DELETE")) { trigger.setOnDelete(true); } else if (parser.expectOptional("TRUNCATE")) { trigger.setOnTruncate(true); } else if (first) { break; } else { parser.throwUnsupportedCommand(); } first = false; } parser.expect("ON"); trigger.setTableName(parser.parseIdentifier()); if (parser.expectOptional("FOR")) { parser.expectOptional("EACH"); if (parser.expectOptional("ROW")) { trigger.setForEachRow(true); } else if (parser.expectOptional("STATEMENT")) { trigger.setForEachRow(false); } else { parser.throwUnsupportedCommand(); } } if (parser.expectOptional("WHEN")) { parser.expect("("); trigger.setWhen(parser.getExpression()); parser.expect(")"); } parser.expect("EXECUTE", "PROCEDURE"); trigger.setFunction(parser.getRest()); database.getDefaultSchema().getTable( trigger.getTableName()).addTrigger(trigger); }
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Matcher matcher = PATTERN.matcher(command.trim()); if (matcher.matches()) { final String triggerName = matcher.group(1); final String when = matcher.group(2); final String[] events = new String[3]; events[0] = matcher.group(3); events[1] = matcher.group(4); events[2] = matcher.group(5); final String tableName = matcher.group(6); final String fireOn = matcher.group(7); final String procedure = matcher.group(8); final PgTrigger trigger = new PgTrigger(); trigger.setBefore("BEFORE".equalsIgnoreCase(when)); trigger.setForEachRow( (fireOn != null) && "ROW".equalsIgnoreCase(fireOn)); trigger.setFunction(procedure.trim()); trigger.setName(triggerName.trim()); trigger.setOnDelete(isEventPresent(events, "DELETE")); trigger.setOnInsert(isEventPresent(events, "INSERT")); trigger.setOnUpdate(isEventPresent(events, "UPDATE")); trigger.setTableName(tableName.trim()); database.getDefaultSchema().getTable( trigger.getTableName()).addTrigger(trigger); } else { throw new ParserException( ParserException.CANNOT_PARSE_COMMAND + command); } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String loadText(String path) throws IOException { StringBuilder sbText = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path), "UTF-8")); String line; while ((line = br.readLine()) != null) { sbText.append(line).append("\n"); } br.close(); return sbText.toString(); }
#vulnerable code private String loadText(String path) throws IOException { StringBuilder sbText = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path))); String line; while ((line = br.readLine()) != null) { sbText.append(line).append("\n"); } br.close(); return sbText.toString(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Set<String> loadDictionary(String path) throws IOException { Set<String> dictionary = new TreeSet<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path), "UTF-8")); String line; while ((line = br.readLine()) != null) { dictionary.add(line); } br.close(); return dictionary; }
#vulnerable code private Set<String> loadDictionary(String path) throws IOException { Set<String> dictionary = new TreeSet<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path))); String line; while ((line = br.readLine()) != null) { dictionary.add(line); } br.close(); return dictionary; } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void deployAndExtractFunctions() throws Exception { // This one can only work if you change the boot classpath to contain reactor-core // and reactive-streams expected.expect(ClassCastException.class); @SuppressWarnings("unchecked") Flux<String> result = (Flux<String>) deployer.lookupFunction("pojos/uppercase") .apply(Flux.just("foo")); assertThat(result.blockFirst()).isEqualTo("FOO"); }
#vulnerable code @Test public void deployAndExtractFunctions() throws Exception { // This one can only work if you change the boot classpath to contain reactor-core // and reactive-streams expected.expect(ClassCastException.class); @SuppressWarnings("unchecked") Flux<String> result = (Flux<String>) deployer.lookupFunction("uppercase") .apply(Flux.just("foo")); assertThat(result.blockFirst()).isEqualTo("FOO"); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") public static Message<?> toBinary(Message<?> inputMessage, MessageConverter messageConverter) { Map<String, Object> headers = inputMessage.getHeaders(); CloudEventAttributes attributes = new CloudEventAttributes(headers); // first check the obvious and see if content-type is `cloudevents` if (!attributes.isValidCloudEvent() && headers.containsKey(MessageHeaders.CONTENT_TYPE)) { MimeType contentType = resolveContentType(inputMessage.getHeaders()); if (contentType != null && contentType.getType().equals(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getType()) && contentType.getSubtype().startsWith(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getSubtype())) { String dataContentType = StringUtils.hasText(attributes.getDataContentType()) ? attributes.getDataContentType() : MimeTypeUtils.APPLICATION_JSON_VALUE; String suffix = contentType.getSubtypeSuffix(); Assert.hasText(suffix, "Content-type 'suffix' can not be determined from " + contentType); MimeType cloudEventDeserializationContentType = MimeTypeUtils .parseMimeType(contentType.getType() + "/" + suffix); Message<?> cloudEventMessage = MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, cloudEventDeserializationContentType) .setHeader(CloudEventMessageUtils.CANONICAL_DATACONTENTTYPE, dataContentType) .build(); Map<String, Object> structuredCloudEvent = (Map<String, Object>) messageConverter.fromMessage(cloudEventMessage, Map.class); Message<?> binaryCeMessage = buildCeMessageFromStructured(structuredCloudEvent, inputMessage.getHeaders()); return binaryCeMessage; } } else if (StringUtils.hasText(attributes.getDataContentType())) { return MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, attributes.getDataContentType()) .build(); } return inputMessage; }
#vulnerable code @SuppressWarnings("unchecked") public static Message<?> toBinary(Message<?> inputMessage, MessageConverter messageConverter) { Map<String, Object> headers = inputMessage.getHeaders(); CloudEventAttributes attributes = new CloudEventAttributes(headers); // first check the obvious and see if content-type is `cloudevents` if (!attributes.isValidCloudEvent() && headers.containsKey(MessageHeaders.CONTENT_TYPE)) { MimeType contentType = contentTypeResolver.resolve(inputMessage.getHeaders()); if (contentType.getType().equals(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getType()) && contentType.getSubtype().startsWith(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getSubtype())) { String dataContentType = StringUtils.hasText(attributes.getDataContentType()) ? attributes.getDataContentType() : MimeTypeUtils.APPLICATION_JSON_VALUE; String suffix = contentType.getSubtypeSuffix(); Assert.hasText(suffix, "Content-type 'suffix' can not be determined from " + contentType); MimeType cloudEventDeserializationContentType = MimeTypeUtils .parseMimeType(contentType.getType() + "/" + suffix); Message<?> cloudEventMessage = MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, cloudEventDeserializationContentType) .setHeader(CloudEventMessageUtils.CANONICAL_DATACONTENTTYPE, dataContentType) .build(); Map<String, Object> structuredCloudEvent = (Map<String, Object>) messageConverter.fromMessage(cloudEventMessage, Map.class); Message<?> binaryCeMessage = buildCeMessageFromStructured(structuredCloudEvent, inputMessage.getHeaders()); return binaryCeMessage; } } else if (StringUtils.hasText(attributes.getDataContentType())) { return MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, attributes.getDataContentType()) .build(); } return inputMessage; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean isRetainOuputAsMessage(Message<?> message) { return message.getHeaders().containsKey(MessageUtils.TARGET_PROTOCOL) || (message.getHeaders().containsKey(MessageUtils.MESSAGE_TYPE) && message.getHeaders().get(MessageUtils.MESSAGE_TYPE).equals(CloudEventMessageUtils.CLOUDEVENT_VALUE)); }
#vulnerable code @Override public boolean isRetainOuputAsMessage(Message<?> message) { return message.getHeaders().containsKey(MessageUtils.MESSAGE_TYPE) && message.getHeaders().get(MessageUtils.MESSAGE_TYPE).equals(CloudEventMessageUtils.CLOUDEVENT_VALUE); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") protected void initialize(ExecutionContext ctxt) { ConfigurableApplicationContext context = AzureSpringFunctionInitializer.context; if (!this.initialized.compareAndSet(false, true)) { return; } if (ctxt != null) { ctxt.getLogger().info("Initializing functions"); } if (context == null) { synchronized (AzureSpringFunctionInitializer.class) { if (context == null) { SpringApplicationBuilder builder = new SpringApplicationBuilder( configurationClass); ClassUtils.overrideThreadContextClassLoader( AzureSpringFunctionInitializer.class.getClassLoader()); context = builder.web(WebApplicationType.NONE).run(); AzureSpringFunctionInitializer.context = context; } } } context.getAutowireCapableBeanFactory().autowireBean(this); if (ctxt != null) { ctxt.getLogger().info("Initialized context: catalog=" + this.catalog); } String name = context.getEnvironment().getProperty("function.name"); if (name == null) { name = "function"; } if (this.catalog == null) { if (context.containsBean(name)) { if (ctxt != null) { ctxt.getLogger() .info("No catalog. Looking for Function bean name=" + name); } this.function = context.getBean(name, Function.class); } } else { Set<String> functionNames = this.catalog.getNames(Function.class); if (functionNames.size() == 1) { this.function = this.catalog.lookup(Function.class, functionNames.iterator().next()); } else { this.function = this.catalog.lookup(Function.class, name); } } }
#vulnerable code @SuppressWarnings("unchecked") protected void initialize(ExecutionContext ctxt) { ConfigurableApplicationContext context = AzureSpringFunctionInitializer.context; if (!this.initialized.compareAndSet(false, true)) { return; } if (ctxt != null) { ctxt.getLogger().info("Initializing functions"); } if (context == null) { synchronized (AzureSpringFunctionInitializer.class) { if (context == null) { SpringApplicationBuilder builder = new SpringApplicationBuilder( configurationClass); ClassUtils.overrideThreadContextClassLoader( AzureSpringFunctionInitializer.class.getClassLoader()); context = builder.web(WebApplicationType.NONE).run(); AzureSpringFunctionInitializer.context = context; } } } context.getAutowireCapableBeanFactory().autowireBean(this); String name = context.getEnvironment().getProperty("function.name"); if (name == null) { name = "function"; } if (this.catalog == null) { this.function = context.getBean(name, Function.class); } else { Set<String> functionNames = this.catalog.getNames(Function.class); if (functionNames.size() == 1) { this.function = this.catalog.lookup(Function.class, functionNames.iterator().next()); } else { this.function = this.catalog.lookup(Function.class, name); } } } #location 44 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { try (InputStream in = proxy != null ? getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy).getInputStream() : getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection().getInputStream()) { CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the Echo SDK"); } return signingCertificate; } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, ex); } }
#vulnerable code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy).getInputStream()) { CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the Echo SDK"); } return signingCertificate; } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, ex); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { for (int attempt = 0; attempt <= CERT_RETRIEVAL_RETRY_COUNT; attempt++) { InputStream in = null; try { HttpURLConnection connection = proxy != null ? (HttpURLConnection)getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy) : (HttpURLConnection)getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(); if (connection.getResponseCode() != 200) { if (waitForRetry(attempt)) { continue; } else { throw new CertificateException("Got a non-200 status code when retrieving certificate at URL: " + signingCertificateChainUrl); } } in = connection.getInputStream(); CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the ASK SDK"); } return signingCertificate; } catch (IOException e) { if (!waitForRetry(attempt)) { throw new CertificateException("Unable to retrieve certificate from URL: " + signingCertificateChainUrl, e); } } catch (Exception e) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, e); } finally { if (in != null) { IOUtils.closeQuietly(in); } } } throw new RuntimeException("Unable to retrieve signing certificate due to an unhandled exception"); }
#vulnerable code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { try (InputStream in = proxy != null ? getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy).getInputStream() : getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection().getInputStream()) { CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the Echo SDK"); } return signingCertificate; } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, ex); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Performance.init(); physicalDatabase = new PhysDB(); memoryDatabase = new MemDB(); updateThread = new UpdateThread(this); // Permissions init permissions = new NoPermissions(); if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else { // Default to Permissions over SuperPermissions, except with SuperpermsBridge Plugin legacy = resolvePlugin("Permissions"); try { // super perms bridge, will throw exception if it's not it if (legacy != null) { if (((com.nijikokun.bukkit.Permissions.Permissions)legacy).getHandler() instanceof com.platymuus.bukkit.permcompat.PermissionHandler) { permissions = new SuperPermsPermissions(); } } } catch (NoClassDefFoundError e) { // Permissions 2/3 or some other bridge if (legacy != null) { permissions = new NijiPermissions(); } } // attempt super perms if we still have nothing if (permissions.getClass() == NoPermissions.class) { try { Method method = CraftHumanEntity.class.getDeclaredMethod("hasPermission", String.class); if (method != null) { permissions = new SuperPermsPermissions(); } } catch(NoSuchMethodException e) { // server does not support SuperPerms } } } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Loading " + Database.DefaultType); try { physicalDatabase.connect(); memoryDatabase.connect(); physicalDatabase.load(); memoryDatabase.load(); log("Using: " + StringUtils.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache lots of protections physicalDatabase.precache(); // tell all modules we're loaded moduleLoader.loadAll(); }
#vulnerable code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Performance.init(); physicalDatabase = new PhysDB(); memoryDatabase = new MemDB(); updateThread = new UpdateThread(this); // Permissions init permissions = new NoPermissions(); if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else { // Default to Permissions over SuperPermissions, except with SuperpermsBridge Plugin legacy = resolvePlugin("Permissions"); try { // super perms bridge if (((com.nijikokun.bukkit.Permissions.Permissions)legacy).getHandler() instanceof com.platymuus.bukkit.permcompat.PermissionHandler) { permissions = new SuperPermsPermissions(); } else { permissions = new NijiPermissions(); } } catch (NoClassDefFoundError e) { } // attempt super perms if we still have nothing if (permissions.getClass() == NoPermissions.class) { try { Method method = CraftHumanEntity.class.getDeclaredMethod("hasPermission", String.class); if (method != null) { permissions = new SuperPermsPermissions(); } } catch(NoSuchMethodException e) { // server does not support SuperPerms } } } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Loading " + Database.DefaultType); try { physicalDatabase.connect(); memoryDatabase.connect(); physicalDatabase.load(); memoryDatabase.load(); log("Using: " + StringUtils.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache lots of protections physicalDatabase.precache(); // tell all modules we're loaded moduleLoader.loadAll(); } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean tryLoadProtection(Block block) { Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); if (protection != null) { // ensure it's the right block if (protection.getBlockId() > 0) { if (protection.isBlockInWorld()) { this.matchedProtection = protection; } else { // Corrupted protection System.out.println("Removing corrupted protection: " + protection); protection.remove(); } } } return this.matchedProtection != null; }
#vulnerable code public boolean tryLoadProtection(Block block) { Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); if (protection != null) { // ensure it's the right block if (protection.getBlockId() > 0) { if (protection.getBlockId() == protection.getBlock().getTypeId()) { this.matchedProtection = protection; } else { // Corrupted protection System.out.println("Removing corrupted protection: " + protection); protection.remove(); } } } return this.matchedProtection != null; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private int getPlayerDropTransferTarget(LWCPlayer player) { Mode mode = player.getMode("dropTransfer"); if (mode == null) { return -1; } String target = mode.getData(); try { return Integer.parseInt(target); } catch (NumberFormatException e) { } return -1; }
#vulnerable code private int getPlayerDropTransferTarget(LWCPlayer player) { Mode mode = player.getMode("dropTransfer"); String target = mode.getData(); try { return Integer.parseInt(target); } catch (NumberFormatException e) { } return -1; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { LWC lwc = LWC.getInstance(); PhysDB physicalDatabase = lwc.getPhysicalDatabase(); // this patcher only does something exciting if you have mysql enabled // :-) if (physicalDatabase.getType() != Type.MySQL) { return; } // this patcher only does something exciting if the old SQLite database // still exists :-) String database = lwc.getConfiguration().getString("database.path"); if (database == null || database.trim().equals("")) { database = "plugins/LWC/lwc.db"; } File file = new File(database); if (!file.exists()) { return; } logger.info("######################################################"); logger.info("######################################################"); logger.info("SQLite to MySQL conversion required"); // rev up those sqlite databases because I sure am hungry for some data... DatabaseMigrator migrator = new DatabaseMigrator(); if (migrator.convertFrom(Type.SQLite)) { logger.info("Successfully converted."); logger.info("Renaming \"" + database + "\" to \"" + database + ".old\""); if (!file.renameTo(new File(database + ".old"))) { logger.info("NOTICE: FAILED TO RENAME lwc.db!! Please rename this manually!"); } logger.info("SQLite to MySQL conversion is now complete!\n"); logger.info("Thank you!"); } else { logger.info("#### SEVERE ERROR: Something bad happened when converting the database (Oops!)"); } logger.info("######################################################"); logger.info("######################################################"); }
#vulnerable code public void run() { LWC lwc = LWC.getInstance(); PhysDB physicalDatabase = lwc.getPhysicalDatabase(); // this patcher only does something exciting if you have mysql enabled // :-) if (physicalDatabase.getType() != Type.MySQL) { return; } // this patcher only does something exciting if the old SQLite database // still exists :-) String database = lwc.getConfiguration().getString("database.path"); if (database == null || database.trim().equals("")) { database = "plugins/LWC/lwc.db"; } File file = new File(database); if (!file.exists()) { return; } logger.info("######################################################"); logger.info("######################################################"); logger.info("SQLite to MySQL conversion required"); logger.info("Loading SQLite"); // rev up those sqlite databases because I sure am hungry for some // data... PhysDB sqliteDatabase = new PhysDB(Type.SQLite); try { sqliteDatabase.connect(); sqliteDatabase.load(); logger.info("SQLite is good to go"); physicalDatabase.getConnection().setAutoCommit(false); logger.info("Preliminary scan..............."); int startProtections = physicalDatabase.getProtectionCount(); int protectionCount = sqliteDatabase.getProtectionCount(); int historyCount = sqliteDatabase.getHistoryCount(); int expectedProtections = protectionCount + startProtections; logger.info("TO CONVERT:"); logger.info("Protections:\t" + protectionCount); logger.info("History:\t" + historyCount); logger.info(""); if (protectionCount > 0) { logger.info("Converting: PROTECTIONS"); List<Protection> tmp = sqliteDatabase.loadProtections(); for (Protection protection : tmp) { // sync it to the live database protection.saveNow(); } logger.info("COMMITTING"); physicalDatabase.getConnection().commit(); logger.info("OK , expecting: " + expectedProtections); if (expectedProtections == (protectionCount = physicalDatabase.getProtectionCount())) { logger.info("OK."); } else { logger.info("Weird, only " + protectionCount + " protections are in the database? Continuing..."); } } if (historyCount > 0) { logger.info("Converting: HISTORY"); List<History> tmp = sqliteDatabase.loadHistory(); for (History history : tmp) { // make sure it's assumed it does not exist in the database history.setExists(false); // sync the history object with the active database (ala MySQL) history.sync(); } logger.info("OK"); } logger.info("Closing SQLite"); sqliteDatabase.getConnection().close(); logger.info("Renaming \"" + database + "\" to \"" + database + ".old\""); if (!file.renameTo(new File(database + ".old"))) { logger.info("NOTICE: FAILED TO RENAME lwc.db!! Please rename this manually!"); } logger.info("SQLite to MySQL conversion is now complete!\n"); logger.info("Thank you!"); } catch (Exception e) { logger.info("#### SEVERE ERROR: Something bad happened when converting the database (Oops!)"); e.printStackTrace(); } try { physicalDatabase.getConnection().setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } logger.info("######################################################"); logger.info("######################################################"); } #location 91 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Add any custom data (if applicable) Set<Plotter> plotters = customData.get(plugin); if (plotters != null) { for (Plotter plotter : plotters) { data += "&" + encode ("Custom" + plotter.getColumnName()) + "=" + encode(Integer.toString(plotter.getValue())); } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } }
#vulnerable code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Statistics.init(); physicalDatabase = new PhysDB(); databaseThread = new DatabaseThread(this); // Permissions init permissions = new SuperPermsPermissions(); if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else if (resolvePlugin("bPermissions") != null) { permissions = new bPermissions(); } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Connecting to " + Database.DefaultType); try { physicalDatabase.connect(); // We're connected, perform any necessary database changes log("Performing any necessary database updates"); physicalDatabase.load(); log("Using database: " + StringUtil.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache protections physicalDatabase.precache(); // We are now done loading! moduleLoader.loadAll(); // Should we try metrics? if (!configuration.getBoolean("optional.optOut", false)) { try { Metrics metrics = new Metrics(); // Create a line graph Metrics.Graph lineGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Line, "Protections"); // Add the total protections plotter lineGraph.addPlotter(new Metrics.Plotter("Total") { @Override public int getValue() { return physicalDatabase.getProtectionCount(); } }); // Create a pie graph for individual protections Metrics.Graph pieGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Pie, "Protection percentages"); for (final Protection.Type type : Protection.Type.values()) { if (type == Protection.Type.RESERVED1 || type == Protection.Type.RESERVED2) { continue; } // Create the plotter Metrics.Plotter plotter = new Metrics.Plotter(StringUtil.capitalizeFirstLetter(type.toString()) + " Protections") { @Override public int getValue() { return physicalDatabase.getProtectionCount(type); } }; // Add it to both graphs lineGraph.addPlotter(plotter); pieGraph.addPlotter(plotter); } metrics.beginMeasuringPlugin(plugin); } catch (IOException e) { log(e.getMessage()); } } }
#vulnerable code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Statistics.init(); physicalDatabase = new PhysDB(); databaseThread = new DatabaseThread(this); // Permissions init permissions = new NoPermissions(); if(permissions.getClass() == NoPermissions.class) { if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else if (resolvePlugin("bPermissions") != null) { permissions = new bPermissions(); } else { try { Method method = CraftHumanEntity.class.getDeclaredMethod("hasPermission", String.class); if (method != null) { permissions = new SuperPermsPermissions(); } } catch(NoSuchMethodException e) { // server does not support SuperPerms } } } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Connecting to " + Database.DefaultType); try { physicalDatabase.connect(); // We're connected, perform any necessary database changes log("Performing any necessary database updates"); physicalDatabase.load(); log("Using database: " + StringUtil.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache protections physicalDatabase.precache(); // We are now done loading! moduleLoader.loadAll(); // Should we try metrics? if (!configuration.getBoolean("optional.optOut", false)) { try { Metrics metrics = new Metrics(); // Create a line graph Metrics.Graph lineGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Line, "Protections"); // Add the total protections plotter lineGraph.addPlotter(new Metrics.Plotter("Total") { @Override public int getValue() { return physicalDatabase.getProtectionCount(); } }); // Create a pie graph for individual protections Metrics.Graph pieGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Pie, "Protection percentages"); for (final Protection.Type type : Protection.Type.values()) { if (type == Protection.Type.RESERVED1 || type == Protection.Type.RESERVED2) { continue; } // Create the plotter Metrics.Plotter plotter = new Metrics.Plotter(StringUtil.capitalizeFirstLetter(type.toString()) + " Protections") { @Override public int getValue() { return physicalDatabase.getProtectionCount(type); } }; // Add it to both graphs lineGraph.addPlotter(plotter); pieGraph.addPlotter(plotter); } metrics.beginMeasuringPlugin(plugin); } catch (IOException e) { log(e.getMessage()); } } } #location 74 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Permission decodeJSON(JSONObject node) { Permission permission = new Permission(); Access access = Access.values()[((Long) node.get("rights")).intValue()]; if (access.ordinal() == 0) { access = Access.PLAYER; } // The values are stored as longs internally, despite us passing an int permission.setName((String) node.get("name")); permission.setType(Type.values()[((Long) node.get("type")).intValue()]); permission.setAccess(access); return permission; }
#vulnerable code public static Permission decodeJSON(JSONObject node) { Permission permission = new Permission(); // The values are stored as longs internally, despite us passing an int permission.setName((String) node.get("name")); permission.setType(Type.values()[((Long) node.get("type")).intValue()]); permission.setAccess(Access.values()[((Long) node.get("rights")).intValue()]); return permission; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Add any custom data (if applicable) Set<Plotter> plotters = customData.get(plugin); if (plotters != null) { for (Plotter plotter : plotters) { data += "&" + encode ("Custom" + plotter.getColumnName()) + "=" + encode(Integer.toString(plotter.getValue())); } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } }
#vulnerable code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static AccessRight decodeJSON(JSONObject node) { AccessRight right = new AccessRight(); // The values are stored as longs internally, despite us passing an int // right.setProtectionId(((Long) node.get("protection")).intValue()); right.setType(((Long) node.get("type")).intValue()); right.setName((String) node.get("name")); right.setRights(((Long) node.get("rights")).intValue()); return right; }
#vulnerable code public static AccessRight decodeJSON(JSONObject node) { AccessRight right = new AccessRight(); // The values are stored as longs internally, despite us passing an int right.setProtectionId(((Long) node.get("protection")).intValue()); right.setType(((Long) node.get("type")).intValue()); right.setName((String) node.get("name")); right.setRights(((Long) node.get("rights")).intValue()); return right; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void initialize(final int cachePercent) throws IOException { cache = new Cache(file.length(), cachePercent); FileWord a; FileWord b = null; synchronized (cache) { position = 0; seek(position); while ((a = nextWord()) != null) { if (b != null && comparator.compare(a.word, b.word) < 0) { throw new IllegalArgumentException("File is not sorted correctly for this comparator"); } b = a; cache.put(size++, position); } } }
#vulnerable code protected void initialize(final int cachePercent) throws IOException { final long fileBytes = file.length(); final long cacheSize = (fileBytes / 100) * cachePercent; final long cacheModulus = cacheSize == 0 ? fileBytes : cacheSize > fileBytes ? 1 : fileBytes / cacheSize; if (cache == null) { throw new IllegalStateException("Cannot initialize after close has been called."); } FileWord a; FileWord b = null; synchronized (cache) { position = 0; seek(0); cache.clear(); while ((a = nextWord()) != null) { if (b != null && comparator.compare(a.word, b.word) < 0) { throw new IllegalArgumentException("File is not sorted correctly for this comparator"); } b = a; if (cacheSize > 0 && size % cacheModulus == 0) { cache.put(size, a.offset); } size++; } } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpConfig files(String[] filePaths, String inputName, boolean forceRemoveContentTypeChraset) { // synchronized (getClass()) { // if(this.map==null){ // this.map= new HashMap<String, Object>(); // } // } // map.put(Utils.ENTITY_MULTIPART, filePaths); // map.put(Utils.ENTITY_MULTIPART+".name", inputName); // map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); Map<String, Object> m = maps.get(); if(m==null || m==null){ m = new HashMap<String, Object>(); } m.put(Utils.ENTITY_MULTIPART, filePaths); m.put(Utils.ENTITY_MULTIPART+".name", inputName); m.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); maps.set(m); return this; }
#vulnerable code public HttpConfig files(String[] filePaths, String inputName, boolean forceRemoveContentTypeChraset) { synchronized (getClass()) { if(this.map==null){ this.map= new HashMap<String, Object>(); } } map.put(Utils.ENTITY_MULTIPART, filePaths); map.put(Utils.ENTITY_MULTIPART+".name", inputName); map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); return this; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpConfig json(String json) { this.json = json; Map<String, Object> map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); maps.set(map); return this; }
#vulnerable code public HttpConfig json(String json) { this.json = json; map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); return this; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Map<String, Object> map() { // return map; return maps.get(); }
#vulnerable code public Map<String, Object> map() { return map; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpConfig json(String json) { this.json = json; Map<String, Object> map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); maps.set(map); return this; }
#vulnerable code public HttpConfig json(String json) { this.json = json; map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); return this; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static String usageString(CommandLine commandLine, Help.Ansi ansi) throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); commandLine.usage(new PrintStream(baos, true, "UTF8"), ansi); String result = baos.toString("UTF8"); if (ansi == Help.Ansi.AUTO) { baos.reset(); commandLine.usage(new PrintStream(baos, true, "UTF8")); assertEquals(result, baos.toString("UTF8")); } else if (ansi == Help.Ansi.ON) { baos.reset(); commandLine.usage(new PrintStream(baos, true, "UTF8"), Help.defaultColorScheme(Help.Ansi.ON)); assertEquals(result, baos.toString("UTF8")); } return result; }
#vulnerable code private static String usageString(CommandLine commandLine, Help.Ansi ansi) throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); commandLine.usage(new PrintStream(baos, true, "UTF8"), ansi); String result = baos.toString("UTF8"); return result; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void verify(final UChannel channel,String extension, final ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); final String ts = json.getString("ts"); final String playerId = json.getString("playerId"); final String accessToken = json.getString("accessToken"); final String nickname = json.getString("nickName"); SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", ""); callback.onSuccess(vResult); ///2016-10-27 华为这版本流程这里,分为两步,这里不便服务器端做验证,注释下面这些 // StringBuilder sb = new StringBuilder(); // sb.append(channel.getCpAppID()).append(ts).append(playerId); // boolean ok = RSAUtil.verify(sb.toString().getBytes("UTF-8"), LOGIN_RSA_PUBLIC, accessToken); // if(ok){ // // SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", nickname); // // callback.onSuccess(vResult); // }else{ // callback.onFailed(channel.getMaster().getSdkName() + " verify failed."); // } }catch (Exception e){ e.printStackTrace(); callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); } }
#vulnerable code @Override public void verify(final UChannel channel,String extension, final ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); final String ts = json.getString("ts"); final String playerId = json.getString("playerId"); final String accessToken = json.getString("accessToken"); final String nickname = json.getString("nickName"); StringBuilder sb = new StringBuilder(); sb.append(channel.getCpAppID()).append(ts).append(playerId); boolean ok = RSAUtil.verify(sb.toString().getBytes("UTF-8"), LOGIN_RSA_PUBLIC, accessToken); if(ok){ SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", nickname); callback.onSuccess(vResult); }else{ callback.onFailed(channel.getMaster().getSdkName() + " verify failed."); } }catch (Exception e){ e.printStackTrace(); callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); } } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testOverridenFields() throws Exception { MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); MappingFileData mappingFileData = fileReader.read("overridemapping.xml"); MappingsParser mappingsParser = MappingsParser.getInstance(); mappingsParser.processMappings(mappingFileData.getClassMaps(), mappingFileData.getConfiguration()); // validate class mappings for (ClassMap classMap : mappingFileData.getClassMaps()) { if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.FurtherTestObject")) { assertTrue(classMap.isStopOnErrors()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.SuperSuperSuperClass")) { assertTrue(classMap.isWildcard()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.TestObject")) { assertTrue(!(classMap.getFieldMaps().get(0)).isCopyByReference()); } } }
#vulnerable code @Test public void testOverridenFields() throws Exception { MappingFileReader fileReader = new MappingFileReader("overridemapping.xml"); MappingFileData mappingFileData = fileReader.read(); MappingsParser mappingsParser = MappingsParser.getInstance(); mappingsParser.processMappings(mappingFileData.getClassMaps(), mappingFileData.getConfiguration()); // validate class mappings Iterator<?> iter = mappingFileData.getClassMaps().iterator(); while (iter.hasNext()) { ClassMap classMap = (ClassMap) iter.next(); if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.FurtherTestObject")) { assertTrue(classMap.isStopOnErrors()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.SuperSuperSuperClass")) { assertTrue(classMap.isWildcard()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.TestObject")) { assertTrue(!(classMap.getFieldMaps().get(0)).isCopyByReference()); } } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, FieldMap fieldMap) { // follow deep field hierarchy. If any values are null along the way, then create a new instance DeepHierarchyElement[] hierarchy = getDeepFieldHierarchy(destObj, fieldMap.getDestDeepIndexHintContainer()); // first, iteratate through hierarchy and instantiate any objects that are null Object parentObj = destObj; int hierarchyLength = hierarchy.length - 1; int hintIndex = 0; for (int i = 0; i < hierarchyLength; i++) { DeepHierarchyElement hierarchyElement = hierarchy[i]; PropertyDescriptor pd = hierarchyElement.getPropDescriptor(); Object value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); Class clazz; if (value == null) { clazz = pd.getPropertyType(); if (clazz.isInterface() && (i + 1) == hierarchyLength && fieldMap.getDestHintContainer() != null) { // before setting the property on the destination object we should check for a destination hint. need to know // that we are at the end of the line determine the property type clazz = fieldMap.getDestHintContainer().getHint(); } Object o = null; if (clazz.isArray()) { o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(clazz.getComponentType()), hierarchyElement.getIndex()); } else if (Collection.class.isAssignableFrom(clazz)) { Class collectionEntryType; Class genericType = ReflectionUtils.determineGenericsType(pd); if (genericType != null) { collectionEntryType = genericType; } else { collectionEntryType = fieldMap.getDestDeepIndexHintContainer().getHint(hintIndex); //hint index is used to handle multiple hints hintIndex += 1; } o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(collectionEntryType), hierarchyElement .getIndex()); } else { try { o = DestBeanCreator.create(clazz); } catch (Exception e) { //lets see if they have a factory we can try as a last ditch. If not...throw the exception: if (fieldMap.getClassMap().getDestClassBeanFactory() != null) { o = DestBeanCreator.create(null, fieldMap.getClassMap().getSrcClassToMap(), clazz, clazz, fieldMap.getClassMap() .getDestClassBeanFactory(), fieldMap.getClassMap().getDestClassBeanFactoryId(), null); } else { MappingUtils.throwMappingException(e); } } } ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { o }); value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); } //Check to see if collection needs to be resized if (MappingUtils.isSupportedCollection(value.getClass())) { int currentSize = CollectionUtils.getLengthOfCollection(value); if (currentSize < hierarchyElement.getIndex() + 1) { value = MappingUtils.prepareIndexedCollection(pd.getPropertyType(), value, DestBeanCreator.create(pd.getPropertyType() .getComponentType()), hierarchyElement.getIndex()); ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { value }); } } if (value != null && value.getClass().isArray()) { parentObj = Array.get(value, hierarchyElement.getIndex()); } else if (value != null && Collection.class.isAssignableFrom(value.getClass())) { parentObj = MappingUtils.getIndexedValue(value, hierarchyElement.getIndex()); } else { parentObj = value; } } // second, set the very last field in the deep hierarchy PropertyDescriptor pd = hierarchy[hierarchy.length - 1].getPropDescriptor(); Class type; // For one-way mappings there could be no read method if (pd.getReadMethod() != null) { type = pd.getReadMethod().getReturnType(); } else { type = pd.getWriteMethod().getParameterTypes()[0]; } if (!type.isPrimitive() || destFieldValue != null) { if (!isIndexed) { Method method = null; if (!isCustomSetMethod()) { method = pd.getWriteMethod(); } else { try { method = ReflectionUtils.findAMethod(parentObj.getClass(), getSetMethodName()); } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } } ReflectionUtils.invoke(method, parentObj, new Object[] { destFieldValue }); } else { writeIndexedValue(parentObj, destFieldValue); } } }
#vulnerable code protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, FieldMap fieldMap) { // follow deep field hierarchy. If any values are null along the way, then create a new instance DeepHierarchyElement[] hierarchy = getDeepFieldHierarchy(destObj, fieldMap.getDestDeepIndexHintContainer()); // first, iteratate through hierarchy and instantiate any objects that are null Object parentObj = destObj; int hierarchyLength = hierarchy.length - 1; int hintIndex = 0; for (int i = 0; i < hierarchyLength; i++) { DeepHierarchyElement hierarchyElement = hierarchy[i]; PropertyDescriptor pd = hierarchyElement.getPropDescriptor(); Object value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); Class clazz; if (value == null) { clazz = pd.getPropertyType(); if (clazz.isInterface() && (i + 1) == hierarchyLength && fieldMap.getDestHintContainer() != null) { // before setting the property on the destination object we should check for a destination hint. need to know // that we are at the end of the line determine the property type clazz = fieldMap.getDestHintContainer().getHint(); } Object o = null; if (clazz.isArray()) { o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(clazz.getComponentType()), hierarchyElement.getIndex()); } else if (Collection.class.isAssignableFrom(clazz)) { Class collectionEntryType; Class genericType = ReflectionUtils.determineGenericsType(pd); if (genericType != null) { collectionEntryType = genericType; } else { collectionEntryType = fieldMap.getDestDeepIndexHintContainer().getHint(hintIndex); //hint index is used to handle multiple hints hintIndex += 1; } o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(collectionEntryType), hierarchyElement .getIndex()); } else { try { o = DestBeanCreator.create(clazz); } catch (Exception e) { //lets see if they have a factory we can try as a last ditch. If not...throw the exception: if (fieldMap.getClassMap().getDestClassBeanFactory() != null) { o = DestBeanCreator.create(null, fieldMap.getClassMap().getSrcClassToMap(), clazz, clazz, fieldMap.getClassMap() .getDestClassBeanFactory(), fieldMap.getClassMap().getDestClassBeanFactoryId(), null); } else { MappingUtils.throwMappingException(e); } } } ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { o }); value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); } //Check to see if collection needs to be resized if (MappingUtils.isSupportedCollection(value.getClass())) { int currentSize = CollectionUtils.getLengthOfCollection(value); if (currentSize < hierarchyElement.getIndex() + 1) { value = MappingUtils.prepareIndexedCollection(pd.getPropertyType(), value, DestBeanCreator.create(pd.getPropertyType().getComponentType()), hierarchyElement.getIndex()); ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { value }); } } if (value != null && value.getClass().isArray()) { parentObj = Array.get(value, hierarchyElement.getIndex()); } else if (value != null && Collection.class.isAssignableFrom(value.getClass())) { parentObj = MappingUtils.getIndexedValue(value, hierarchyElement.getIndex()); } else { parentObj = value; } } // second, set the very last field in the deep hierarchy PropertyDescriptor pd = hierarchy[hierarchy.length - 1].getPropDescriptor(); Class type; // For one-way mappings there could be no read method if (pd.getReadMethod() != null) { type = pd.getReadMethod().getReturnType(); } else { type = pd.getWriteMethod().getParameterTypes()[0]; } if (!type.isPrimitive() || destFieldValue != null) { if (!isIndexed) { Method method = pd.getWriteMethod(); try { if (method == null && getSetMethodName() != null) { // lets see if we can find a custom method method = ReflectionUtils.findAMethod(parentObj.getClass(), getSetMethodName()); } } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } ReflectionUtils.invoke(method, parentObj, new Object[] { destFieldValue }); } else { writeIndexedValue(parentObj, destFieldValue); } } } #location 96 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDuplicateMapIds() throws Exception { MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); MappingFileData mappingFileData = fileReader.read("duplicateMapIdsMapping.xml"); try { parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); fail("should have thrown exception"); } catch (Exception e) { assertTrue("invalid exception thrown", e.getMessage().indexOf("Duplicate Map Id") != -1); } }
#vulnerable code @Test public void testDuplicateMapIds() throws Exception { MappingFileReader fileReader = new MappingFileReader("duplicateMapIdsMapping.xml"); MappingFileData mappingFileData = fileReader.read(); try { parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); fail("should have thrown exception"); } catch (Exception e) { assertTrue("invalid exception thrown", e.getMessage().indexOf("Duplicate Map Id") != -1); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } BeanContainer beanContainer = BeanContainer.getInstance(); registerClassLoader(globalSettings, classLoader, beanContainer); registerProxyResolver(globalSettings, beanContainer); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } }
#vulnerable code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } String classLoaderName = globalSettings.getClassLoaderName(); String proxyResolverName = globalSettings.getProxyResolverName(); DefaultClassLoader defaultClassLoader = new DefaultClassLoader(classLoader); BeanContainer beanContainer = BeanContainer.getInstance(); Class<? extends DozerClassLoader> classLoaderType = loadBeanType(classLoaderName, defaultClassLoader, DozerClassLoader.class); Class<? extends DozerProxyResolver> proxyResolverType = loadBeanType(proxyResolverName, defaultClassLoader, DozerProxyResolver.class); // TODO Chicken-egg problem - investigate // DozerClassLoader classLoaderBean = ReflectionUtils.newInstance(classLoaderType); DozerClassLoader classLoaderBean = defaultClassLoader; DozerProxyResolver proxyResolverBean = ReflectionUtils.newInstance(proxyResolverType); beanContainer.setClassLoader(classLoaderBean); beanContainer.setProxyResolver(proxyResolverBean); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getBeanId() { Class<?> factoryClass = objectFactory(destObjClass).getClass(); Class<?> destClass = null; String methodName = "create" + destObjClass.substring(destObjClass.lastIndexOf(".") + 1) + StringUtils.capitalize(destFieldName); try { Method method = ReflectionUtils.findAMethod(factoryClass, methodName); Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterClass : parameterTypes) { destClass = parameterClass; break; } } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } return (destClass != null) ? destClass.getCanonicalName() : null; }
#vulnerable code public String getBeanId() { Class<?> factoryClass = objectFactory(destObjClass).getClass(); Class<?> destClass = null; String methodName = "create" + destObjClass.substring(destObjClass.lastIndexOf(".") + 1) + StringUtils.capitalize(destFieldName); try { Method method = ReflectionUtils.findAMethod(factoryClass, methodName); Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterClass : parameterTypes) { destClass = parameterClass; break; } } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } return destClass.getCanonicalName(); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getValue() { return value.get(); }
#vulnerable code public long getValue() { return value; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } BeanContainer beanContainer = BeanContainer.getInstance(); registerClassLoader(globalSettings, classLoader, beanContainer); registerProxyResolver(globalSettings, beanContainer); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } }
#vulnerable code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } String classLoaderName = globalSettings.getClassLoaderName(); String proxyResolverName = globalSettings.getProxyResolverName(); DefaultClassLoader defaultClassLoader = new DefaultClassLoader(classLoader); BeanContainer beanContainer = BeanContainer.getInstance(); Class<? extends DozerClassLoader> classLoaderType = loadBeanType(classLoaderName, defaultClassLoader, DozerClassLoader.class); Class<? extends DozerProxyResolver> proxyResolverType = loadBeanType(proxyResolverName, defaultClassLoader, DozerProxyResolver.class); // TODO Chicken-egg problem - investigate // DozerClassLoader classLoaderBean = ReflectionUtils.newInstance(classLoaderType); DozerClassLoader classLoaderBean = defaultClassLoader; DozerProxyResolver proxyResolverBean = ReflectionUtils.newInstance(proxyResolverType); beanContainer.setClassLoader(classLoaderBean); beanContainer.setProxyResolver(proxyResolverBean); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static boolean isEnumType(Class srcFieldClass, Class destFieldType){ if (GlobalSettings.getInstance().isJava5()){//Verify if running JRE is 1.5 or above if ( ((Boolean) ReflectionUtils.invoke(Jdk5Methods.getInstance().getIsAnonymousClassMethod(), srcFieldClass, null)).booleanValue()) { //If srcFieldClass is anonymous class, replace srcFieldClass with its enclosing class. //This is used to ensure Dozer can get correct Enum type. srcFieldClass = (Class) ReflectionUtils.invoke(Jdk5Methods.getInstance().getGetEnclosingClassMethod(), srcFieldClass, null); } if ( ((Boolean) ReflectionUtils.invoke(Jdk5Methods.getInstance().getIsAnonymousClassMethod(), destFieldType, null)).booleanValue()) { //Just like srcFieldClass, if destFieldType is anonymous class, replace destFieldType with //its enclosing class. This is used to ensure Dozer can get correct Enum type. destFieldType = (Class) ReflectionUtils.invoke(Jdk5Methods.getInstance().getGetEnclosingClassMethod(), destFieldType, null); } return ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), srcFieldClass, null)) .booleanValue() && ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), destFieldType, null)) .booleanValue(); } return false; }
#vulnerable code public static boolean isEnumType(Class srcFieldClass, Class destFieldType){ if (GlobalSettings.getInstance().isJava5()){//Verify if running JRE is 1.5 or above if (srcFieldClass.isAnonymousClass()){ //If srcFieldClass is anonymous class, replace srcFieldClass with its enclosing class. //This is used to ensure Dozer can get correct Enum type. srcFieldClass = srcFieldClass.getEnclosingClass(); } if (destFieldType.isAnonymousClass()){ //Just like srcFieldClass, if destFieldType is anonymous class, replace destFieldType with //its enclosing class. This is used to ensure Dozer can get correct Enum type. destFieldType = destFieldType.getEnclosingClass(); } return ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), srcFieldClass, null)) .booleanValue() && ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), destFieldType, null)) .booleanValue(); } return false; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getScript(String path) { StringBuilder sb = new StringBuilder(); InputStream stream = ScriptUtil.class.getClassLoader().getResourceAsStream(path); try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))){ String str; while ((str = br.readLine()) != null) { sb.append(str).append(System.lineSeparator()); } } catch (IOException e) { System.err.println(e.getStackTrace()); } return sb.toString(); }
#vulnerable code public static String getScript(String path) { StringBuilder sb = new StringBuilder(); InputStream stream = ScriptUtil.class.getClassLoader().getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); try { String str = ""; while ((str = br.readLine()) != null) { sb.append(str).append(System.lineSeparator()); } } catch (IOException e) { System.err.println(e.getStackTrace()); } return sb.toString(); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean limit() { String key = String.valueOf(System.currentTimeMillis() / 1000); Object result = null; try { RedisClusterConnection clusterConnection = jedis.getClusterConnection(); JedisCluster jedisCluster = (JedisCluster) clusterConnection.getNativeConnection(); result = jedisCluster.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); if (FAIL_CODE != (Long) result) { return true; } else { return false; } }catch (InvalidDataAccessApiUsageException e){ } Jedis jedisConn = (Jedis)jedis.getConnection().getNativeConnection() ; result = jedisConn.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); if (FAIL_CODE != (Long) result) { return true; } else { return false; } }
#vulnerable code public boolean limit() { String key = String.valueOf(System.currentTimeMillis() / 1000); Object result = null; RedisClusterConnection clusterConnection = jedis.getClusterConnection(); if (clusterConnection != null){ JedisCluster jedisCluster = (JedisCluster) clusterConnection.getNativeConnection(); result = jedisCluster.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); }else { Jedis jedis = (Jedis) clusterConnection.getNativeConnection(); result = jedis.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); } if (FAIL_CODE != (Long) result) { return true; } else { return false; } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final void build() { LOGGER.info("Starting tree reconstruction"); Project inbox = beanFactory.getBean("project", Project.class); inbox.setName("Inbox"); inbox.setId("__%%Inbox"); // to give deterministic JSON/XML output Context noContext = beanFactory.getBean("context", Context.class); noContext.setName("No Context"); noContext.setId("__%%NoContext"); // to give deterministic JSON/XML output ConfigParams configParams = beanFactory.getBean("configparams", ConfigParams.class); // Build Folder Hierarchy for (Folder folder : folders.values()) { String parentId = folder.getParentFolderId(); if (parentId != null) { Folder parent = folders.get(parentId); parent.add(folder); } } // Build Task Hierarchy for (Task task : tasks.values()) { String parentId = task.getParentTaskId(); if (parentId != null) { Task parent = tasks.get(parentId); parent.add(task); } if (task.isInInbox() && task.getParentTaskId() == null) { inbox.add(task); } if (task.getContextId() == null) { noContext.add(task); } } // Build Context Hierarchy for (Context context : contexts.values()) { String parentId = context.getParentContextId(); if (parentId != null) { Context parent = contexts.get(parentId); parent.add(context); } } // Add tasks to contexts for (Task task : tasks.values()) { String contextId = task.getContextId(); if (contextId != null) { Context context = contexts.get(contextId); context.getTasks().add(task); task.setContext(context); } } // Create Projects from their root tasks // Must do this after task hierarchy is woven // since a copy of the root tasks subtasks is taken for (ProjectInfo projInfo : projInfos.values()) { Task rootTask = tasks.get(projInfo.getRootTaskId()); Project project = new Project(projInfo, rootTask); project.setConfigParams(configParams); // Set containing Folder for project String folderId = projInfo.getFolderId(); if (folderId != null) { Folder folder = folders.get(folderId); folder.add(project); } projects.put(project.getId(), project); // Discard the root task. But note that it'll still be // a child in any contexts tasks.remove(rootTask.getId()); } if (!inbox.getTasks().isEmpty()) { projects.put(inbox.getId(), inbox); } if (!noContext.getTasks().isEmpty()) { contexts.put(noContext.getId(), noContext); } LOGGER.info("Finished tree reconstruction"); }
#vulnerable code public final void build() { LOGGER.info("Starting tree reconstruction"); Project inbox = new Project(); inbox.setName("Inbox"); inbox.setId("__%%Inbox"); // to give deterministic JSON/XML output Context noContext = new Context(); noContext.setName("No Context"); noContext.setId("__%%NoContext"); // to give deterministic JSON/XML output // Build Folder Hierarchy for (Folder folder : folders.values()) { String parentId = folder.getParentFolderId(); if (parentId != null) { Folder parent = folders.get(parentId); parent.add(folder); } } // Build Task Hierarchy for (Task task : tasks.values()) { String parentId = task.getParentTaskId(); if (parentId != null) { Task parent = tasks.get(parentId); parent.add(task); } if (task.isInInbox() && task.getParentTaskId() == null) { inbox.add(task); } if (task.getContextId() == null) { noContext.add(task); } } // Build Context Hierarchy for (Context context : contexts.values()) { String parentId = context.getParentContextId(); if (parentId != null) { Context parent = contexts.get(parentId); parent.add(context); } } // Add tasks to contexts for (Task task : tasks.values()) { String contextId = task.getContextId(); if (contextId != null) { Context context = contexts.get(contextId); context.getTasks().add(task); task.setContext(context); } } // Create Projects from their root tasks // Must do this after task hierarchy is woven // since a copy of the root tasks subtasks is taken for (ProjectInfo projInfo : projInfos.values()) { Task rootTask = tasks.get(projInfo.getRootTaskId()); Project project = new Project(projInfo, rootTask); // Set containing Folder for project String folderId = projInfo.getFolderId(); if (folderId != null) { Folder folder = folders.get(folderId); folder.add(project); } projects.put(project.getId(), project); // Discard the root task. But note that it'll still be // a child in any contexts tasks.remove(rootTask.getId()); } if (!inbox.getTasks().isEmpty()) { projects.put(inbox.getId(), inbox); } if (!noContext.getTasks().isEmpty()) { contexts.put(noContext.getId(), noContext); } LOGGER.info("Finished tree reconstruction"); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean within(Date date, String lower, String upper) throws ParseException { LOGGER.debug("within({},{},{})", date, lower, upper); Date lowerDate = date(lower); Date upperDate = date(upper); boolean result = date != null && date.getTime() >= lowerDate.getTime() && date.getTime() <= upperDate.getTime(); LOGGER.debug("within({},{},{})={}", date, lower, upper, result); return result; }
#vulnerable code public boolean within(Date date, String lower, String upper) throws ParseException { Date lowerDate = date(lower); Date upperDate = date(upper); return date != null && date.getTime() >= lowerDate.getTime() && date.getTime() <= upperDate.getTime(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { ApplicationContext appContext = ApplicationContextFactory.getContext(); Main main = appContext.getBean("main", Main.class); if (!main.procesPreLoadOptions(args)) { LOGGER.debug("Exiting"); return; } main.loadData(); main.processPostLoadOptions(args); main.run(); LOGGER.debug("Exiting"); }
#vulnerable code public static void main(String[] args) throws Exception { ApplicationContext appContext = ApplicationContextFactory.create(); Main main = appContext.getBean("main", Main.class); if (!main.procesPreLoadOptions(args)) { LOGGER.debug("Exiting"); return; } main.loadData(); main.processPostLoadOptions(args); main.run(); LOGGER.debug("Exiting"); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void writeToLog(String type, String content) { writerThread.execute(()->{ String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } }); }
#vulnerable code private void writeToLog(String type, String content) { String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { final String fileId = request.getParameter("fileId"); if (fileId != null) { final Node f = this.fm.queryById(fileId); if (f != null) { final String fileBlocks = ConfigureReader.instance().getFileBlockPath(); final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath()); downloadRangeFile(request, response, fo, f.getFileName());// 使用断点续传执行下载 this.lu.writeDownloadFileEvent(request, f); } } } }
#vulnerable code public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { final String fileId = request.getParameter("fileId"); if (fileId != null) { final Node f = this.fm.queryById(fileId); if (f != null) { final String fileBlocks = ConfigureReader.instance().getFileBlockPath(); final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath()); try { final FileInputStream fis = new FileInputStream(fo); response.setContentType("application/force-download"); response.setHeader("Content-Length", "" + fo.length()); response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(f.getFileName(), "UTF-8")); final int buffersize = ConfigureReader.instance().getBuffSize(); final byte[] buffer = new byte[buffersize]; final BufferedInputStream bis = new BufferedInputStream(fis); final OutputStream os = (OutputStream) response.getOutputStream(); int index = 0; while ((index = bis.read(buffer)) != -1) { os.write(buffer, 0, index); } bis.close(); fis.close(); this.lu.writeDownloadFileEvent(request, f); } catch (Exception ex) { } } } } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void writeToLog(String type, String content) { writerThread.execute(()->{ String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } }); }
#vulnerable code private void writeToLog(String type, String content) { String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String fname = request.getParameter("fname"); final String originalFileName = (fname != null ? fname : file.getOriginalFilename()); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } }
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String fname = request.getParameter("fname"); final String originalFileName = (fname != null ? fname : file.getOriginalFilename()).replaceAll("\"", "_"); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String fname = request.getParameter("fname"); final String originalFileName = fname != null ? fname : file.getOriginalFilename(); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } }
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void writeRangeFileStream(HttpServletRequest request, HttpServletResponse response, File fo, String fname, String contentType) { long fileLength = fo.length(); // 记录文件大小 long pastLength = 0; // 记录已下载文件大小 int rangeSwitch = 0; // 0:从头开始的全文下载;1:从某字节开始的下载(bytes=27000-);2:从某字节开始到某字节结束的下载(bytes=27000-39000) long toLength = 0; // 记录客户端需要下载的字节段的最后一个字节偏移量(比如bytes=27000-39000,则这个值是为39000) long contentLength = 0; // 客户端请求的字节总量 String rangeBytes = ""; // 记录客户端传来的形如“bytes=27000-”或者“bytes=27000-39000”的内容 OutputStream os = null; // 写出数据 OutputStream out = null; // 缓冲 byte b[] = new byte[ConfigureReader.instance().getBuffSize()]; // 暂存容器 if (request.getHeader("Range") != null) { // 客户端请求的下载的文件块的开始字节 response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT); rangeBytes = request.getHeader("Range").replaceAll("bytes=", ""); if (rangeBytes.indexOf('-') == rangeBytes.length() - 1) {// bytes=969998336- rangeSwitch = 1; rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-')); pastLength = Long.parseLong(rangeBytes.trim()); contentLength = fileLength - pastLength; // 客户端请求的是 969998336 之后的字节 } else { // bytes=1275856879-1275877358 rangeSwitch = 2; String temp0 = rangeBytes.substring(0, rangeBytes.indexOf('-')); String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1, rangeBytes.length()); pastLength = Long.parseLong(temp0.trim()); // bytes=1275856879-1275877358,从第 1275856879 个字节开始下载 toLength = Long.parseLong(temp2); // bytes=1275856879-1275877358,到第 1275877358 个字节结束 contentLength = toLength - pastLength; // 客户端请求的是 1275856879-1275877358 之间的字节 } } else { // 从开始进行下载 contentLength = fileLength; // 客户端要求全文下载 } /** * 如果设设置了Content -Length,则客户端会自动进行多线程下载。如果不希望支持多线程,则不要设置这个参数。 响应的格式是: Content - * Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节] * ServletActionContext.getResponse().setHeader("Content- Length", new * Long(file.length() - p).toString()); */ response.setHeader("Accept-Ranges", "bytes");// 如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1 200 OK if (pastLength != 0) { // 不是从最开始下载, // 响应的格式是: // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小] switch (rangeSwitch) { case 1: { // 针对 bytes=27000- 的请求 String contentRange = new StringBuffer("bytes ").append(new Long(pastLength).toString()).append("-") .append(new Long(fileLength - 1).toString()).append("/").append(new Long(fileLength).toString()) .toString(); response.setHeader("Content-Range", contentRange); break; } case 2: { // 针对 bytes=27000-39000 的请求 String contentRange = new StringBuffer("bytes ").append(rangeBytes).append("/").append(new Long(fileLength).toString()).toString(); response.setHeader("Content-Range", contentRange); break; } default: { break; } } } else { // 是从开始下载 } response.addHeader("Content-Disposition", "attachment; filename=\"" + fname + "\""); response.setContentType(contentType); // set the MIME type. response.addHeader("Content-Length", String.valueOf(contentLength)); try (RandomAccessFile raf = new RandomAccessFile(fo, "r")) { os = response.getOutputStream(); out = new BufferedOutputStream(os); System.out.println("--Range Download--"); System.out.println("Content-Type:"+response.getContentType()); System.out.println("Content-Length:"+response.getHeader("Content-Length")); System.out.println("Content-Range:"+response.getHeader("Content-Range")); System.out.println("--Range Download--"); switch (rangeSwitch) { case 0: { // 普通下载,或者从头开始的下载 // 同1 } case 1: { // 针对 bytes=27000- 的请求 raf.seek(pastLength); // 形如 bytes=969998336- 的客户端请求,跳过 969998336 个字节 int n = 0; while ((n = raf.read(b)) != -1) { out.write(b, 0, n); } break; } case 2: { // 针对 bytes=27000-39000 的请求 raf.seek(pastLength); // 形如 bytes=1275856879-1275877358 的客户端请求,找到第 1275856879 个字节 int n = 0; long readLength = 0; // 记录已读字节数 while (readLength <= contentLength) {// 大部分字节在这里读取 n = raf.read(b); readLength += n; out.write(b, 0, n); } break; } default: { break; } } out.flush(); } catch (IOException ex) { } finally { } }
#vulnerable code protected void writeRangeFileStream(HttpServletRequest request, HttpServletResponse response, File fo, String fname, String contentType) { long skipLength = 0;// 下载时跳过的字节数 long downLength = 0;// 需要继续下载的字节数 boolean hasEnd = false;// 是否具备结束字节声明 try { response.setHeader("Accept-Ranges", "bytes");// 支持断点续传声明 // 获取已下载字节数和需下载字节数 String rangeLabel = request.getHeader("Range");// 获取下载长度声明 if (null != rangeLabel) { // 当进行断点续传时,返回响应码206 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 解析下载跳过长度和继续长度 rangeLabel = request.getHeader("Range").replaceAll("bytes=", ""); if (rangeLabel.indexOf('-') == rangeLabel.length() - 1) { hasEnd = false; rangeLabel = rangeLabel.substring(0, rangeLabel.indexOf('-')); skipLength = Long.parseLong(rangeLabel.trim()); } else { hasEnd = true; String startBytes = rangeLabel.substring(0, rangeLabel.indexOf('-')); String endBytes = rangeLabel.substring(rangeLabel.indexOf('-') + 1, rangeLabel.length()); skipLength = Long.parseLong(startBytes.trim()); downLength = Long.parseLong(endBytes); } } // 设置响应中文件块声明 long fileLength = fo.length();// 文件长度 if (0 != skipLength) { String contentRange = ""; if (hasEnd) { contentRange = new StringBuffer(rangeLabel).append("/").append(new Long(fileLength).toString()) .toString(); } else { contentRange = new StringBuffer("bytes").append(new Long(skipLength).toString()).append("-") .append(new Long(fileLength - 1).toString()).append("/") .append(new Long(fileLength).toString()).toString(); } response.setHeader("Content-Range", contentRange); } // 开始执行下载 response.setContentType(contentType); response.setHeader("Content-Length", "" + fileLength); response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fname, "UTF-8")); final int buffersize = ConfigureReader.instance().getBuffSize(); final byte[] buffer = new byte[buffersize]; final RandomAccessFile raf = new RandomAccessFile(fo, "r"); final OutputStream os = (OutputStream) response.getOutputStream(); raf.seek(skipLength);// 跳过已经下载的字节数 if (hasEnd) { while (raf.getFilePointer() < downLength) { os.write(raf.read()); } } else { int index = 0; while ((index = raf.read(buffer)) != -1) { os.write(buffer, 0, index); } } raf.close(); os.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 62 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void getCondensedPicture(final HttpServletRequest request, final HttpServletResponse response) { // TODO 自动生成的方法存根 if (ConfigureReader.instance().authorized((String) request.getSession().getAttribute("ACCOUNT"), AccountAuth.DOWNLOAD_FILES)) { String fileId = request.getParameter("fileId"); if (fileId != null) { Node node = fm.queryById(fileId); if (node != null) { File pBlock = fbu.getFileFromBlocks(node); if (pBlock != null && pBlock.exists()) { try { int pSize = Integer.parseInt(node.getFileSize()); if (pSize < 3) { Thumbnails.of(pBlock).size(1024, 1024).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else if (pSize < 5) { Thumbnails.of(pBlock).size(1440, 1440).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else { Thumbnails.of(pBlock).size(1680, 1680).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } } catch (IOException e) { // TODO 自动生成的 catch 块 // 压缩失败时,尝试以源文件进行预览 try { Files.copy(pBlock.toPath(), response.getOutputStream()); } catch (IOException e1) { // TODO 自动生成的 catch 块 } } } } } } }
#vulnerable code @Override public void getCondensedPicture(final HttpServletRequest request, final HttpServletResponse response) { // TODO 自动生成的方法存根 if (ConfigureReader.instance().authorized((String) request.getSession().getAttribute("ACCOUNT"), AccountAuth.DOWNLOAD_FILES)) { String fileId = request.getParameter("fileId"); if (fileId != null) { Node node = fm.queryById(fileId); if (node != null) { File pBlock = fbu.getFileFromBlocks(node); if (pBlock.exists()) { try { int pSize = Integer.parseInt(node.getFileSize()); if (pSize < 3) { Thumbnails.of(pBlock).size(1024, 1024).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else if (pSize < 5) { Thumbnails.of(pBlock).size(1440, 1440).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else { Thumbnails.of(pBlock).size(1680, 1680).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } } catch (IOException e) { // TODO 自动生成的 catch 块 // 压缩失败时,尝试以源文件进行预览 try { Files.copy(pBlock.toPath(), response.getOutputStream()); } catch (IOException e1) { // TODO 自动生成的 catch 块 } } } } } } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; }
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } for (String pName : paths) { try { Folder target = flm.queryByParentId(folderId).parallelStream() .filter((e) -> e.getFolderName().equals(pName)).findAny().get(); if (ConfigureReader.instance().accessFolder(target, account)) { folderId = target.getFolderId();// 向下迭代直至将父路径全部迭代完毕并找到最终路径 } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } catch (NoSuchElementException e) { Folder newFolder = fu.createNewFolder(flm.queryById(folderId), account, pName, folderConstraint); if (newFolder != null) { folderId = newFolder.getFolderId(); } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } } String fileName = getFileNameFormPath(originalFileName); // 检查是否存在同名文件。存在则直接失败(确保上传的文件夹内容的原始性) final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(fileName))) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return UPLOADERROR; } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean removeAddedAuthByFolderId(List<String> fIds) { if (fIds == null || fIds.size() == 0) { return false; } Set<String> configs = accountp.stringPropertieNames(); List<String> invalidConfigs = new ArrayList<>(); for (String fId : fIds) { for (String config : configs) { if (config.endsWith(".auth." + fId)) { invalidConfigs.add(config); } } } for (String config : invalidConfigs) { accountp.removeProperty(config); } try (FileOutputStream accountSettingOut = new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE)) { FileLock lock = accountSettingOut.getChannel().lock(); accountp.store(accountSettingOut, null); lock.release(); return true; } catch (Exception e) { Printer.instance.print("错误:更新账户配置文件时出现错误,请立即检查账户配置文件。"); return false; } }
#vulnerable code public boolean removeAddedAuthByFolderId(List<String> fIds) { if(fIds == null || fIds.size() == 0) { return false; } Set<String> configs=accountp.stringPropertieNames(); List<String> invalidConfigs = new ArrayList<>(); for(String fId:fIds) { for (String config:configs) { if(config.endsWith(".auth."+fId)) { invalidConfigs.add(config); } } } for(String config:invalidConfigs) { accountp.removeProperty(config); } try { accountp.store(new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE), null); return true; } catch (Exception e) { Printer.instance.print("错误:更新账户配置文件时出现错误,请立即检查账户配置文件。"); return false; } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); cifr.setResult("repeatFolder"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } }
#vulnerable code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { Folder testfolder = folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 if (ConfigureReader.instance().accessFolder(testfolder, account)) { cifr.setResult("coverOrBoth"); return gson.toJson(cifr); } } // 如果上述条件不满足,则只能允许保留两者 cifr.setResult("onlyBoth"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。 boolean isUpload = false; for (Cookie c : request.getCookies()) { if (KIFTD_UPLOAD_KEY.equals(c.getName())) { synchronized (keyList) { if (keyList.contains(c.getValue())) {// 比对钥匙有效性 isUpload = true; keyList.remove(c.getValue());// 销毁这把钥匙 c.setMaxAge(0); response.addCookie(c); } else { return UPLOADERROR; } } } } if (!isUpload) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(request, f); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(request, f2); return UPLOADSUCCESS; } return UPLOADERROR; }
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。 boolean isUpload = false; if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { for (Cookie c : request.getCookies()) { if (KIFTD_UPLOAD_KEY.equals(c.getName())) { synchronized (keyList) { if (keyList.contains(c.getValue())) {//比对钥匙有效性 isUpload = true; keyList.remove(c.getValue());//销毁这把钥匙 c.setMaxAge(0); response.addCookie(c); } else { return UPLOADERROR; } } } } } if (!isUpload) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(request, f); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(request, f2); return UPLOADSUCCESS; } return UPLOADERROR; } #location 51 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean deleteFromFileBlocks(Node f) { // 获取对应的文件块对象 File file = getFileFromBlocks(f); if (file != null) { return file.delete();// 执行删除操作 } return false; }
#vulnerable code public boolean deleteFromFileBlocks(Node f) { // 先判断一下文件块所在的存储区 File rootPath = new File(ConfigureReader.instance().getFileBlockPath()); if (!f.getFilePath().startsWith("file_")) {// 存放于主文件系统中 short index = Short.parseShort(f.getFilePath().substring(0, f.getFilePath().indexOf('_'))); rootPath = ConfigureReader.instance().getExtendStores().parallelStream() .filter((e) -> e.getIndex() == index).findAny().get().getPath(); } // 获取对应的文件块对象 File file = getFileFromBlocks(f); if (file != null) { if (file.delete()) { File parentPath = file.getParentFile(); while (parentPath != null && parentPath.isDirectory() && (!parentPath.equals(rootPath)) && parentPath.list().length == 0) { File thisPath = parentPath; parentPath = thisPath.getParentFile(); thisPath.delete(); } return true; } } return false; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; }
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } for (String pName : paths) { try { Folder target = flm.queryByParentId(folderId).parallelStream() .filter((e) -> e.getFolderName().equals(pName)).findAny().get(); if (ConfigureReader.instance().accessFolder(target, account)) { folderId = target.getFolderId();// 向下迭代直至将父路径全部迭代完毕并找到最终路径 } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } catch (NoSuchElementException e) { Folder newFolder = fu.createNewFolder(flm.queryById(folderId), account, pName, folderConstraint); if (newFolder != null) { folderId = newFolder.getFolderId(); } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } } String fileName = getFileNameFormPath(originalFileName); // 检查是否存在同名文件。存在则直接失败(确保上传的文件夹内容的原始性) final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(fileName))) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return UPLOADERROR; } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); cifr.setResult("repeatFolder"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } }
#vulnerable code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { Folder testfolder = folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 if (ConfigureReader.instance().accessFolder(testfolder, account)) { cifr.setResult("coverOrBoth"); return gson.toJson(cifr); } } // 如果上述条件不满足,则只能允许保留两者 cifr.setResult("onlyBoth"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 检查上传凭证,如果有则允许上传,否则丢弃该资源。该凭证用完后立即销毁。 String uploadKey = request.getParameter("uploadKey"); if (uploadKey != null) { synchronized (keyEffecMap) { UploadKeyCertificate c = keyEffecMap.get(uploadKey); if (c != null && c.isEffective()) {// 比对凭证有效性 c.checked();// 使用一次 account = c.getAccount(); if (!c.isEffective()) { keyEffecMap.remove(uploadKey);// 用完后销毁这个凭证 } } else { return UPLOADERROR; } } } else { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(f, account); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } return UPLOADERROR; }
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 检查上传凭证,如果有则允许上传,否则丢弃该资源。该凭证用完后立即销毁。 String uploadKey = request.getParameter("uploadKey"); if (uploadKey != null) { synchronized (keyEffecMap) { UploadKeyCertificate c = keyEffecMap.get(uploadKey); if (c != null && c.isEffective()) {// 比对凭证有效性 c.checked();// 使用一次 account = c.getAccount(); if (!c.isEffective()) { keyEffecMap.remove(uploadKey);// 用完后销毁这个凭证 } } else { return UPLOADERROR; } } } else { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(f, account); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } return UPLOADERROR; } #location 43 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void getLRContextByUTF8(String fileId, HttpServletRequest request, HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); // 权限检查 if (fileId != null) { Node n = nm.queryById(fileId); if (n != null) { if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES, fu.getAllFoldersId(n.getFileParentFolder())) && ConfigureReader.instance().accessFolder(fm.queryById(n.getFileParentFolder()), account)) { File file = fbu.getFileFromBlocks(n); if (file != null && file.isFile()) { // 后缀检查 String suffix = ""; if (n.getFileName().indexOf(".") >= 0) { suffix = n.getFileName().substring(n.getFileName().lastIndexOf(".")).trim().toLowerCase(); } if (".lrc".equals(suffix)) { String contentType = "text/plain"; response.setContentType(contentType); response.setCharacterEncoding("UTF-8"); String lastModified = file.lastModified() + ""; response.setHeader("ETag", lastModified); response.setHeader("Last-Modified", lastModified); // 执行转换并写出输出流 try { String inputFileEncode = tcg.getTxtCharset(new FileInputStream(file)); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(file), inputFileEncode)); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(response.getOutputStream(), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line); bufferedWriter.newLine(); } bufferedWriter.close(); bufferedReader.close(); return; } catch (IOException e) { } catch (Exception e) { Printer.instance.print(e.getMessage()); lu.writeException(e); } } } } } } try { response.sendError(500); } catch (Exception e1) { } }
#vulnerable code @Override public void getLRContextByUTF8(String fileId, HttpServletRequest request, HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); // 权限检查 if (fileId != null) { Node n = nm.queryById(fileId); if (n != null) { if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES, fu.getAllFoldersId(n.getFileParentFolder())) && ConfigureReader.instance().accessFolder(fm.queryById(n.getFileParentFolder()), account)) { File file = fbu.getFileFromBlocks(n); if (file != null && file.isFile()) { // 后缀检查 String suffix = ""; if (n.getFileName().indexOf(".") >= 0) { suffix = n.getFileName().substring(n.getFileName().lastIndexOf(".")).trim().toLowerCase(); } if (".lrc".equals(suffix)) { String contentType = "text/plain"; response.setContentType(contentType); // 执行转换并写出输出流 try { String inputFileEncode = tcg.getTxtCharset(new FileInputStream(file)); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(file), inputFileEncode)); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(response.getOutputStream(), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line); bufferedWriter.newLine(); } bufferedWriter.close(); bufferedReader.close(); return; } catch (IOException e) { } catch (Exception e) { Printer.instance.print(e.getMessage()); lu.writeException(e); } } } } } } try { response.sendError(500); } catch (Exception e1) { } } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String checkLoginRequest(final HttpServletRequest request, final HttpSession session) { final String encrypted = request.getParameter("encrypted"); try { final String loginInfoStr = DecryptionUtil.dncryption(encrypted, ku.getPrivateKey()); final LoginInfoPojo info = gson.fromJson(loginInfoStr, LoginInfoPojo.class); if (System.currentTimeMillis() - Long.parseLong(info.getTime()) > TIME_OUT) { return "error"; } final String accountId = info.getAccountId(); if (!ConfigureReader.instance().foundAccount(accountId)) { return "accountnotfound"; } // 如果验证码开启且该账户已被关注,则要求提供验证码 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { if (focusAccount.contains(accountId)) { String reqVerCode = request.getParameter("vercode"); String trueVerCode = (String) session.getAttribute("VERCODE"); session.removeAttribute("VERCODE");// 确保一个验证码只会生效一次,无论对错 if (reqVerCode == null || trueVerCode == null || !trueVerCode.equals(reqVerCode.toLowerCase())) { return "needsubmitvercode"; } } } } if (ConfigureReader.instance().checkAccountPwd(accountId, info.getAccountPwd())) { session.setAttribute("ACCOUNT", (Object) accountId); // 如果该账户输入正确且是一个被关注的账户,则解除该账户的关注,释放空间 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { focusAccount.remove(accountId); } } return "permitlogin"; } // 如果账户密码不匹配,则将该账户加入到关注账户集合,避免对方进一步破解 synchronized (focusAccount) { if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { focusAccount.add(accountId); } } return "accountpwderror"; } catch (Exception e) { return "error"; } }
#vulnerable code public String checkLoginRequest(final HttpServletRequest request, final HttpSession session) { final String encrypted = request.getParameter("encrypted"); final String loginInfoStr = DecryptionUtil.dncryption(encrypted, ku.getPrivateKey()); try { final LoginInfoPojo info = gson.fromJson(loginInfoStr, LoginInfoPojo.class); if (System.currentTimeMillis() - Long.parseLong(info.getTime()) > TIME_OUT) { return "error"; } final String accountId = info.getAccountId(); if (!ConfigureReader.instance().foundAccount(accountId)) { return "accountnotfound"; } // 如果验证码开启且该账户已被关注,则要求提供验证码 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { if (focusAccount.contains(accountId)) { String reqVerCode = request.getParameter("vercode"); String trueVerCode = (String) session.getAttribute("VERCODE"); session.removeAttribute("VERCODE");// 确保一个验证码只会生效一次,无论对错 if (reqVerCode == null || trueVerCode == null || !trueVerCode.equals(reqVerCode.toLowerCase())) { return "needsubmitvercode"; } } } } if (ConfigureReader.instance().checkAccountPwd(accountId, info.getAccountPwd())) { session.setAttribute("ACCOUNT", (Object) accountId); // 如果该账户输入正确且是一个被关注的账户,则解除该账户的关注,释放空间 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { focusAccount.remove(accountId); } } return "permitlogin"; } // 如果账户密码不匹配,则将该账户加入到关注账户集合,避免对方进一步破解 synchronized (focusAccount) { if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { focusAccount.add(accountId); } } return "accountpwderror"; } catch (Exception e) { return "error"; } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void deleteFolder(String folderId) throws SQLException { Folder f = selectFolderById(folderId); List<Node> nodes = selectNodesByFolderId(folderId); int size = nodes.size(); if(f==null) { return; } // 删除该文件夹内的所有文件 for (int i = 0; i < size && gono; i++) { deleteFile(nodes.get(i).getFileId()); } List<Folder> folders = getFoldersByParentId(folderId); size = folders.size(); // 迭代删除该文件夹内的所有文件夹 for (int i = 0; i < size && gono; i++) { deleteFolder(folders.get(i).getFolderId()); } per = 50; message = "正在删除文件夹:" + f.getFolderName(); // 删除自己的数据 if (deleteFolderById(folderId) > 0) { per = 100; return; } throw new SQLException(); }
#vulnerable code private void deleteFolder(String folderId) throws SQLException { Folder f = selectFolderById(folderId); List<Node> nodes = selectNodesByFolderId(folderId); int size = nodes.size(); // 删除该文件夹内的所有文件 for (int i = 0; i < size && gono; i++) { deleteFile(nodes.get(i).getFileId()); } List<Folder> folders = getFoldersByParentId(folderId); size = folders.size(); // 迭代删除该文件夹内的所有文件夹 for (int i = 0; i < size && gono; i++) { deleteFolder(folders.get(i).getFolderId()); } per = 50; message = "正在删除文件夹:" + f.getFolderName(); // 删除自己的数据 if (deleteFolderById(folderId) > 0) { per = 100; return; } throw new SQLException(); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.