instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { urlDbClient.reload(null); urlDbClient.getIndex().optimize(null); targetClient.reload(null); targetClient.getIndex().optimize(null); } urlDbClient.reload(null); targetClient.reload(null); }
#vulnerable code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { client.reload(null); client.getIndex().optimize(null); } client.reload(null); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String ct = conn.getContentType(); Charset cs = Charset.forName("Cp1252"); if (ct != null) { Matcher m = PAT_CHARSET.matcher(ct); if(m.find()) { final String charset = m.group(1); try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); }
#vulnerable code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String charset = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (charset != null) { try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getText(final URL url) throws BoilerpipeProcessingException { try { return getText(HTMLFetcher.fetch(url).toInputSource()); } catch (IOException e) { throw new BoilerpipeProcessingException(e); } }
#vulnerable code public String getText(final URL url) throws BoilerpipeProcessingException { try { final URLConnection conn = url.openConnection(); final String encoding = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (encoding != null) { try { cs = Charset.forName(encoding); } catch (UnsupportedCharsetException e) { // keep default } } final InputStream in = conn.getInputStream(); InputSource is = new InputSource(in); if(cs != null) { is.setEncoding(cs.name()); } final String text = getText(is); in.close(); return text; } catch (IOException e) { throw new BoilerpipeProcessingException(e); } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); if(admin==null) return; UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); }
#vulnerable code private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
#vulnerable code public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { e.printStackTrace(); username = null; } return username; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onHttpFinish(QQHttpResponse response) { try { LOG.debug(response.getContentType()); String type = response.getContentType(); if(type!=null && (type.startsWith("application/x-javascript") || type.startsWith("application/json") || type.indexOf("text") >= 0 ) && response.getContentLength() > 0){ LOG.debug(response.getResponseString()); } if(response.getResponseCode() == QQHttpResponse.S_OK){ onHttpStatusOK(response); }else{ onHttpStatusError(response); } } catch (QQException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, e); } catch (JSONException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.JSON_ERROR, e)); } catch (Throwable e){ notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.UNKNOWN_ERROR, e)); } }
#vulnerable code @Override public void onHttpFinish(QQHttpResponse response) { try { LOG.debug(response.getContentType()); String type = response.getContentType(); if((type.startsWith("application/x-javascript") || type.startsWith("application/json") || type.indexOf("text") >= 0 ) && response.getContentLength() > 0){ LOG.debug(response.getResponseString()); } if(response.getResponseCode() == QQHttpResponse.S_OK){ onHttpStatusOK(response); }else{ onHttpStatusError(response); } } catch (QQException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, e); } catch (JSONException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.JSON_ERROR, e)); } catch (Throwable e){ notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.UNKNOWN_ERROR, e)); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(); // List<SelectElem> selectElems = r.selectElemsWithAggregateSource(); List<SelectElem> selectElems = ((AggregatedRelation) r).getAggList(); // another wrapper to combine all subsampled aggregations. List<SelectElem> finalAgg = new ArrayList<SelectElem>(); for (int i = 0; i < selectElems.size() - 1; i++) { // excluding the last one which is psize // odd columns are for mean estimation // even columns are for err estimation if (i%2 == 1) continue; SelectElem meanElem = selectElems.get(i); SelectElem errElem = selectElems.get(i+1); ColNameExpr est = new ColNameExpr(meanElem.getAlias(), r.getAliasName()); ColNameExpr errEst = new ColNameExpr(errElem.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); Expr originalAggExpr = elems.get(i/2).getExpr(); // average estimate Expr meanEstExpr = null; if (originalAggExpr.isCountDistinct()) { meanEstExpr = FuncExpr.round(FuncExpr.avg(est)); } else { meanEstExpr = BinaryOpExpr.from(FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), FuncExpr.sum(psize), "/"); if (originalAggExpr.isCount()) { meanEstExpr = FuncExpr.round(meanEstExpr); } } finalAgg.add(new SelectElem(meanEstExpr, meanElem.getAlias())); // error estimation Expr errEstExpr = BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(errEst), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); finalAgg.add(new SelectElem(errEstExpr, errElem.getAlias())); } /* * Example input query: * select category, avg(col) * from t * group by category * * Transformed query: * select category, sum(est * psize) / sum(psize) AS final_est * from ( * select category, avg(col) AS est, count(*) as psize * from t * group by category, verdict_partition) AS vt1 * group by category * * where t1 was obtained by rewriteWithPartition(). */ if (source instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) source).getGroupby(); List<ColNameExpr> groupbyInNewSource = new ArrayList<ColNameExpr>(); for (ColNameExpr g : groupby) { groupbyInNewSource.add(new ColNameExpr(g.getCol(), r.getAliasName())); } r = new GroupedRelation(vc, r, groupbyInNewSource); } r = new AggregatedRelation(vc, r, finalAgg); r.setAliasName(getAliasName()); return r; }
#vulnerable code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(); // List<SelectElem> selectElems = r.selectElemsWithAggregateSource(); List<SelectElem> selectElems = ((AggregatedRelation) r).getAggList(); // another wrapper to combine all subsampled aggregations. List<SelectElem> finalAgg = new ArrayList<SelectElem>(); for (int i = 0; i < selectElems.size() - 1; i++) { // excluding the last one which is psize SelectElem e = selectElems.get(i); ColNameExpr est = new ColNameExpr(e.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); // average estimate // Expr meanEst = BinaryOpExpr.from( // FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), // FuncExpr.sum(psize), "/"); Expr meanEst = FuncExpr.avg(est); Expr originalAggExpr = elems.get(i).getExpr(); if (originalAggExpr instanceof FuncExpr) { if (((FuncExpr) originalAggExpr).getFuncName().equals(FuncExpr.FuncName.COUNT) || ((FuncExpr) originalAggExpr).getFuncName().equals(FuncExpr.FuncName.COUNT_DISTINCT)) { meanEst = FuncExpr.round(meanEst); } } finalAgg.add(new SelectElem(meanEst, e.getAlias())); // error estimation finalAgg.add(new SelectElem( BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"), e.getAlias() + errColSuffix())); } /* * Example input query: * select category, avg(col) * from t * group by category * * Transformed query: * select category, sum(est * psize) / sum(psize) AS final_est * from ( * select category, avg(col) AS est, count(*) as psize * from t * group by category, verdict_partition) AS vt1 * group by category * * where t1 was obtained by rewriteWithPartition(). */ if (source instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) source).getGroupby(); List<ColNameExpr> groupbyInNewSource = new ArrayList<ColNameExpr>(); for (ColNameExpr g : groupby) { groupbyInNewSource.add(new ColNameExpr(g.getCol(), r.getAliasName())); } r = new GroupedRelation(vc, r, groupbyInNewSource); } r = new AggregatedRelation(vc, r, finalAgg); r.setAliasName(getAliasName()); return r; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } columnsCache.addAll(connection.getColumns(schema, table)); return columnsCache; }
#vulnerable code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getColumnsCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { String type = jdbcQueryResult.getString(syntax.getColumnTypeColumnIndex()); // remove the size of type type = type.replaceAll("\\(.*\\)", ""); columnsCache.add(new ImmutablePair<>(jdbcQueryResult.getString(syntax.getColumnNameColumnIndex()), DataTypeConverter.typeInt(type))); } return columnsCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void addParent(QueryExecutionNode parent) { parents.add(parent); }
#vulnerable code void print(int indentSpace) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < indentSpace; i++) { builder.append(" "); } builder.append(this.toString()); System.out.println(builder.toString()); for (QueryExecutionNode dep : dependents) { dep.print(indentSpace + 2); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } tablesCache.addAll(connection.getTables(schema)); return tablesCache; }
#vulnerable code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getTableCommand(schema)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { tablesCache.add(jdbcQueryResult.getString(syntax.getTableNameColumnIndex())); } return tablesCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<String> getPartitionColumns(String schema, String table) throws VerdictDBDbmsException { List<String> partition = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getPartitionCommand(schema, table)); while (queryResult.next()) { partition.add((String) queryResult.getValue(0)); } return partition; }
#vulnerable code @Override public List<String> getPartitionColumns(String schema, String table) throws VerdictDBDbmsException { List<String> partition = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getPartitionCommand(schema, table)); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); // the result of postgresql is a vector of column index try { if (syntax instanceof PostgresqlSyntax) { queryResult.next(); Object o = jdbcResultSet.getObject(1); String[] arr = o.toString().split(" "); List<Pair<String, String>> columns = getColumns(schema, table); for (int i=0; i<arr.length; i++) { partition.add(columns.get(Integer.valueOf(arr[i])-1).getKey()); } } else { while (queryResult.next()) { partition.add(jdbcResultSet.getString(1)); } } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } jdbcResultSet.close(); return partition; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<String> getTables(String schema) throws VerdictDBDbmsException { List<String> tables = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getTableCommand(schema)); while (queryResult.next()) { tables.add((String) queryResult.getValue(syntax.getTableNameColumnIndex())); } return tables; }
#vulnerable code @Override public List<String> getTables(String schema) throws VerdictDBDbmsException { List<String> tables = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getTableCommand(schema)); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); try { while (queryResult.next()) { tables.add(jdbcResultSet.getString(syntax.getTableNameColumnIndex()+1)); } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } return tables; } #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 testExecuteNode() throws VerdictDBException { BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery query = SelectQuery.create(Arrays.<SelectItem>asList(new AsteriskColumn()), base); QueryExecutionNode root = CreateTableAsSelectExecutionNode.create(query, "newschema"); // ExecutionInfoToken token = new ExecutionInfoToken(); ExecutionInfoToken newTableName = root.executeNode(conn, Arrays.<ExecutionInfoToken>asList()); // no information to pass String schemaName = (String) newTableName.getValue("schemaName"); String tableName = (String) newTableName.getValue("tableName"); conn.executeUpdate(String.format("DROP TABLE \"%s\".\"%s\"", schemaName, tableName)); }
#vulnerable code @Test public void testExecuteNode() throws VerdictDBException { BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery query = SelectQuery.create(Arrays.<SelectItem>asList(new AsteriskColumn()), base); QueryExecutionNode root = CreateTableAsSelectExecutionNode.create(query, "newschema"); // LinkedBlockingDeque<ExecutionResult> resultQueue = new LinkedBlockingDeque<>(); root.executeNode(conn, null); // no information to pass conn.executeUpdate(String.format("DROP TABLE \"%s\".\"%s\"", newSchema, "verdictdbtemptable_0")); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected Map<TableUniqueName, String> tableSubstitution() { return source.tableSubstitution(); }
#vulnerable code @Override protected Map<TableUniqueName, String> tableSubstitution() { return ImmutableMap.of(); } #location 2 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } schemaCache.addAll(connection.getSchemas()); return schemaCache; }
#vulnerable code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getSchemaCommand()); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { schemaCache.add(jdbcQueryResult.getString(syntax.getSchemaNameColumnIndex())); } return schemaCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSingleAggCombiningWithH2() throws VerdictDBDbmsException, VerdictDBException { QueryExecutionPlan plan = new QueryExecutionPlan("newschema"); BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery leftQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); leftQuery.addFilterByAnd(ColumnOp.lessequal(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); SelectQuery rightQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); rightQuery.addFilterByAnd(ColumnOp.greater(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); AggExecutionNode leftNode = AggExecutionNode.create(plan, leftQuery); AggExecutionNode rightNode = AggExecutionNode.create(plan, rightQuery); // ExecutionTokenQueue queue = new ExecutionTokenQueue(); AggCombinerExecutionNode combiner = AggCombinerExecutionNode.create(plan, leftNode, rightNode); combiner.print(); ExecutionTokenReader reader = ExecutablePlanRunner.getTokenReader( conn, new SimpleTreePlan(combiner)); // combiner.addBroadcastingQueue(queue); // combiner.executeAndWaitForTermination(conn); ExecutionInfoToken token = reader.next(); String schemaName = (String) token.getValue("schemaName"); String tableName = (String) token.getValue("tableName"); DbmsQueryResult result = conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(ColumnOp.count(), base))); result.next(); int expectedCount = Integer.valueOf(result.getValue(0).toString()); DbmsQueryResult result2 = conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(new AsteriskColumn(), new BaseTable(schemaName, tableName, "t")))); result2.next(); int actualCount = Integer.valueOf(result2.getValue(0).toString()); assertEquals(expectedCount, actualCount); conn.execute(QueryToSql.convert( new H2Syntax(), DropTableQuery.create(schemaName, tableName))); }
#vulnerable code @Test public void testSingleAggCombiningWithH2() throws VerdictDBDbmsException, VerdictDBException { QueryExecutionPlan plan = new QueryExecutionPlan("newschema"); BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery leftQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); leftQuery.addFilterByAnd(ColumnOp.lessequal(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); SelectQuery rightQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); rightQuery.addFilterByAnd(ColumnOp.greater(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); AggExecutionNode leftNode = AggExecutionNode.create(plan, leftQuery); AggExecutionNode rightNode = AggExecutionNode.create(plan, rightQuery); // ExecutionTokenQueue queue = new ExecutionTokenQueue(); AggCombinerExecutionNode combiner = AggCombinerExecutionNode.create(plan, leftNode, rightNode); combiner.print(); ExecutionTokenReader reader = ExecutablePlanRunner.getTokenReader( conn, new SimpleTreePlan(combiner)); // combiner.addBroadcastingQueue(queue); // combiner.executeAndWaitForTermination(conn); ExecutionInfoToken token = reader.next(); String schemaName = (String) token.getValue("schemaName"); String tableName = (String) token.getValue("tableName"); conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(ColumnOp.count(), base))); DbmsQueryResult result = conn.getResult(); result.next(); int expectedCount = Integer.valueOf(result.getValue(0).toString()); conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(new AsteriskColumn(), new BaseTable(schemaName, tableName, "t")))); DbmsQueryResult result2 = conn.getResult(); result2.next(); int actualCount = Integer.valueOf(result2.getValue(0).toString()); assertEquals(expectedCount, actualCount); conn.execute(QueryToSql.convert( new H2Syntax(), DropTableQuery.create(schemaName, tableName))); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String visitSelect_list_elem(VerdictSQLParser.Select_list_elemContext ctx) { select_list_elem_num++; String newSelectListElem = null; Pair<String, Alias> colName2Alias = null; if (ctx.getText().equals("*")) { // TODO: replace * with all columns in the (joined) source table. newSelectListElem = "*"; } else { StringBuilder elem = new StringBuilder(); // We use a baseRewriter to prevent that "COUNT(*)" is rewritten to "COUNT(*) * (1/sample_ratio)" SelectStatementBaseRewriter baseRewriter = new SelectStatementBaseRewriter(queryString); String tabColName = baseRewriter.visit(ctx.expression()); String tabName = NameHelpers.tabNameOfColName(tabColName); TableUniqueName tabUniqueName = NameHelpers.tabUniqueNameOfColName(vc, tabColName); String colName = NameHelpers.colNameOfColName(tabColName); // if a table name is specified, we change it to its alias name. if (tableAliases.containsKey(tabUniqueName)) { tabName = tableAliases.get(tabUniqueName).toString(); } // if there was derived table(s), we may need to substitute aliased name for the colName. for (Map.Entry<String, Map<String, Alias>> e : derivedTableColName2Aliases.entrySet()) { String derivedTabName = e.getKey(); if (tabName.length() > 0 && !tabName.equals(derivedTabName)) { // this is the case where there are more than one derived tables, and a user specifically referencing // a column in one of those derived tables. continue; } if (e.getValue().containsKey(colName)) { Alias alias = e.getValue().get(colName); if (alias.autoGenerated()) { colName = alias.toString(); } } } if (tabName.length() > 0) { elem.append(String.format("%s.%s", tabName, colName)); } else { elem.append(colName); } if (ctx.column_alias() != null) { Alias alias = new Alias(colName, ctx.column_alias().getText()); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(colName, alias); } else { // We add a pseudo column alias Alias alias = Alias.genAlias(depth, colName); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(baseRewriter.visit(ctx.expression()), alias); } newSelectListElem = elem.toString(); } colName2Aliases.add(Pair.of(colName2Alias.getKey(), colName2Alias.getValue())); return newSelectListElem; }
#vulnerable code @Override public String visitSelect_list_elem(VerdictSQLParser.Select_list_elemContext ctx) { select_list_elem_num++; String newSelectListElem = null; Pair<String, Alias> colName2Alias = null; if (ctx.getText().equals("*")) { // TODO: replace * with all columns in the (joined) source table. newSelectListElem = "*"; } else { StringBuilder elem = new StringBuilder(); elem.append(visit(ctx.expression())); SelectStatementBaseRewriter baseRewriter = new SelectStatementBaseRewriter(queryString); String colName = baseRewriter.visit(ctx.expression()); if (ctx.column_alias() != null) { Alias alias = new Alias(colName, ctx.column_alias().getText()); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(colName, alias); } else { // We add a pseudo column alias Alias alias = Alias.genAlias(depth, colName); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(baseRewriter.visit(ctx.expression()), alias); } newSelectListElem = elem.toString(); } colName2Aliases.add(Pair.of(colName2Alias.getKey(), colName2Alias.getValue())); return newSelectListElem; } #location 31 #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[] a) throws Exception { PropertyConfigurator.configure(FoxCfg.LOG_FILE); String in = "University of Leipzig in Leipzig.."; String query = "select * from search.termextract where context="; URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("query.yahooapis.com").setPath("/v1/public/yql").setParameter("diagnostics", "false").setParameter("q", query + "'" + in + "'"); HttpGet httpget = new HttpGet(builder.build()); System.out.println(httpget.getURI()); HttpClient httpclient = HttpClientBuilder.create().build(); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { String myString = IOUtils.toString(instream, "UTF-8"); System.out.println(myString); } finally { instream.close(); } } }
#vulnerable code public static void main(String[] a) throws Exception { PropertyConfigurator.configure(FoxCfg.LOG_FILE); String in = "University of Leipzig in Leipzig.."; String query = "select * from search.termextract where context="; URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("query.yahooapis.com").setPath("/v1/public/yql").setParameter("diagnostics", "false").setParameter("q", query + "'" + in + "'"); HttpGet httpget = new HttpGet(builder.build()); System.out.println(httpget.getURI()); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { String myString = IOUtils.toString(instream, "UTF-8"); System.out.println(myString); } finally { instream.close(); } } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); MustacheFactory mf = new DefaultMustacheFactory(); URI uri = null; try { uri = new URI(templatePath); } catch (URISyntaxException e) { throw new GenerateException(e); } if (!uri.isAbsolute()) { File file = new File(templatePath); if (!file.exists()) { throw new GenerateException("Template " + file.getAbsoluteFile() + " not found. You can go to https://github.com/kongchen/api-doc-template to get templates."); } else { uri = new File(templatePath).toURI(); } } URL url = null; try { url = uri.toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = mf.compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } }
#vulnerable code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); try { URL url = getTemplateUri().toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = getMustacheFactory().compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } String description; List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping controllerRM = controller.getAnnotation(RequestMapping.class); String[] controllerProduces = new String[0]; String[] controllerConsumes = new String[0]; if (controllerRM != null) { controllerConsumes = controllerRM.consumes(); controllerProduces = controllerRM.produces(); } if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return swagger; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); description = api.description(); } resourcePath = resource.getControllerMapping(); //collect api from method with @RequestMapping Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods); for (String path : apiMethodMap.keySet()) { for (Method method : apiMethodMap.get(path)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping == null) { continue; } ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); if (apiOperation == null) { continue; } String httpMethod = null; Map<String, String> regexMap = new HashMap<String, String>(); String operationPath = parseOperationPath(path, regexMap); //http method if (requestMapping.method() != null && requestMapping.method().length != 0) { httpMethod = requestMapping.method()[0].toString().toLowerCase(); if (httpMethod == null) { continue; } } Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiProduces = requestMapping.produces(); String[] apiConsumes = requestMapping.consumes(); apiProduces = (apiProduces == null || apiProduces.length == 0 ) ? controllerProduces : apiProduces; apiConsumes = (apiConsumes == null || apiProduces.length == 0 ) ? controllerConsumes : apiConsumes; apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation); apiProduces = updateOperationProduces(new String[0], apiProduces, operation); ApiOperation op = method.getAnnotation(ApiOperation.class); updateTagsForOperation(operation, op); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } return swagger; }
#vulnerable code public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping apiPath = controller.getAnnotation(RequestMapping.class); if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return null; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); // description = api.description(); // position = api.position(); } resourcePath = resource.getControllerMapping(); Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); //collect api from method with @RequestMapping collectApisByRequestMapping(methods, apiMethodMap); for (String p : apiMethodMap.keySet()) { List<Operation> operations = new ArrayList<Operation>(); for (Method method : apiMethodMap.get(p)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); String operationPath = p; //getPath(apiPath, requestMapping, ""); String operationId; String httpMethod = null; if (operationPath != null && apiOperation != null) { Map<String, String> regexMap = new HashMap<String, String>(); operationPath = parseOperationPath(operationPath, regexMap); //http method if (requestMapping.method() != null && requestMapping.method().length != 0) { httpMethod = requestMapping.method()[0].toString().toLowerCase(); } Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiConsumes = new String[0]; String[] apiProduces = new String[0]; RequestMapping rm = controller.getAnnotation(RequestMapping.class); String[] pps = new String[0]; String[] pcs = new String[0]; if (rm != null) { pcs = rm.consumes(); pps = rm.produces(); } apiConsumes = updateOperationConsumes(method, pcs, apiConsumes, operation); apiProduces = updateOperationProduces(method, pps, apiProduces, operation); // can't continue without a valid http method // httpMethod = httpMethod == null ? parentMethod : httpMethod; ApiOperation op = method.getAnnotation(ApiOperation.class); updateTagsForOperation(operation, op); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } } return swagger; } #location 38 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Operation parseMethod(String httpMethod, Method method) { int responseCode = 200; Operation operation = new Operation(); ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); String operationId = getOperationId(method, httpMethod); String responseContainer = null; Type responseClassType = null; Map<String, Property> defaultResponseHeaders = null; if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); Map<String, Object> customExtensions = BaseReaderUtils.parseExtensions(apiOperation.extensions()); operation.setVendorExtensions(customExtensions); if (!apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { responseClassType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } } operation.operationId(operationId); if (responseClassType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseClassType = method.getGenericReturnType(); } boolean hasApiAnnotation = false; if (responseClassType instanceof Class) { hasApiAnnotation = AnnotationUtils.findAnnotation((Class) responseClassType, Api.class) != null; } if ((responseClassType != null) && !responseClassType.equals(Void.class) && !responseClassType.equals(void.class) && !responseClassType.equals(javax.ws.rs.core.Response.class) && !hasApiAnnotation && !isSubResource(httpMethod, method)) { if (isPrimitive(responseClassType)) { Property property = ModelConverters.getInstance().readAsProperty(responseClassType); if (property != null) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, property); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClassType.equals(Void.class) && !responseClassType.equals(void.class)) { Map<String, Model> models = ModelConverters.getInstance().read(responseClassType); if (models.isEmpty()) { Property p = ModelConverters.getInstance().readAsProperty(responseClassType); operation.response(responseCode, new Response() .description("successful operation") .schema(p) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, new RefProperty().asDefault(key)); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } } Map<String, Model> models = readAllModels(responseClassType); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : consumes.value()) { operation.consumes(mediaType); } } Produces produces = AnnotationUtils.findAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : produces.value()) { operation.produces(mediaType); } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } if (AnnotationUtils.findAnnotation(method, Deprecated.class) != null) { operation.deprecated(true); } // process parameters Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = findParamAnnotations(method); for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { if (hasCommonParameter(parameter)) { Parameter refParameter = new RefParameter(RefType.PARAMETER.getInternalPrefix() + parameter.getName()); operation.parameter(refParameter); } else { parameter = replaceArrayModelForOctetStream(operation, parameter); operation.parameter(parameter); } } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); processOperationDecorator(operation, method); return operation; }
#vulnerable code public Operation parseMethod(String httpMethod, Method method) { int responseCode = 200; Operation operation = new Operation(); ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); String operationId = getOperationId(method, httpMethod); String responseContainer = null; Type responseClassType = null; Map<String, Property> defaultResponseHeaders = null; if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); Map<String, Object> customExtensions = BaseReaderUtils.parseExtensions(apiOperation.extensions()); operation.setVendorExtensions(customExtensions); if (!apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { responseClassType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } } operation.operationId(operationId); if (responseClassType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseClassType = method.getGenericReturnType(); } boolean hasApiAnnotation = false; if (responseClassType instanceof Class) { hasApiAnnotation = AnnotationUtils.findAnnotation((Class) responseClassType, Api.class) != null; } if ((responseClassType != null) && !responseClassType.equals(Void.class) && !responseClassType.equals(void.class) && !responseClassType.equals(javax.ws.rs.core.Response.class) && !hasApiAnnotation && !isSubResource(httpMethod, method)) { if (isPrimitive(responseClassType)) { Property property = ModelConverters.getInstance().readAsProperty(responseClassType); if (property != null) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, property); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClassType.equals(Void.class) && !responseClassType.equals(void.class)) { Map<String, Model> models = readModels(responseClassType); if (models.isEmpty()) { Property p = ModelConverters.getInstance().readAsProperty(responseClassType); operation.response(responseCode, new Response() .description("successful operation") .schema(p) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, new RefProperty().asDefault(key)); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } } Map<String, Model> models = readAllModels(responseClassType); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : consumes.value()) { operation.consumes(mediaType); } } Produces produces = AnnotationUtils.findAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : produces.value()) { operation.produces(mediaType); } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } if (AnnotationUtils.findAnnotation(method, Deprecated.class) != null) { operation.deprecated(true); } // process parameters Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = findParamAnnotations(method); for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { if (hasCommonParameter(parameter)) { Parameter refParameter = new RefParameter(RefType.PARAMETER.getInternalPrefix() + parameter.getName()); operation.parameter(refParameter); } else { parameter = replaceArrayModelForOctetStream(operation, parameter); operation.parameter(parameter); } } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); processOperationDecorator(operation, method); return operation; } #location 80 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Operation parseMethod(Method method) { Operation operation = new Operation(); RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); Class<?> responseClass = null; List<String> produces = new ArrayList<String>(); List<String> consumes = new ArrayList<String>(); String responseContainer = null; String operationId = method.getName(); Map<String, Property> defaultResponseHeaders = null; Set<Map<String, Object>> customExtensions = null; ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); if (apiOperation.hidden()) return null; if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname(); defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); customExtensions = parseCustomExtensions(apiOperation.extensions()); if (customExtensions != null) { for (Map<String, Object> extension : customExtensions) { if (extension != null) { for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension(map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } } } if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) responseClass = apiOperation.response(); if (!"".equals(apiOperation.responseContainer())) responseContainer = apiOperation.responseContainer(); ///security if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) operation.security(sec); } } if (responseClass == null) { // pick out response from method declaration LOG.info("picking up response class from method " + method); Type t = method.getGenericReturnType(); responseClass = method.getReturnType(); if (responseClass.equals(ResponseEntity.class)) { responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); } if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && AnnotationUtils.findAnnotation(responseClass, Api.class) == null) { LOG.info("reading model " + responseClass); Map<String, Model> models = ModelConverters.getInstance().readAll(t); } } if (responseClass != null && !responseClass.equals(Void.class) && !responseClass.equals(ResponseEntity.class) && AnnotationUtils.findAnnotation(responseClass, Api.class) == null) { if (isPrimitive(responseClass)) { Property responseProperty = null; Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(property); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(property); else responseProperty = property; operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.size() == 0) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(pp) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = null; if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(new RefProperty().asDefault(key)); else responseProperty = new RefProperty().asDefault(key); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (String key : models.keySet()) { swagger.model(key, models.get(key)); } } } operation.operationId(operationId); if (requestMapping.produces() != null) { for (String str : Arrays.asList(requestMapping.produces())) { if (!produces.contains(str)) { produces.add(str); } } } if (requestMapping.consumes() != null) { for (String str : Arrays.asList(requestMapping.consumes())) { if (!consumes.contains(str)) { consumes.add(str); } } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } else { ResponseStatus responseStatus = AnnotationUtils.findAnnotation(method, ResponseStatus.class); if (responseStatus != null) { operation.response(responseStatus.value().value(), new Response().description(responseStatus.reason())); } } Deprecated annotation = AnnotationUtils.findAnnotation(method, Deprecated.class); if (annotation != null) operation.deprecated(true); // FIXME `hidden` is never used boolean hidden = false; if (apiOperation != null) hidden = apiOperation.hidden(); // process parameters Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); // paramTypes = method.getParameterTypes // genericParamTypes = method.getGenericParameterTypes for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); return operation; }
#vulnerable code private Operation parseMethod(Method method) { Operation operation = new Operation(); RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); Class<?> responseClass = null; List<String> produces = new ArrayList<String>(); List<String> consumes = new ArrayList<String>(); String responseContainer = null; String operationId = method.getName(); Map<String, Property> defaultResponseHeaders = null; Set<Map<String, Object>> customExtensions = null; ApiOperation apiOperation = Annotations.get(method, ApiOperation.class); if (apiOperation.hidden()) return null; if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname(); defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); customExtensions = parseCustomExtensions(apiOperation.extensions()); if (customExtensions != null) { for (Map<String, Object> extension : customExtensions) { if (extension != null) { for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension(map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } } } if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) responseClass = apiOperation.response(); if (!"".equals(apiOperation.responseContainer())) responseContainer = apiOperation.responseContainer(); ///security if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) operation.security(sec); } } if (responseClass == null) { // pick out response from method declaration LOG.info("picking up response class from method " + method); Type t = method.getGenericReturnType(); responseClass = method.getReturnType(); if (responseClass.equals(ResponseEntity.class)) { responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); } if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && Annotations.get(responseClass, Api.class) == null) { LOG.info("reading model " + responseClass); Map<String, Model> models = ModelConverters.getInstance().readAll(t); } } if (responseClass != null && !responseClass.equals(Void.class) && !responseClass.equals(ResponseEntity.class) && Annotations.get(responseClass, Api.class) == null) { if (isPrimitive(responseClass)) { Property responseProperty = null; Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(property); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(property); else responseProperty = property; operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.size() == 0) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(pp) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = null; if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(new RefProperty().asDefault(key)); else responseProperty = new RefProperty().asDefault(key); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (String key : models.keySet()) { swagger.model(key, models.get(key)); } } } operation.operationId(operationId); if (requestMapping.produces() != null) { for (String str : Arrays.asList(requestMapping.produces())) { if (!produces.contains(str)) { produces.add(str); } } } if (requestMapping.consumes() != null) { for (String str : Arrays.asList(requestMapping.consumes())) { if (!consumes.contains(str)) { consumes.add(str); } } } ApiResponses responseAnnotation = Annotations.get(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } else { ResponseStatus responseStatus = Annotations.get(method, ResponseStatus.class); if (responseStatus != null) { operation.response(responseStatus.value().value(), new Response().description(responseStatus.reason())); } } Deprecated annotation = Annotations.get(method, Deprecated.class); if (annotation != null) operation.deprecated(true); // FIXME `hidden` is never used boolean hidden = false; if (apiOperation != null) hidden = apiOperation.hidden(); // process parameters Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); // paramTypes = method.getParameterTypes // genericParamTypes = method.getGenericParameterTypes for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); return operation; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); try { URL url = getTemplateUri().toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = getMustacheFactory().compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } }
#vulnerable code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); MustacheFactory mf = new DefaultMustacheFactory(); URI uri = null; try { uri = new URI(templatePath); } catch (URISyntaxException e) { throw new GenerateException(e); } if (!uri.isAbsolute()) { File file = new File(templatePath); if (!file.exists()) { throw new GenerateException("Template " + file.getAbsoluteFile() + " not found. You can go to https://github.com/kongchen/api-doc-template to get templates."); } else { uri = new File(templatePath).toURI(); } } URL url = null; try { url = uri.toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = mf.compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 39 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet("'Can't connect to MySQL server on 'localhost'"); try { Process p; if (Platform.detect() == Platform.Windows) { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin.exe").toString(); successPatterns.add("mysqld.exe: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); } else { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); successPatterns.add("mysqld: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), //String.format("--socket=%s", sockFile(getExecutable().executable)), "shutdown"}); } retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(unsafeRuntimeConfig.getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseable(stdOut); closeCloseable(stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 59 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean stopUsingMysqldadmin() { ResultMatchingListener shutdownListener = outputWatch.addListener(new ResultMatchingListener(": Shutdown complete")); boolean retValue = false; Reader stdErr = null; try { String cmd = Paths.get(getExecutable().getFile().baseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[]{ cmd, "--no-defaults", "--protocol=tcp", format("-u%s", MysqldConfig.SystemDefaults.USERNAME), format("--port=%s", getConfig().getPort()), "shutdown"}); retValue = p.waitFor() == 0; stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { shutdownListener.waitForResult(getConfig().getTimeout()); if (!shutdownListener.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + shutdownListener.getFailureFound()); retValue = false; } else { retValue = true; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + errOutput); } } } catch (InterruptedException | IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdErr); } return retValue; }
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().baseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", format("-u%s", MysqldConfig.SystemDefaults.USERNAME), format("--port=%s", getConfig().getPort()), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor(successPatterns, "[ERROR]", StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().getBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } } catch (InterruptedException | IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 51 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet("'Can't connect to MySQL server on 'localhost'"); try { Process p; if (Platform.detect() == Platform.Windows) { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin.exe").toString(); successPatterns.add("mysqld.exe: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); } else { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); successPatterns.add("mysqld: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), //String.format("--socket=%s", sockFile(getExecutable().executable)), "shutdown"}); } retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(unsafeRuntimeConfig.getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseable(stdOut); closeCloseable(stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 60 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected SettableBeanProperty _resolvedObjectIdProperty(DeserializationContext ctxt, SettableBeanProperty prop) throws JsonMappingException { ObjectIdInfo objectIdInfo = prop.getObjectIdInfo(); JsonDeserializer<Object> valueDeser = prop.getValueDeserializer(); ObjectIdReader objectIdReader = (valueDeser == null) ? null : valueDeser.getObjectIdReader(); if (objectIdInfo == null && objectIdReader == null) { return prop; } return new ObjectIdReferenceProperty(prop, objectIdInfo); }
#vulnerable code protected SettableBeanProperty _resolvedObjectIdProperty(DeserializationContext ctxt, SettableBeanProperty prop) throws JsonMappingException { ObjectIdInfo objectIdInfo = prop.getObjectIdInfo(); JsonDeserializer<Object> valueDeser = prop.getValueDeserializer(); ObjectIdReader objectIdReader = valueDeser.getObjectIdReader(); if (objectIdInfo == null && objectIdReader == null) { return prop; } return new ObjectIdReferenceProperty(prop, objectIdInfo); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testDeepPrefixedUnwrappingDeserialize() throws Exception { DeepPrefixUnwrap bean = MAPPER.readValue("{\"u.name\":\"Bubba\",\"u._x\":2,\"u._y\":3}", DeepPrefixUnwrap.class); assertNotNull(bean.unwrapped); assertNotNull(bean.unwrapped.location); assertEquals(2, bean.unwrapped.location.x); assertEquals(3, bean.unwrapped.location.y); assertEquals("Bubba", bean.unwrapped.name); }
#vulnerable code public void testDeepPrefixedUnwrappingDeserialize() throws Exception { DeepPrefixUnwrap bean = mapper.readValue("{\"u.name\":\"Bubba\",\"u._x\":2,\"u._y\":3}", DeepPrefixUnwrap.class); assertNotNull(bean.unwrapped); assertNotNull(bean.unwrapped.location); assertEquals(2, bean.unwrapped.location.x); assertEquals(3, bean.unwrapped.location.y); assertEquals("Bubba", bean.unwrapped.name); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public <T> MappingIterator<T> readValues(File src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), false); } return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src))); }
#vulnerable code public <T> MappingIterator<T> readValues(File src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), false); } return _bindAndReadValues(considerFilter(_parserFactory.createParser(src))); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testRootBeans() throws Exception { final String JSON = aposToQuotes("{'a':3} {'x':5}"); MappingIterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(JSON); // First one should be fine assertTrue(it.hasNextValue()); Bean bean = it.nextValue(); assertEquals(3, bean.a); // but second one not try { bean = it.nextValue(); fail("Should not have succeeded"); } catch (JsonMappingException e) { verifyException(e, "Unrecognized field \"x\""); } // 21-May-2015, tatu: With [databind#734], recovery, we now know there's no more data! assertFalse(it.hasNextValue()); it.close(); }
#vulnerable code public void testRootBeans() throws Exception { final String JSON = aposToQuotes("{'a':3} {'b':5}"); MappingIterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(JSON); // First one should be fine assertTrue(it.hasNextValue()); Bean bean = it.nextValue(); assertEquals(3, bean.a); // but second one not try { bean = it.nextValue(); fail("Should not have succeeded"); } catch (JsonMappingException e) { verifyException(e, "Unrecognized field"); } // 24-Mar-2015, tatu: With 2.5, best we can do is to avoid infinite loop; // also, since the next token is END_OBJECT, will produce empty Object assertTrue(it.hasNextValue()); bean = it.nextValue(); assertEquals(0, bean.a); // and we should be done now assertFalse(it.hasNextValue()); it.close(); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testAtomicLong() throws Exception { AtomicLong value = MAPPER.readValue("12345678901", AtomicLong.class); assertEquals(12345678901L, value.get()); }
#vulnerable code public void testAtomicLong() throws Exception { ObjectMapper mapper = new ObjectMapper(); AtomicLong value = mapper.readValue("12345678901", AtomicLong.class); assertEquals(12345678901L, value.get()); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void withTree749() throws Exception { ObjectMapper mapper = new ObjectMapper().registerModule(new TestEnumModule()); Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>(); Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>(); Map<String, String> reps = new LinkedHashMap<String, String>(); reps.put("1", "one"); replacements.put(TestEnum.GREEN, reps); inputMap.put(KeyEnum.replacements, replacements); JsonNode tree = mapper.valueToTree(inputMap); ObjectNode ob = (ObjectNode) tree; JsonNode inner = ob.get("replacements"); String firstFieldName = inner.fieldNames().next(); assertEquals("green", firstFieldName); }
#vulnerable code public void withTree749() throws Exception { Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>(); Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>(); Map<String, String> reps = new LinkedHashMap<String, String>(); reps.put("1", "one"); replacements.put(TestEnum.GREEN, reps); inputMap.put(KeyEnum.replacements, replacements); ObjectMapper mapper = TestEnumModule.setupObjectMapper(new ObjectMapper()); JsonNode tree = mapper.valueToTree(inputMap); ObjectNode ob = (ObjectNode) tree; JsonNode inner = ob.get("replacements"); String firstFieldName = inner.fieldNames().next(); assertEquals("green", firstFieldName); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); try { is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, "UTF-8"))); } catch (UnsupportedEncodingException e) { IOUtils.closeQuietly(bomIs); throw new RuntimeException("Impossible exception", e); } return processXml(sitemapUrl, is); }
#vulnerable code private AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs))); return processXml(sitemapUrl, is); } #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 testVideosSitemap() throws UnknownFormatException, IOException { SiteMapParser parser = new SiteMapParser(); parser.enableExtension(Extension.VIDEO); String contentType = "text/xml"; byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml"); URL url = new URL("http://www.example.com/sitemap-video.xml"); AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url); assertEquals(false, asm.isIndex()); assertEquals(true, asm instanceof SiteMap); SiteMap sm = (SiteMap) asm; assertEquals(2, sm.getSiteMapUrls().size()); Iterator<SiteMapURL> siter = sm.getSiteMapUrls().iterator(); // first <loc> element: nearly all video attributes VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123")); expectedVideoAttributes.setDuration(600); ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00"); expectedVideoAttributes.setExpirationDate(dt); dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00"); expectedVideoAttributes.setPublicationDate(dt); expectedVideoAttributes.setRating(4.2f); expectedVideoAttributes.setViewCount(12345); expectedVideoAttributes.setFamilyFriendly(true); expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" }); expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" }); expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com")); expectedVideoAttributes.setGalleryTitle("Cooking Videos"); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) }); expectedVideoAttributes.setRequiresSubscription(true); expectedVideoAttributes.setUploader("GrillyMcGrillerson"); expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson")); expectedVideoAttributes.setLive(false); VideoAttributes attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0]; assertNotNull(attr); assertEquals(expectedVideoAttributes, attr); // locale-specific number format in <video:price>, test #220 expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123-2.jpg"), "Grilling steaks for summer, episode 2", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123-2.flv"), null); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", null, VideoAttributes.VideoPriceType.own) }); attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0]; assertNotNull(attr); assertEquals(expectedVideoAttributes, attr); }
#vulnerable code @Test public void testVideosSitemap() throws UnknownFormatException, IOException { SiteMapParser parser = new SiteMapParser(); parser.enableExtension(Extension.VIDEO); String contentType = "text/xml"; byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml"); URL url = new URL("http://www.example.com/sitemap-video.xml"); AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url); assertEquals(false, asm.isIndex()); assertEquals(true, asm instanceof SiteMap); SiteMap sm = (SiteMap) asm; assertEquals(1, sm.getSiteMapUrls().size()); VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123")); expectedVideoAttributes.setDuration(600); ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00"); expectedVideoAttributes.setExpirationDate(dt); dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00"); expectedVideoAttributes.setPublicationDate(dt); expectedVideoAttributes.setRating(4.2f); expectedVideoAttributes.setViewCount(12345); expectedVideoAttributes.setFamilyFriendly(true); expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" }); expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" }); expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com")); expectedVideoAttributes.setGalleryTitle("Cooking Videos"); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) }); expectedVideoAttributes.setRequiresSubscription(true); expectedVideoAttributes.setUploader("GrillyMcGrillerson"); expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson")); expectedVideoAttributes.setLive(false); for (SiteMapURL su : sm.getSiteMapUrls()) { assertNotNull(su.getAttributesForExtension(Extension.VIDEO)); VideoAttributes attr = (VideoAttributes) su.getAttributesForExtension(Extension.VIDEO)[0]; assertEquals(expectedVideoAttributes, attr); } } #location 37 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, UTF_8))); return processXml(sitemapUrl, is); }
#vulnerable code protected AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); try { is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, "UTF-8"))); } catch (UnsupportedEncodingException e) { IOUtils.closeQuietly(bomIs); throw new RuntimeException("Impossible exception", e); } return processXml(sitemapUrl, is); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean validate(UserPersonalInfo info) { validator.validate(info); if(validator.hasErrors()){ return false; } if (info.getUser() == null) { validator.add(new ValidationMessage("user.errors.wrong", "error")); } if (!info.getUser().getEmail().equals(info.getEmail())){ emailValidator.validate(info.getEmail()); } if (info.getBirthDate() != null && info.getBirthDate().getYear() > DateTime.now().getYear()-12){ validator.add(new ValidationMessage("user.errors.invalid_birth_date.min_age", "error")); } if(!info.getUser().getName().equals(info.getName())){ DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt(); if(nameLastTouchedAt.isAfter(new DateTime().minusDays(30))){ validator.add(new ValidationMessage("user.errors.name.min_time", "error", nameLastTouchedAt.plusDays(30).toString())); } } return !validator.hasErrors(); }
#vulnerable code public boolean validate(UserPersonalInfo info) { validator.validate(info); if(validator.hasErrors()){ return false; } if (info.getUser() == null) { validator.add(new ValidationMessage("user.errors.wrong", "error")); } if(!info.getUser().getEmail().equals(info.getEmail())){ emailValidator.validate(info.getEmail()); } if(info.getBirthDate().getYear() > DateTime.now().getYear()-12){ validator.add(new ValidationMessage("user.errors.invalid_birth_date.min_age", "error")); } if(!info.getUser().getName().equals(info.getName())){ DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt(); if(nameLastTouchedAt.isAfter(new DateTime().minusDays(30))){ validator.add(new ValidationMessage("user.errors.name.min_time", "error", nameLastTouchedAt.plusDays(30).toString())); } } return !validator.hasErrors(); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void moderator_should_approve_question_information() throws Exception { Information approvedInfo = new QuestionInformation("edited title", "edited desc", new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment"); moderator.approve(myQuestion, approvedInfo); assertEquals(approvedInfo, myQuestion.getInformation()); assertTrue(myQuestion.getInformation().isModerated()); }
#vulnerable code @Test public void moderator_should_approve_question_information() throws Exception { Question question = question("question title", "question description", author); Information approvedInfo = new QuestionInformation("edited title", "edited desc", new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment"); moderator.approve(question, approvedInfo); assertEquals(approvedInfo, question.getInformation()); assertTrue(question.getInformation().isModerated()); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public SyndFeedInfo remove(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(fileName); ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); final File file = new File(fileName); if (file.exists()) { file.delete(); } } catch (final FileNotFoundException fnfe) { // That's OK, we'l return null } catch (final ClassNotFoundException cnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", cnfe); } catch (final IOException fnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", fnfe); } finally { if (fis != null) { try { fis.close(); } catch (final IOException e) { } } if (ois != null) { try { ois.close(); } catch (final IOException e) { } } } return info; }
#vulnerable code @Override public SyndFeedInfo remove(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis; try { fis = new FileInputStream(fileName); final ObjectInputStream ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); fis.close(); final File file = new File(fileName); if (file.exists()) { file.delete(); } } catch (final FileNotFoundException fnfe) { // That's OK, we'l return null } catch (final ClassNotFoundException cnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", cnfe); } catch (final IOException fnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", fnfe); } return info; } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testEncodingAttributeXML() throws Exception { final InputStream is = new ByteArrayInputStream(ENCODING_ATTRIBUTE_XML.getBytes()); final XmlReader xmlReader = new XmlReader(is, "", true); assertEquals(xmlReader.getEncoding(), "UTF-8"); xmlReader.close(); }
#vulnerable code public void testEncodingAttributeXML() throws Exception { final InputStream is = new ByteArrayInputStream(ENCODING_ATTRIBUTE_XML.getBytes()); final XmlReader xmlReader = new XmlReader(is, "", true); assertEquals(xmlReader.getEncoding(), "UTF-8"); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void testRawNoBomInvalid(final String encoding) throws Exception { InputStream is = null; XmlReader xmlReader = null; try { is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is, false); fail("It should have failed"); } catch (final IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } finally { if (xmlReader != null) { xmlReader.close(); } if (is != null) { is.close(); } } }
#vulnerable code protected void testRawNoBomInvalid(final String encoding) throws Exception { final InputStream is = getXmlStream("no-bom", XML3, encoding, encoding); try { final XmlReader xmlReader = new XmlReader(is, false); fail("It should have failed"); } catch (final IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void testHttpLenient(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String shouldbe) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML2, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, true); assertEquals(xmlReader.getEncoding(), shouldbe); xmlReader.close(); }
#vulnerable code protected void testHttpLenient(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String shouldbe) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML2, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, true); assertEquals(xmlReader.getEncoding(), shouldbe); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testParse() { final Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); // four-digit year String sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // four-digit year sDate = "Tue, 19 Jul 2005 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // RFC822 sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); // RFC822 sDate = "Tue, 19 Jul 05 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.set(2000, Calendar.JANUARY, 01, 0, 0, 0); final Date expectedDate = c.getTime(); // W3C sDate = "2000-01-01T00:00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01-01T00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // EXTRA sDate = "18:10 2000/10/10"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); // INVALID sDate = "X20:10 2000-10-10"; assertNull(DateParser.parseDate(sDate, Locale.US)); }
#vulnerable code public void testParse() { final Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); // four-digit year String sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // four-digit year sDate = "Tue, 19 Jul 2005 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // RFC822 sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate)); // RFC822 sDate = "Tue, 19 Jul 05 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate)); final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.set(2000, Calendar.JANUARY, 01, 0, 0, 0); final Date expectedDate = c.getTime(); // W3C sDate = "2000-01-01T00:00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01-01T00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // EXTRA sDate = "18:10 2000/10/10"; assertNotNull(DateParser.parseDate(sDate)); // INVALID sDate = "X20:10 2000-10-10"; assertNull(DateParser.parseDate(sDate)); } #location 67 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code HtmlTreeBuilder() {}
#vulnerable code Element pop() { // todo - dev, remove validation check if (stack.peekLast().nodeName().equals("td") && !state.name().equals("InCell")) Validate.isFalse(true, "pop td not in cell"); if (stack.peekLast().nodeName().equals("html")) Validate.isFalse(true, "popping html!"); return stack.pollLast(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static String readInputStream(InputStream inStream, String charsetName) throws IOException { byte[] buffer = new byte[bufferSize]; ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize); int read; while(true) { read = inStream.read(buffer); if (read == -1) break; outStream.write(buffer, 0, read); } ByteBuffer byteData = ByteBuffer.wrap(outStream.toByteArray()); String docData; if (charsetName == null) { // determine from http-equiv. safe parse as UTF-8 docData = Charset.forName(defaultCharset).decode(byteData).toString(); Document doc = Jsoup.parse(docData); Element httpEquiv = doc.select("meta[http-equiv]").first(); if (httpEquiv != null) { // if not found, will keep utf-8 as best attempt String foundCharset = getCharsetFromContentType(httpEquiv.attr("content")); if (foundCharset != null && !foundCharset.equals(defaultCharset)) { // need to re-decode byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); } } } else { // specified by content type header (or by user on file load) docData = Charset.forName(charsetName).decode(byteData).toString(); } return docData; }
#vulnerable code private static String readInputStream(InputStream inStream, String charsetName) throws IOException { char[] buffer = new char[0x20000]; // ~ 130K StringBuilder data = new StringBuilder(0x20000); Reader inReader = new InputStreamReader(inStream, charsetName); int read; do { read = inReader.read(buffer, 0, buffer.length); if (read > 0) { data.append(buffer, 0, read); } } while (read >= 0); return data.toString(); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static String load(File in, String charsetName) throws IOException { InputStream inStream = new FileInputStream(in); String data = readInputStream(inStream, charsetName); inStream.close(); return data; }
#vulnerable code static String load(File in, String charsetName) throws IOException { char[] buffer = new char[0x20000]; // ~ 130K StringBuilder data = new StringBuilder(0x20000); InputStream inStream = new FileInputStream(in); Reader inReader = new InputStreamReader(inStream, charsetName); int read; do { read = inReader.read(buffer, 0, buffer.length); if (read > 0) { data.append(buffer, 0, read); } } while (read >= 0); return data.toString(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(select("html").first()); normalise(this); return this; }
#vulnerable code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); normalise(this); normalise(select("html").first()); normalise(head()); return this; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Document parse() { // TODO: figure out implicit head & body elements Document doc = new Document(); stack.add(doc); StringBuilder commentAccum = null; while (tokenStream.hasNext()) { Token token = tokenStream.next(); if (token.isFullComment()) { // <!-- comment --> Comment comment = new Comment(stack.peek(), token.getCommentData()); stack.getLast().addChild(comment); } else if (token.isStartComment()) { // <!-- comment commentAccum = new StringBuilder(token.getCommentData()); } else if (token.isEndComment() && commentAccum != null) { // comment --> commentAccum.append(token.getCommentData()); Comment comment = new Comment(stack.peek(), commentAccum.toString()); stack.getLast().addChild(comment); commentAccum = null; } else if (commentAccum != null) { // within a comment commentAccum.append(token.getData()); } else if (token.isStartTag()) { Attributes attributes = attributeParser.parse(token.getAttributeString()); Tag tag = Tag.valueOf(token.getTagName()); StartTag startTag = new StartTag(tag, attributes); // if tag is "html", we already have it, so OK to ignore skip. todo: abstract this. and can there be attributes to set? if (doc.getTag().equals(tag)) continue; Element parent = popStackToSuitableContainer(tag); Validate.notNull(parent, "Should always have a viable container"); Element node = new Element(parent, startTag); parent.addChild(node); stack.add(node); } if (token.isEndTag() && commentAccum == null) { // empty tags are both start and end tags stack.removeLast(); } // TODO[must] handle comments else if (token.isTextNode()) { String text = token.getData(); TextNode textNode = new TextNode(stack.peek(), text); stack.getLast().addChild(textNode); } } return doc; }
#vulnerable code public Document parse() { // TODO: figure out implicit head & body elements Document doc = new Document(); stack.add(doc); while (tokenStream.hasNext()) { Token token = tokenStream.next(); if (token.isStartTag()) { Attributes attributes = attributeParser.parse(token.getAttributeString()); Tag tag = Tag.valueOf(token.getTagName()); StartTag startTag = new StartTag(tag, attributes); // if tag is "html", we already have it, so OK to ignore skip. todo: abstract this. and can there be attributes to set? if (doc.getTag().equals(tag)) continue; Element parent = popStackToSuitableContainer(tag); Validate.notNull(parent, "Should always have a viable container"); Element node = new Element(parent, startTag); parent.addChild(node); stack.add(node); } if (token.isEndTag()) { // empty tags are both start and end tags stack.removeLast(); } // TODO[must] handle comments else if (token.isTextNode()) { String text = token.getData(); TextNode textNode = new TextNode(stack.peek(), text); stack.getLast().addChild(textNode); } } return doc; } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code ParseSettings defaultSettings() { return ParseSettings.htmlDefault; }
#vulnerable code void insert(Token.Character characterToken) { Node node; // characters in script and style go in as datanodes, not text nodes final String tagName = currentElement().tagName(); final String data = characterToken.getData(); if (characterToken.isCData()) node = new CDataNode(data); else if (tagName.equals("script") || tagName.equals("style")) node = new DataNode(data); else node = new TextNode(data); currentElement().appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack. } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void forms() { Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"); Elements els = doc.select("*"); assertEquals(9, els.size()); List<FormElement> forms = els.forms(); assertEquals(2, forms.size()); assertNotNull(forms.get(0)); assertNotNull(forms.get(1)); assertEquals("1", forms.get(0).id()); assertEquals("2", forms.get(1).id()); }
#vulnerable code @Test public void forms() { Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"); Elements els = doc.select("*"); assertEquals(9, els.size()); List<FormElement> forms = els.forms(); assertEquals(2, forms.size()); assertTrue(forms.get(0) != null); assertTrue(forms.get(1) != null); assertEquals("1", forms.get(0).id()); assertEquals("2", forms.get(1).id()); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Node nextSibling() { if (parentNode == null) return null; // root List<Node> siblings = parentNode.childNodes; Integer index = siblingIndex(); Validate.notNull(index); if (siblings.size() > index+1) return siblings.get(index+1); else return null; }
#vulnerable code public Node nextSibling() { if (parentNode == null) return null; // root List<Node> siblings = parentNode.childNodes; Integer index = indexInList(this, siblings); Validate.notNull(index); if (siblings.size() > index+1) return siblings.get(index+1); else return null; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAppendTo() { String parentHtml = "<div class='a'></div>"; String childHtml = "<div class='b'></div><p>Two</p>"; Document parentDoc = Jsoup.parse(parentHtml); Element parent = parentDoc.body(); Document childDoc = Jsoup.parse(childHtml); Element div = childDoc.select("div").first(); Element p = childDoc.select("p").first(); Element appendTo1 = div.appendTo(parent); assertEquals(div, appendTo1); Element appendTo2 = p.appendTo(div); assertEquals(p, appendTo2); assertEquals("<div class=\"a\"></div>\n<div class=\"b\">\n <p>Two</p>\n</div>", parentDoc.body().html()); assertEquals("", childDoc.body().html()); // got moved out }
#vulnerable code @Test public void testAppendTo() { String parentHtml = "<div class='a'></div>"; String childHtml = "<div class='b'></div>"; Element parentElement = Jsoup.parse(parentHtml).getElementsByClass("a").first(); Element childElement = Jsoup.parse(childHtml).getElementsByClass("b").first(); childElement.attr("class", "test-class").appendTo(parentElement).attr("id", "testId"); assertEquals("test-class", childElement.attr("class")); assertEquals("testId", childElement.attr("id")); assertThat(parentElement.attr("id"), not(equalTo("testId"))); assertThat(parentElement.attr("class"), not(equalTo("test-class"))); assertSame(childElement, parentElement.children().first()); assertSame(parentElement, childElement.parent()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code boolean preserveWhitespace() { return tag.preserveWhitespace() || parent() != null && parent().preserveWhitespace(); }
#vulnerable code void outerHtmlHead(StringBuilder accum, int depth) { if (isBlock() || (parent() != null && parent().tag().canContainBlock() && siblingIndex() == 0)) indent(accum, depth); accum .append("<") .append(tagName()) .append(attributes.html()); if (childNodes.isEmpty() && tag.isEmpty()) accum.append(" />"); else accum.append(">"); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void outerHtml(StringBuilder accum) { new NodeTraversor(new OuterHtmlVisitor(accum, getOutputSettings())).traverse(this); }
#vulnerable code protected void outerHtml(StringBuilder accum) { new NodeTraversor(new OuterHtmlVisitor(accum, ownerDocument().outputSettings())).traverse(this); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<ul id='ul'>" + "<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>" + "</ul>" + "<div id='div'>" + "<li id='d'>d</li>" + "</div>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); assertEquals("b", elementSiblings.get(0).id()); assertEquals("c", elementSiblings.get(1).id()); Element element1 = doc.getElementById("b"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNotNull(elementSiblings1); assertEquals(1, elementSiblings1.size()); assertEquals("c", elementSiblings1.get(0).id()); Element element2 = doc.getElementById("c"); List<Element> elementSiblings2 = element2.nextElementSiblings(); assertEquals(0, elementSiblings2.size()); Element ul = doc.getElementById("ul"); List<Element> elementSiblings3 = ul.nextElementSiblings(); assertNotNull(elementSiblings3); assertEquals(1, elementSiblings3.size()); assertEquals("div", elementSiblings3.get(0).id()); Element div = doc.getElementById("div"); List<Element> elementSiblings4 = div.nextElementSiblings(); try { Element elementSibling = elementSiblings4.get(0); fail("This element should has no next siblings"); } catch (IndexOutOfBoundsException e) { } }
#vulnerable code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); Element element1 = doc.getElementById("c"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNull(elementSiblings1); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Document normalise() { Element htmlEl = findFirstElementByTagName("html", this); if (htmlEl == null) htmlEl = appendElement("html"); if (head() == null) htmlEl.prependElement("head"); if (body() == null) htmlEl.appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(htmlEl); normalise(this); return this; }
#vulnerable code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(select("html").first()); normalise(this); return this; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void removeChild(Node out) { Validate.isTrue(out.parentNode == this); int index = out.siblingIndex(); childNodes.remove(index); reindexChildren(); out.parentNode = null; }
#vulnerable code protected void removeChild(Node out) { Validate.isTrue(out.parentNode == this); int index = indexInList(out, childNodes); childNodes.remove(index); out.parentNode = null; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<ul id='ul'>" + "<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>" + "</ul>" + "<div id='div'>" + "<li id='d'>d</li>" + "</div>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); assertEquals("b", elementSiblings.get(0).id()); assertEquals("c", elementSiblings.get(1).id()); Element element1 = doc.getElementById("b"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNotNull(elementSiblings1); assertEquals(1, elementSiblings1.size()); assertEquals("c", elementSiblings1.get(0).id()); Element element2 = doc.getElementById("c"); List<Element> elementSiblings2 = element2.nextElementSiblings(); assertEquals(0, elementSiblings2.size()); Element ul = doc.getElementById("ul"); List<Element> elementSiblings3 = ul.nextElementSiblings(); assertNotNull(elementSiblings3); assertEquals(1, elementSiblings3.size()); assertEquals("div", elementSiblings3.get(0).id()); Element div = doc.getElementById("div"); List<Element> elementSiblings4 = div.nextElementSiblings(); try { Element elementSibling = elementSiblings4.get(0); fail("This element should has no next siblings"); } catch (IndexOutOfBoundsException e) { } }
#vulnerable code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); Element element1 = doc.getElementById("c"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNull(elementSiblings1); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code ParseSettings defaultSettings() { return ParseSettings.htmlDefault; }
#vulnerable code void insert(Token.Character characterToken) { final Node node; final Element el = currentElement(); final String tagName = el.normalName(); final String data = characterToken.getData(); if (characterToken.isCData()) node = new CDataNode(data); else if (tagName.equals("script") || tagName.equals("style")) node = new DataNode(data); else node = new TextNode(data); el.appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack. } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Document load(File in, String charsetName, String baseUri) throws IOException { InputStream inStream = null; try { inStream = new FileInputStream(in); ByteBuffer byteData = readToByteBuffer(inStream); return parseByteData(byteData, charsetName, baseUri); } finally { if (inStream != null) inStream.close(); } }
#vulnerable code public static Document load(File in, String charsetName, String baseUri) throws IOException { InputStream inStream = new FileInputStream(in); ByteBuffer byteData = readToByteBuffer(inStream); Document doc = parseByteData(byteData, charsetName, baseUri); inStream.close(); return doc; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String consumeCssIdentifier() { int start = pos; while (!isEmpty() && (matchesWord() || matchesAny('-', '_'))) pos++; return queue.substring(start, pos); }
#vulnerable code public String consumeCssIdentifier() { StringBuilder accum = new StringBuilder(); Character c = peek(); while (!isEmpty() && (Character.isLetterOrDigit(c) || c.equals('-') || c.equals('_'))) { accum.append(consume()); c = peek(); } return accum.toString(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void addChildren(int index, Node... children) { Validate.notNull(children); if (children.length == 0) { return; } final List<Node> nodes = ensureChildNodes(); // fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace final Node firstParent = children[0].parent(); if (firstParent != null && firstParent.childNodeSize() == children.length) { boolean sameList = true; final List<Node> firstParentNodes = firstParent.childNodes(); // identity check contents to see if same int i = children.length; while (i-- > 0) { if (children[i] != firstParentNodes.get(i)) { sameList = false; break; } } firstParent.empty(); nodes.addAll(index, Arrays.asList(children)); i = children.length; while (i-- > 0) { children[i].parentNode = this; } reindexChildren(index); return; } Validate.noNullElements(children); for (Node child : children) { reparentChild(child); } nodes.addAll(index, Arrays.asList(children)); reindexChildren(index); }
#vulnerable code protected void addChildren(int index, Node... children) { Validate.noNullElements(children); final List<Node> nodes = ensureChildNodes(); for (Node child : children) { reparentChild(child); } nodes.addAll(index, Arrays.asList(children)); reindexChildren(index); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);? StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } // skip } else { String name = m.group(1); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { // out of range String c = Character.toString((char) charval); m.appendReplacement(accum, c); } else { m.appendReplacement(accum, m.group(0)); // replace with original string } } m.appendTail(accum); return accum.toString(); }
#vulnerable code static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);? StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } // skip } else { String name = m.group(1).toLowerCase(); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { // out of range String c = Character.toString((char) charval); m.appendReplacement(accum, c); } else { m.appendReplacement(accum, m.group(0)); // replace with original string } } m.appendTail(accum); return accum.toString(); } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); int i = 0; try { ByteBuffer bytes = DataUtil.readToByteBuffer(stream, 0); String contents = Charset.forName("ascii").decode(bytes).toString(); CharacterReader reader = new CharacterReader(contents); while (!reader.isEmpty()) { // NotNestedLessLess=10913,824;1887 final String name = reader.consumeTo('='); reader.advance(); final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix); final char codeDelim = reader.current(); reader.advance(); final int cp2; if (codeDelim == ',') { cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix); reader.advance(); } else { cp2 = empty; } final int index = Integer.parseInt(reader.consumeTo('\n'), codepointRadix); reader.advance(); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } } catch (IOException err) { throw new IllegalStateException("Error reading resource " + file); } }
#vulnerable code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String entry; int i = 0; try { while ((entry = reader.readLine()) != null) { // NotNestedLessLess=10913,824;1887 final Matcher match = entityPattern.matcher(entry); if (match.find()) { final String name = match.group(1); final int cp1 = Integer.parseInt(match.group(2), codepointRadix); final int cp2 = match.group(3) != null ? Integer.parseInt(match.group(3), codepointRadix) : empty; final int index = Integer.parseInt(match.group(4), codepointRadix); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } } reader.close(); } catch (IOException err) { throw new IllegalStateException("Error reading resource " + file); } } #location 36 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void parseStartTag() { tq.consume("<"); Attributes attributes = new Attributes(); String tagName = tq.consumeWord(); while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) { Attribute attribute = parseAttribute(); if (attribute != null) attributes.put(attribute); } Tag tag = Tag.valueOf(tagName); StartTag startTag = new StartTag(tag, attributes); Element child = new Element(startTag); boolean emptyTag; if (tq.matchChomp("/>")) { // empty tag, don't add to stack emptyTag = true; } else { tq.matchChomp(">"); // safe because checked above (or ran out of data) emptyTag = false; } // pc data only tags (textarea, script): chomp to end tag, add content as text node if (tag.isData()) { String data = tq.chompTo("</" + tagName); tq.chompTo(">"); TextNode textNode = TextNode.createFromEncoded(data); // TODO: maybe have this be another data type? So doesn't come back in text()? child.addChild(textNode); if (tag.equals(titleTag)) doc.setTitle(child.text()); } // switch between html, head, body, to preserve doc structure if (tag.equals(htmlTag)) { doc.getAttributes().mergeAttributes(attributes); } else if (tag.equals(headTag)) { doc.getHead().getAttributes().mergeAttributes(attributes); // head is on stack from start, no action required } else if (last().getTag().equals(headTag) && !headTag.canContain(tag)) { // switch to body stack.removeLast(); stack.addLast(doc.getBody()); last().addChild(child); if (!emptyTag) stack.addLast(child); } else if (tag.equals(bodyTag) && last().getTag().equals(htmlTag)) { doc.getBody().getAttributes().mergeAttributes(attributes); stack.removeLast(); stack.addLast(doc.getBody()); } else { Element parent = popStackToSuitableContainer(tag); parent.addChild(child); if (!emptyTag && !tag.isData()) // TODO: only check for data here because last() == head is wrong; should be ancestor is head stack.addLast(child); } }
#vulnerable code private void parseStartTag() { tq.consume("<"); Attributes attributes = new Attributes(); String tagName = tq.consumeWord(); while (!tq.matches("<") && !tq.matches("/>") && !tq.matches(">") && !tq.isEmpty()) { Attribute attribute = parseAttribute(); if (attribute != null) attributes.put(attribute); } Tag tag = Tag.valueOf(tagName); StartTag startTag = new StartTag(tag, attributes); Element child = new Element(startTag); boolean emptyTag; if (tq.matchChomp("/>")) { // empty tag, don't add to stack emptyTag = true; } else { tq.matchChomp(">"); // safe because checked above (or ran out of data) emptyTag = false; } // pc data only tags (textarea, script): chomp to end tag, add content as text node if (tag.isData()) { String data = tq.chompTo("</" + tagName); tq.chompTo(">"); TextNode textNode = TextNode.createFromEncoded(data); child.addChild(textNode); if (tag.equals(titleTag)) doc.setTitle(child.text()); } // switch between html, head, body, to preserve doc structure if (tag.equals(htmlTag)) { doc.getAttributes().mergeAttributes(attributes); } else if (tag.equals(headTag)) { doc.getHead().getAttributes().mergeAttributes(attributes); // head is on stack from start, no action required } else if (last().getTag().equals(headTag) && !headTag.canContain(tag)) { // switch to body stack.removeLast(); stack.addLast(doc.getBody()); last().addChild(child); if (!emptyTag) stack.addLast(child); } else if (tag.equals(bodyTag) && last().getTag().equals(htmlTag)) { doc.getBody().getAttributes().mergeAttributes(attributes); stack.removeLast(); stack.addLast(doc.getBody()); } else { Element parent = popStackToSuitableContainer(tag); parent.addChild(child); if (!emptyTag && !tag.isData()) // TODO: only check for data here because last() == head is wrong; should be ancestor is head stack.addLast(child); } } #location 54 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNamespaceInBackground() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); CuratorListener listener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.EXISTS ) { queue.put(event.getPath()); } } }; client.getCuratorListenable().addListener(listener); client.create().forPath("/base"); client.checkExists().inBackground().forPath("/base"); String path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); client.getCuratorListenable().removeListener(listener); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; client.getChildren().inBackground(callback).forPath("/base"); path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); } finally { client.close(); } }
#vulnerable code @Test public void testNamespaceInBackground() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); CuratorListener listener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.EXISTS ) { queue.put(event.getPath()); } } }; client.getCuratorListenable().addListener(listener); client.create().forPath("/base", new byte[0]); client.checkExists().inBackground().forPath("/base"); String path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); client.getCuratorListenable().removeListener(listener); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; client.getChildren().inBackground(callback).forPath("/base"); path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); } finally { client.close(); } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNamespaceWithWatcher() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { try { queue.put(event.getPath()); } catch ( InterruptedException e ) { throw new Error(e); } } }; client.create().forPath("/base"); client.getChildren().usingWatcher(watcher).forPath("/base"); client.create().forPath("/base/child"); String path = queue.take(); Assert.assertEquals(path, "/base"); } finally { client.close(); } }
#vulnerable code @Test public void testNamespaceWithWatcher() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { try { queue.put(event.getPath()); } catch ( InterruptedException e ) { throw new Error(e); } } }; client.create().forPath("/base", new byte[0]); client.getChildren().usingWatcher(watcher).forPath("/base"); client.create().forPath("/base/child", new byte[0]); String path = queue.take(); Assert.assertEquals(path, "/base"); } finally { client.close(); } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setObsoleteTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setTag(trytes.substring(2592, 2619)); this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000); this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911))); this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938))); this.setNonce(trytes.substring(2646, 2673)); }
#vulnerable code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setNonce(trytes.substring(2592, 2673)); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { // validate & if needed pad seed if ( (seed = InputValidator.validateSeed(seed)) == null) { throw new IllegalStateException("Invalid Seed"); } start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } StopWatch sw = new StopWatch(); sw.start(); System.out.println("GetTransfer started"); GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { System.out.println("GetTransfers after getNewAddresses " + sw.getTime() + " ms"); Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); System.out.println("GetTransfers after bundlesFromAddresses " + sw.getTime() + " ms"); sw.stop(); return GetTransferResponse.create(bundles); } sw.stop(); return null; }
#vulnerable code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); return GetTransferResponse.create(bundles); } return null; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setObsoleteTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setTag(trytes.substring(2592, 2619)); this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000); this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911))); this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938))); this.setNonce(trytes.substring(2646, 2673)); }
#vulnerable code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setNonce(trytes.substring(2592, 2673)); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { // validate & if needed pad seed if ( (seed = InputValidator.validateSeed(seed)) == null) { throw new IllegalStateException("Invalid Seed"); } start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } StopWatch sw = new StopWatch(); sw.start(); System.out.println("GetTransfer started"); GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { System.out.println("GetTransfers after getNewAddresses " + sw.getTime() + " ms"); Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); System.out.println("GetTransfers after bundlesFromAddresses " + sw.getTime() + " ms"); sw.stop(); return GetTransferResponse.create(bundles); } sw.stop(); return null; }
#vulnerable code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); return GetTransferResponse.create(bundles); } return null; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private synchronized boolean send(byte[] bytes) { // buffering if (pendings.position() + bytes.length > pendings.capacity()) { LOG.severe("Cannot send logs to " + server.toString()); return false; } pendings.put(bytes); try { // suppress reconnection burst if (!reconnector.enableReconnection(System.currentTimeMillis())) { return true; } // send pending data flush(); } catch (IOException e) { // close socket close(); } return true; }
#vulnerable code private synchronized boolean send(byte[] bytes) { // buffering if (pendings.position() + bytes.length > pendings.capacity()) { LOG.severe("Cannot send logs to " + server.toString()); return false; } pendings.put(bytes); try { // suppress reconnection burst if (!reconnector.enableReconnection(System.currentTimeMillis())) { return true; } // check whether connection is established or not reconnect(); // write data out.write(getBuffer()); out.flush(); clearBuffer(); } catch (IOException e) { // close socket close(); } return true; } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } props.remove(Config.FLUENT_SENDER_CLASS); }
#vulnerable code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { try { final Socket socket = serverSocket.accept(); Thread th = new Thread() { public void run() { try { process.process(msgpack, socket); } catch (IOException e) { // ignore } } }; th.start(); } catch (IOException e) { e.printStackTrace(); } }
#vulnerable code public void run() throws IOException { Socket socket = serverSock.accept(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // TODO } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } props.remove(Config.FLUENT_SENDER_CLASS); }
#vulnerable code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } } #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 testRenderMultipleObjects() { TestObject testObject = new TestObject(); // step 1: add one object. Result result = new Result(200); result.render(testObject); assertEquals(testObject, result.getRenderable()); // step 2: add a second object (string is just a dummy) // => we expect to get a map from the result now... String string = new String("test"); result.render(string); assertTrue(result.getRenderable() instanceof Map); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(string, resultMap.get("string")); assertEquals(testObject, resultMap.get("testObject")); // step 3: add same object => we expect an illegal argument exception as the map // cannot handle that case: TestObject anotherObject = new TestObject(); boolean gotException = false; try { result.render(anotherObject); } catch (IllegalArgumentException e) { gotException = true; } assertTrue(gotException); // step 4: add an entry Entry<String, Object> entry = new AbstractMap.SimpleImmutableEntry<String, Object>("anotherObject", anotherObject); result.render(entry); resultMap = (Map) result.getRenderable(); assertEquals(3, resultMap.size()); assertEquals(anotherObject, resultMap.get("anotherObject")); // step 5: add another map and check that conversion works: Map<String, Object> mapToRender = Maps.newHashMap(); String anotherString = new String("anotherString"); TestObject anotherTestObject = new TestObject(); mapToRender.put("anotherString", anotherString); mapToRender.put("anotherTestObject", anotherTestObject); result.render(mapToRender); resultMap = (Map) result.getRenderable(); assertEquals(2, resultMap.size()); assertEquals(anotherString, resultMap.get("anotherString")); assertEquals(anotherTestObject, resultMap.get("anotherTestObject")); }
#vulnerable code @Test public void testRenderMultipleObjects() { TestObject testObject = new TestObject(); // step 1: add one object. Result result = new Result(200); result.render(testObject); assertEquals(testObject, result.getRenderable()); // step 2: add a second object (string is just a dummy) // => we expect to get a map from the result now... String string = new String("test"); result.render(string); assertTrue(result.getRenderable() instanceof Map); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(string, resultMap.get("string")); assertEquals(testObject, resultMap.get("testObject")); // step 3: add same object => we expect an illegal argument exception as the map // cannot handle that case: TestObject anotherObject = new TestObject(); boolean gotException = false; try { result.render(anotherObject); } catch (IllegalArgumentException e) { gotException = true; } assertTrue(gotException); // step 4: add an entry Entry<String, Object> entry = new AbstractMap.SimpleImmutableEntry<String, Object>("anotherObject", anotherObject); result.render(entry); resultMap = (Map) result.getRenderable(); assertEquals(3, resultMap.size()); assertEquals(anotherObject, resultMap.get("anotherObject")); // step 5: add another map and check that conversion works: Map<String, Object> mapToRender = Maps.newHashMap(); String anotherString = new String("anotherString"); TestObject anotherTestObject = new TestObject(); mapToRender.put("anotherString", anotherString); mapToRender.put("anotherTestObject", anotherTestObject); result.render(mapToRender); resultMap = (Map) result.getRenderable(); assertEquals(5, resultMap.size()); assertEquals(anotherString, resultMap.get("anotherString")); assertEquals(anotherTestObject, resultMap.get("anotherTestObject")); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void parse() { Map<String,RouteParameter> params; RouteParameter param; // no named parameters is null params = RouteParameter.parse("/user"); assertThat(params, aMapWithSize(0)); params = RouteParameter.parse("/user/{id}/{email: [0-9]+}"); param = params.get("id"); assertThat(param.getName(), is("id")); assertThat(param.getToken(), is("{id}")); assertThat(param.getRegex(), is(nullValue())); param = params.get("email"); assertThat(param.getName(), is("email")); assertThat(param.getToken(), is("{email: [0-9]+}")); assertThat(param.getRegex(), is("[0-9]+")); }
#vulnerable code @Test public void parse() { Map<String,RouteParameter> params; RouteParameter param; // no named parameters is null params = RouteParameter.parse("/user"); assertThat(params, is(nullValue())); params = RouteParameter.parse("/user/{id}/{email: [0-9]+}"); param = params.get("id"); assertThat(param.getName(), is("id")); assertThat(param.getToken(), is("{id}")); assertThat(param.getRegex(), is(nullValue())); param = params.get("email"); assertThat(param.getName(), is("email")); assertThat(param.getToken(), is("{email: [0-9]+}")); assertThat(param.getRegex(), is("[0-9]+")); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static private SourceSnippet readFromInputStream(InputStream is, URI source, int lineFrom, int lineTo) throws IOException { // did the user provide a strange range (e.g. negative values)? // this sometimes may happen when a range is provided like an error // on line 3 and you want 5 before and 5 after if (lineFrom < 1 && lineTo > 0) { // calculate intended range int intendedRange = lineTo - lineFrom; lineFrom = 1; lineTo = lineFrom + intendedRange; } else if (lineFrom < 0 && lineTo < 0) { if (lineFrom < lineTo) { int intendedRange = -1 * (lineFrom - lineTo); lineFrom = 1; lineTo = lineFrom + intendedRange; } else { // giving up return null; } } BufferedReader in = new BufferedReader( new InputStreamReader(is)); List<String> lines = new ArrayList<>(); int i = 0; String line; while ((line = in.readLine()) != null) { i++; // lines index are 1-based if (i >= lineFrom) { if (i <= lineTo) { lines.add(line); } else { break; } } } if (lines.isEmpty()) { return null; } // since file may not contain enough lines for requested lineTo -- // we caclulate the actual range here by number read "from" line // since we are inclusive and not zero based we adjust the "from" by 1 return new SourceSnippet(source, lines, lineFrom, lineFrom + lines.size() - 1); }
#vulnerable code static private SourceSnippet readFromInputStream(InputStream is, URI source, int lineFrom, int lineTo) throws IOException { if (lineTo <= 0) { throw new IllegalArgumentException("lineTo was <= 0"); } // just zero this out if (lineFrom < 0) { lineFrom = 0; } if (lineTo < lineFrom) { throw new IllegalArgumentException("lineTo was < lineFrom"); } BufferedReader in = new BufferedReader( new InputStreamReader(is)); List<String> lines = new ArrayList<>(); int i = 0; String line; while ((line = in.readLine()) != null) { i++; // lines index are 1-based if (i >= lineFrom) { if (i <= lineTo) { lines.add(line); } else { break; } } } if (lines.isEmpty()) { return null; } // since file may not contain enough lines for requested lineTo -- // we caclulate the actual range here by number read "from" line. return new SourceSnippet(source, lines, lineFrom, lineFrom + lines.size()); } #location 42 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String makeRequest(String url, Map<String, String> headers) { StringBuffer sb = new StringBuffer(); BufferedReader br = null; try { HttpGet getRequest = new HttpGet(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { getRequest.addHeader(header.getKey(), header.getValue()); } } HttpResponse response; response = httpClient.execute(getRequest); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } getRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { LOG.error("Failed to close resource", e); } } } return sb.toString(); }
#vulnerable code public String makeRequest(String url, Map<String, String> headers) { StringBuffer sb = new StringBuffer(); try { HttpGet getRequest = new HttpGet(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { getRequest.addHeader(header.getKey(), header.getValue()); } } HttpResponse response; response = httpClient.execute(getRequest); BufferedReader br = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } getRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } return sb.toString(); } #location 29 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException { if (!ninjaProperties.isProd()) { // print out full stacktrace if we are in test or dev mode PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>" + "<b style='font-size:medium'>FreeMarker template error!</b>" + "<pre><xmp>"); te.printStackTrace(pw); pw.println("</xmp></pre></div></html>"); pw.flush(); pw.close(); logger.error("Templating error.", te); } // Let the exception bubble up to the central handlers // so the application can return the correct error page // or perform some other application specific action. throw te; }
#vulnerable code public void handleTemplateException(TemplateException te, Environment env, Writer out) { if (ninjaProperties.isProd()) { PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println( "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>"); pw.println("<b style='font-size:medium'>Ooops. A really strange error occurred. Please contact admin if error persists.</b>"); pw.println("</div></html>"); pw.flush(); pw.close(); logger.log(Level.SEVERE, "Templating error. This should not happen in production", te); } else { // print out full stacktrace if we are in test or dev mode PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>" + "<b style='font-size:medium'>FreeMarker template error!</b>" + "<pre><xmp>"); te.printStackTrace(pw); pw.println("</xmp></pre></div></html>"); pw.flush(); pw.close(); logger.log(Level.SEVERE, "Templating error.", te); } } #location 62 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String makePostRequestWithFormParameters(String url, Map<String, String> headers, Map<String, String> formParameters) { StringBuffer sb = new StringBuffer(); BufferedReader br = null; try { HttpPost postRequest = new HttpPost(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { postRequest.addHeader(header.getKey(), header.getValue()); } } // add form parameters: List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>(); if (formParameters != null) { for (Entry<String, String> parameter : formParameters .entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); postRequest.setEntity(entity); HttpResponse response; response = httpClient.execute(postRequest); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } postRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { LOG.error("Failed to close resource", e); } } } return sb.toString(); }
#vulnerable code public String makePostRequestWithFormParameters(String url, Map<String, String> headers, Map<String, String> formParameters) { StringBuffer sb = new StringBuffer(); try { HttpPost postRequest = new HttpPost(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { postRequest.addHeader(header.getKey(), header.getValue()); } } // add form parameters: List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>(); if (formParameters != null) { for (Entry<String, String> parameter : formParameters .entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); postRequest.setEntity(entity); HttpResponse response; response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } postRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } return sb.toString(); } #location 49 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRawRecordingSpeed() throws Exception { testRawRecordingSpeedAtExpectedInterval(1000000000); testRawRecordingSpeedAtExpectedInterval(10000); }
#vulnerable code @Test public void testRawRecordingSpeed() throws Exception { Histogram histogram = new Histogram(highestTrackableValue, numberOfSignificantValueDigits); // Warm up: long startTime = System.nanoTime(); recordLoop(histogram, warmupLoopLength); long endTime = System.nanoTime(); long deltaUsec = (endTime - startTime) / 1000L; long rate = 1000000 * warmupLoopLength / deltaUsec; System.out.println("Warmup:\n" + warmupLoopLength + " value recordings completed in " + deltaUsec + " usec, rate = " + rate + " value recording calls per sec."); histogram.reset(); // Wait a bit to make sure compiler had a cache to do it's stuff: try { Thread.sleep(1000); } catch (InterruptedException e) { } startTime = System.nanoTime(); recordLoop(histogram, timingLoopCount); endTime = System.nanoTime(); deltaUsec = (endTime - startTime) / 1000L; rate = 1000000 * timingLoopCount / deltaUsec; System.out.println("Timing:"); System.out.println(timingLoopCount + " value recordings completed in " + deltaUsec + " usec, rate = " + rate + " value recording calls per sec."); rate = 1000000 * histogram.getHistogramData().getTotalCount() / deltaUsec; System.out.println(histogram.getHistogramData().getTotalCount() + " raw recorded entries completed in " + deltaUsec + " usec, rate = " + rate + " recorded values per sec."); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, ModelAndView modelAndView) throws Exception { PostVO ret = (PostVO) modelAndView.getModelMap().get("view"); Object editing = modelAndView.getModel().get("editing"); if (null == editing && ret != null) { PostVO post = new PostVO(); BeanUtils.copyProperties(ret, post); if (check(ret.getId(), ret.getAuthor().getId())) { String c = post.getContent().replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", SHOW); post.setContent(c); } else { String c = post.getContent().replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", "$1"); post.setContent(c); } modelAndView.getModelMap().put("view", post); } }
#vulnerable code @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, ModelAndView modelAndView) throws Exception { PostVO ret = (PostVO) modelAndView.getModelMap().get("view"); Object editing = modelAndView.getModel().get("editing"); if (null == editing && ret != null) { PostVO post = new PostVO(); BeanUtils.copyProperties(ret, post); if (check(ret.getId(), ret.getAuthor().getId())) { post.setContent(replace(post.getContent())); } else { String c = post.getContent().replaceAll("&lt;hide&gt;", "<hide>"); c = c.replaceAll("&lt;/hide&gt;", "</hide>"); post.setContent(c); } modelAndView.getModelMap().put("view", post); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ServiceFlow [ flowName = "); builder.append(flowName); builder.append("\r\n\t"); ServiceConfig hh = header; buildString(hh, builder); builder.append("\n]"); return builder.toString(); }
#vulnerable code @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ServiceFlow [\r\n\tflowName = "); builder.append(flowName); builder.append("\r\n\t"); Set<ServiceConfig> nextServices = servicesOfFlow.get(getHeadServiceConfig().getServiceName()); builder.append(getHeadServiceConfig().getSimpleDesc()); builder.append(" --> "); getHeadServiceConfig().getNextServiceConfigs().forEach(item -> { builder.append(item.getSimpleDesc()).append(","); }); if (nextServices != null) { for (Map.Entry<String, Set<ServiceConfig>> entry : servicesOfFlow.entrySet()) { if (getHeadServiceConfig().getServiceName().equals(entry.getKey())) { continue; } builder.append("\r\n\t"); builder.append(getServiceConfig(entry.getKey()).getSimpleDesc()); builder.append(" -- > "); entry.getValue().forEach(item -> { builder.append(item.getSimpleDesc()).append(", "); }); } } builder.append("\n]"); return builder.toString(); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings({"unchecked", "rawtypes"}) @Override public void onServiceContextReceived(ServiceContext serviceContext) throws Throwable { FlowMessage flowMessage = serviceContext.getFlowMessage(); if (serviceContext.isSync()) { CacheManager.get(serviceActorCachePrefix + serviceContext.getFlowName()).add(serviceContext.getId(), getSender(), defaultTimeToLive); } Serializer serializer = ExtensionLoader.load(Serializer.class).load(serviceContext.getCodec()); Object result = null; Object param = null; try { ServiceContextUtil.fillServiceContext(serviceContext); param = getAndDecodeParam(serviceContext); if (getFilter(serviceContext) != null) { getFilter(serviceContext).filter(param, serviceContext); } // logger.info("服务参数类型 {} : {}", pType, getService(serviceContext)); result = ((Service) getService(serviceContext)).process(param, serviceContext); } catch (Throwable e) { handleException(serviceContext, e, param, serializer); } if (result != null && result instanceof CompletableFuture) { final Object tempParam = param; ((CompletableFuture<Object>) result).whenComplete((r, e) -> { if (e != null) { handleException(serviceContext, e, tempParam, serializer); return; } handleNextServices(serviceContext, r, flowMessage.getTransactionId(), serializer); }); } else { handleNextServices(serviceContext, result, flowMessage.getTransactionId(), serializer); } }
#vulnerable code @SuppressWarnings({"unchecked", "rawtypes"}) @Override public void onServiceContextReceived(ServiceContext serviceContext) throws Throwable { FlowMessage flowMessage = serviceContext.getFlowMessage(); if (serviceContext.isSync()) { CacheManager.get(serviceActorCachePrefix + serviceContext.getFlowName()).add(serviceContext.getId(), getSender(), defaultTimeToLive); } Serializer serializer = ExtensionLoader.load(Serializer.class).load(serviceContext.getCodec()); Object result = null; Object param = null; try { ServiceContextUtil.fillServiceContext(serviceContext); String pType = getParamType(serviceContext); if (flowMessage.getMessage() != null && ClassUtil.exists(flowMessage.getMessageType())) { pType = flowMessage.getMessageType(); } param = serializer.decode(flowMessage.getMessage(), pType); if (getFilter(serviceContext) != null) { getFilter(serviceContext).filter(param, serviceContext); } // logger.info("服务参数类型 {} : {}", pType, getService(serviceContext)); result = ((Service) getService(serviceContext)).process(param, serviceContext); } catch (Throwable e) { handleException(serviceContext, e, param, serializer); } if (result != null && result instanceof CompletableFuture) { final Object tempParam = param; ((CompletableFuture<Object>) result).whenComplete((r, e) -> { if (e != null) { handleException(serviceContext, e, tempParam, serializer); return; } handleNextServices(serviceContext, r, flowMessage.getTransactionId(), serializer); }); } else { handleNextServices(serviceContext, result, flowMessage.getTransactionId(), serializer); } } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doStartup(String configLocation) throws Throwable { Class<?> applicationContextClazz = Class.forName("org.springframework.context.support.ClassPathXmlApplicationContext", true, getClassLoader()); Object flowerFactory = applicationContextClazz.getConstructor(String.class).newInstance(configLocation); Method startMethod = applicationContextClazz.getMethod("start"); startMethod.invoke(flowerFactory); logger.info("spring初始化完成"); }
#vulnerable code @Override public void doStartup(String configLocation) { ClassPathXmlApplicationContext applicationContext = null; try { applicationContext = new ClassPathXmlApplicationContext(configLocation); applicationContext.start(); } catch (Exception e) { if (applicationContext != null) { applicationContext.close(); } logger.error("", e); } logger.info("spring初始化完成"); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static List<Pair<String, String>> readFlow(String path) throws IOException { InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path),Constant.ENCODING_UTF_8); BufferedReader br = new BufferedReader(fr); String line; List<Pair<String, String>> flow = new ArrayList<>(); while ((line = br.readLine()) != null) { String sl = line.trim(); if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) { continue; } String[] connection = sl.split("->"); if (connection == null || connection.length != 2) { close(br, fr); throw new RuntimeException("Illegal flow config:" + path); } else { flow.add(new Pair<String, String>(connection[0].trim(), connection[1].trim())); } } close(br, fr); return flow; }
#vulnerable code public static List<Pair<String, String>> readFlow(String path) throws IOException { InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path)); BufferedReader br = new BufferedReader(fr); String line = ""; List<Pair<String, String>> flow = new ArrayList<>(); while ((line = br.readLine()) != null) { String sl = line.trim(); if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) { continue; } String[] connection = sl.split("->"); if (connection == null || connection.length != 2) { close(br, fr); throw new RuntimeException("Illegal flow config:" + path); } else { flow.add(new Pair<String, String>(connection[0].trim(), connection[1].trim())); } } close(br, fr); return flow; } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private EnvTypePair analyzeLooseCallNodeBwd( Node callNode, TypeEnv outEnv, JSType retType) { Preconditions.checkArgument(callNode.isCall()); Preconditions.checkNotNull(retType); Node callee = callNode.getFirstChild(); TypeEnv tmpEnv = outEnv; FunctionTypeBuilder builder = new FunctionTypeBuilder(); for (int i = callNode.getChildCount() - 2; i >= 0; i--) { Node arg = callNode.getChildAtIndex(i + 1); tmpEnv = analyzeExprBwd(arg, tmpEnv).env; // Wait until FWD to get more precise argument types. builder.addReqFormal(JSType.BOTTOM); } JSType looseRetType = retType.isUnknown() ? JSType.BOTTOM : retType; JSType looseFunctionType = builder.addRetType(looseRetType).addLoose().buildType(); println("loose function type is ", looseFunctionType); EnvTypePair calleePair = analyzeExprBwd(callee, tmpEnv, looseFunctionType); return new EnvTypePair(calleePair.env, retType); }
#vulnerable code private EnvTypePair analyzeLooseCallNodeBwd( Node callNode, TypeEnv outEnv, JSType retType) { Preconditions.checkArgument(callNode.isCall()); Preconditions.checkNotNull(retType); Node callee = callNode.getFirstChild(); TypeEnv tmpEnv = outEnv; FunctionTypeBuilder builder = new FunctionTypeBuilder(); for (int i = callNode.getChildCount() - 2; i >= 0; i--) { Node arg = callNode.getChildAtIndex(i + 1); tmpEnv = analyzeExprBwd(arg, tmpEnv).env; // Wait until FWD to get more precise argument types. builder.addReqFormal(JSType.BOTTOM); } JSType looseRetType = retType.isUnknown() ? JSType.BOTTOM : retType; JSType looseFunctionType = builder.addRetType(looseRetType).addLoose().buildType(); looseFunctionType.getFunType().checkValid(); println("loose function type is ", looseFunctionType); EnvTypePair calleePair = analyzeExprBwd(callee, tmpEnv, looseFunctionType); return new EnvTypePair(calleePair.env, retType); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<JSSourceFile> getDefaultExterns() { try { return CommandLineRunner.getDefaultExterns(); } catch (IOException e) { throw new BuildException(e); } }
#vulnerable code private List<JSSourceFile> getDefaultExterns() { try { InputStream input = Compiler.class.getResourceAsStream( "/externs.zip"); ZipInputStream zip = new ZipInputStream(input); List<JSSourceFile> externs = Lists.newLinkedList(); for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) { LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize()); externs.add( JSSourceFile.fromInputStream(entry.getName(), entryStream)); } return externs; } catch (IOException e) { throw new BuildException(e); } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void writeResult(String source) { if (this.outputFile.getParentFile().mkdirs()) { log("Created missing parent directory " + this.outputFile.getParentFile(), Project.MSG_DEBUG); } try { OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(this.outputFile), outputEncoding); out.append(source); out.flush(); out.close(); } catch (IOException e) { throw new BuildException(e); } log("Compiled javascript written to " + this.outputFile.getAbsolutePath(), Project.MSG_DEBUG); }
#vulnerable code private void writeResult(String source) { if (this.outputFile.getParentFile().mkdirs()) { log("Created missing parent directory " + this.outputFile.getParentFile(), Project.MSG_DEBUG); } try { FileWriter out = new FileWriter(this.outputFile); out.append(source); out.close(); } catch (IOException e) { throw new BuildException(e); } log("Compiled javascript written to " + this.outputFile.getAbsolutePath(), Project.MSG_DEBUG); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Writer fileNameToOutputWriter(String fileName) throws IOException { if (fileName == null) { return null; } if (testMode) { return new StringWriter(); } return streamToOutputWriter(filenameToOutputStream(fileName)); }
#vulnerable code private Writer fileNameToOutputWriter(String fileName) throws IOException { if (fileName == null) { return null; } if (testMode) { return new StringWriter(); } return streamToOutputWriter(new FileOutputStream(fileName)); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<INPUT> getSortedDependenciesOf(List<INPUT> roots) { return getDependenciesOf(roots, true); }
#vulnerable code public List<INPUT> getSortedDependenciesOf(List<INPUT> roots) { Preconditions.checkArgument(inputs.containsAll(roots)); Set<INPUT> included = Sets.newHashSet(); Deque<INPUT> worklist = new ArrayDeque<INPUT>(roots); while (!worklist.isEmpty()) { INPUT current = worklist.pop(); if (included.add(current)) { for (String req : current.getRequires()) { INPUT dep = provideMap.get(req); if (dep != null) { worklist.add(dep); } } } } ImmutableList.Builder<INPUT> builder = ImmutableList.builder(); for (INPUT current : sortedList) { if (included.contains(current)) { builder.add(current); } } return builder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Set<String> getOwnPropertyNames() { return getPropertyMap().getOwnPropertyNames(); }
#vulnerable code public Set<String> getOwnPropertyNames() { return ImmutableSet.of(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST