output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@Override
public boolean acceptSolution(Collection<VehicleRoutingProblemSolution> solutions, VehicleRoutingProblemSolution newSolution) {
boolean solutionAccepted = false;
if (solutions.size() < solutionMemory) {
solutions.add(newSolution);
solutionAccepted = true;
} else {
VehicleRoutingProblemSolution worst = null;
double threshold = getThreshold(currentIteration);
for(VehicleRoutingProblemSolution solutionInMemory : solutions){
if(worst == null) worst = solutionInMemory;
else if(solutionInMemory.getCost() > worst.getCost()) worst = solutionInMemory;
}
if(worst == null){
solutions.add(newSolution);
solutionAccepted = true;
}
else if(newSolution.getCost() < worst.getCost() + threshold){
solutions.remove(worst);
solutions.add(newSolution);
solutionAccepted = true;
}
}
return solutionAccepted;
} | #vulnerable code
@Override
public boolean acceptSolution(Collection<VehicleRoutingProblemSolution> solutions, VehicleRoutingProblemSolution newSolution) {
boolean solutionAccepted = false;
if (solutions.size() < solutionMemory) {
solutions.add(newSolution);
solutionAccepted = true;
} else {
VehicleRoutingProblemSolution worst = null;
double threshold = getThreshold(currentIteration);
for(VehicleRoutingProblemSolution solutionInMemory : solutions){
if(worst == null) worst = solutionInMemory;
else if(solutionInMemory.getCost() > worst.getCost()) worst = solutionInMemory;
}
if(newSolution.getCost() < worst.getCost() + threshold){
solutions.remove(worst);
solutions.add(newSolution);
solutionAccepted = true;
}
}
return solutionAccepted;
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void skillViolationAtAct3_shouldWork(){
SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() {
@Override
public double getDistance(String fromLocationId, String toLocationId) {
return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null);
}
});
VehicleRoute route = solution.getRoutes().iterator().next();
Boolean violated = analyser.hasSkillConstraintViolationAtActivity(route.getActivities().get(2), route);
assertTrue(violated);
} | #vulnerable code
@Test
public void skillViolationAtAct3_shouldWork(){
SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() {
@Override
public double getDistance(String fromLocationId, String toLocationId) {
return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null);
}
});
VehicleRoute route = solution.getRoutes().iterator().next();
Boolean violated = analyser.skillConstraintIsViolatedAtActivity(route.getActivities().get(2),route);
assertTrue(violated);
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void informAlgorithmStarts(VehicleRoutingProblem problem, VehicleRoutingAlgorithm algorithm, Collection<VehicleRoutingProblemSolution> solutions) {
reset();
logger.info("---------------------------------------------------------------------");
logger.info("prepare schrimpfAcceptanceFunction, i.e. determine initial threshold");
logger.info("start random-walk (see randomWalk.xml)");
double now = System.currentTimeMillis();
this.nOfTotalIterations = algorithm.getNuOfIterations();
/*
* randomWalk to determine standardDev
*/
final double[] results = new double[nOfRandomWalks];
URL resource = Resource.getAsURL("randomWalk.xml");
AlgorithmConfig algorithmConfig = new AlgorithmConfig();
new AlgorithmConfigXmlReader(algorithmConfig).read(resource);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.createAlgorithm(problem, algorithmConfig);
vra.setNuOfIterations(nOfRandomWalks);
vra.getAlgorithmListeners().addListener(new IterationEndsListener() {
@Override
public void informIterationEnds(int iteration, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
double result = Solutions.getBest(solutions).getCost();
// logger.info("result="+result);
results[iteration-1] = result;
}
});
vra.searchSolutions();
StandardDeviation dev = new StandardDeviation();
double standardDeviation = dev.evaluate(results);
initialThreshold = standardDeviation / 2;
logger.info("warmup done");
logger.info("total time: " + ((System.currentTimeMillis()-now)/1000.0) + "s");
logger.info("initial threshold: " + initialThreshold);
logger.info("---------------------------------------------------------------------");
} | #vulnerable code
@Override
public void informAlgorithmStarts(VehicleRoutingProblem problem, VehicleRoutingAlgorithm algorithm, Collection<VehicleRoutingProblemSolution> solutions) {
reset();
logger.info("---------------------------------------------------------------------");
logger.info("prepare schrimpfAcceptanceFunction, i.e. determine initial threshold");
logger.info("start random-walk (see algorith-config at scr/main/resources/randomWalk.xml)");
double now = System.currentTimeMillis();
this.nOfTotalIterations = algorithm.getNuOfIterations();
/*
* randomWalk to determine standardDev
*/
final double[] results = new double[nOfRandomWalks];
URL resource = Resource.getAsURL("randomWalk.xml");
AlgorithmConfig algorithmConfig = new AlgorithmConfig();
new AlgorithmConfigXmlReader(algorithmConfig).read(resource.getPath());
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.createAlgorithm(problem, algorithmConfig);
vra.setNuOfIterations(nOfRandomWalks);
vra.getAlgorithmListeners().addListener(new IterationEndsListener() {
@Override
public void informIterationEnds(int iteration, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
double result = Solutions.getBest(solutions).getCost();
// logger.info("result="+result);
results[iteration-1] = result;
}
});
vra.searchSolutions();
StandardDeviation dev = new StandardDeviation();
double standardDeviation = dev.evaluate(results);
initialThreshold = standardDeviation / 2;
logger.info("warmup done");
logger.info("total time: " + ((System.currentTimeMillis()-now)/1000.0) + "s");
logger.info("initial threshold: " + initialThreshold);
logger.info("---------------------------------------------------------------------");
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void whenWritingVehicleV2_readingAgainAssignsCorrectType(){
Builder builder = VehicleRoutingProblem.Builder.newInstance();
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build();
VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build();
VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setReturnToDepot(false).setStartLocation(TestUtils.loc("loc")).setType(type1).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocation(TestUtils.loc("loc")).setType(type2).build();
builder.addVehicle(v1);
builder.addVehicle(v2);
Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc")).setServiceTime(2.0).build();
Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc2")).setServiceTime(4.0).build();
VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build();
new VrpXMLWriter(vrp, null).write(infileName);
VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance();
new VrpXMLReader(vrpToReadBuilder, null).read(infileName);
VehicleRoutingProblem readVrp = vrpToReadBuilder.build();
Vehicle v = getVehicle("v2",readVrp.getVehicles());
assertEquals("vehType2",v.getType().getTypeId());
assertEquals(200,v.getType().getCapacityDimensions().get(0));
} | #vulnerable code
@Test
public void whenWritingVehicleV2_readingAgainAssignsCorrectType(){
Builder builder = VehicleRoutingProblem.Builder.newInstance();
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build();
VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build();
VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setReturnToDepot(false).setStartLocationId("loc").setType(type1).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocationId("loc").setType(type2).build();
builder.addVehicle(v1);
builder.addVehicle(v2);
Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocationId("loc").setServiceTime(2.0).build();
Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocationId("loc2").setServiceTime(4.0).build();
VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build();
new VrpXMLWriter(vrp, null).write(infileName);
VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance();
new VrpXMLReader(vrpToReadBuilder, null).read(infileName);
VehicleRoutingProblem readVrp = vrpToReadBuilder.build();
Vehicle v = getVehicle("v2",readVrp.getVehicles());
assertEquals("vehType2",v.getType().getTypeId());
assertEquals(200,v.getType().getCapacityDimensions().get(0));
}
#location 24
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void read(String filename) {
logger.debug("read vrp: {}", filename);
XMLConfiguration xmlConfig = createXMLConfiguration();
try {
xmlConfig.load(filename);
} catch (ConfigurationException e) {
throw new RuntimeException(e);
}
read(xmlConfig);
} | #vulnerable code
public void read(String filename) {
logger.debug("read vrp: {}", filename);
XMLConfiguration xmlConfig = new XMLConfiguration();
xmlConfig.setFileName(filename);
xmlConfig.setAttributeSplittingDisabled(true);
xmlConfig.setDelimiterParsingDisabled(true);
if (schemaValidation) {
final InputStream resource = Resource.getAsInputStream("vrp_xml_schema.xsd");
if (resource != null) {
EntityResolver resolver = new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
{
InputSource is = new InputSource(resource);
return is;
}
}
};
xmlConfig.setEntityResolver(resolver);
xmlConfig.setSchemaValidation(true);
} else {
logger.debug("cannot find schema-xsd file (vrp_xml_schema.xsd). try to read xml without xml-file-validation.");
}
}
try {
xmlConfig.load();
} catch (ConfigurationException e) {
throw new RuntimeException(e);
}
readProblemType(xmlConfig);
readVehiclesAndTheirTypes(xmlConfig);
readShipments(xmlConfig);
readServices(xmlConfig);
readInitialRoutes(xmlConfig);
readSolutions(xmlConfig);
addJobsAndTheirLocationsToVrp();
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@JsonIgnore
@Override
public String getImageId() {
/*Image image = getImage();
return (image != null) ? image.getId() : null;*/
if(image instanceof Map) {
Map<String, String> map = (Map<String, String>) image;
return map.get("id");
}
return null;
} | #vulnerable code
@JsonIgnore
@Override
public String getImageId() {
/*Image image = getImage();
return (image != null) ? image.getId() : null;*/
if(image instanceof Map) {
Map<String, String> map = (Map<String, String>) image;
return map.get("id");
}
return getImage().getId();
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private String resolveV3(URLResolverParams p) {
Token token = p.token;
//in v3 api, if user has no default project, and token is unscoped, no catalog will be returned
//then if service is Identity service, should directly return the endpoint back
if (token.getCatalog() == null) {
if (ServiceType.IDENTITY.equals(p.type)) {
return token.getEndpoint();
} else {
return null;
}
}
for (org.openstack4j.model.identity.v3.Service service : token.getCatalog()) {
if (p.type == ServiceType.forName(service.getType())) {
if (p.perspective == null) {
p.perspective = Facing.PUBLIC;
}
for (org.openstack4j.model.identity.v3.Endpoint ep : service.getEndpoints()) {
if (matches(ep, p))
return ep.getUrl().toString();
}
}
}
return null;
} | #vulnerable code
private String resolveV3(URLResolverParams p) {
Token token = p.token;
//in v3 api, if user has no default project, and token is unscoped, no catalog will be returned
//then if service is Identity service, should directly return the endpoint back
if (token.getCatalog() == null) {
if (ServiceType.IDENTITY.equals(p.type)) {
return token.getEndpoint();
}
}
for (org.openstack4j.model.identity.v3.Service service : token.getCatalog()) {
if (p.type == ServiceType.forName(service.getType())) {
if (p.perspective == null) {
p.perspective = Facing.PUBLIC;
}
for (org.openstack4j.model.identity.v3.Endpoint ep : service.getEndpoints()) {
if (matches(ep, p)) {
//some installation have v2.0 url in catalog for v3 identity api
//some other the url does not have version in it
//so we do an additional check here for identity service only
if (ServiceType.IDENTITY.equals(ServiceType.forName(service.getType()))) {
String v3Url = ep.getUrl().toString();
if (v3Url.endsWith("/v3") || v3Url.endsWith("/v3/") ) {
} else if (v3Url.endsWith("/v2.0") || v3Url.endsWith("/v2.0/") ) {
v3Url = v3Url.replace("v2.0", "v3");
} else {
v3Url = v3Url + "/v3";
}
LOG.trace("resolved v3 endpoint for identity service: {}", v3Url);
return v3Url;
} else {
return ep.getUrl().toString();
}
}
}
}
}
return null;
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static IpPool getIpPool() {
if (ipPool == null) {
synchronized (IpPoolHolder.class) {
if (ipPool == null) {
ipPool = IpPool.create(DungProxyContext.create().buildDefaultConfigFile());
}
}
}
return ipPool;
} | #vulnerable code
public static IpPool getIpPool() {
if (ipPool == null) {
synchronized (IpPoolHolder.class) {
if (ipPool == null) {
ipPool = IpPool.create(DungProxyContext.create().buildDefaultConfigFile().handleConfig());
}
}
}
return ipPool;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public AvProxy bind(String url, Object userID) {
if (testUrls.size() < 10) {
testUrls.add(url);
} else {
testUrls.set(random.nextInt(10), url);
}
if (consistentBuckets.size() < minSize) {
refreshInNewThread();//在新线程刷新
}
readWriteLock.readLock().lock();
try {
if(consistentBuckets.size() ==0){
return Context.getInstance().getDefaultProxy();
}
// 注意hash空间问题,之前是Integer,hash值就是字面值,导致hash空间只存在了正数空间
AvProxy hint = hint(userID == null ? String.valueOf(random.nextInt()).hashCode() : userID.hashCode());
if (userID != null && hint != null) {
if (!hint.equals(bindMap.get(userID))) {
// IP 绑定改变事件
}
bindMap.put(userID, hint);
}
return hint;
} finally {
readWriteLock.readLock().unlock();
}
} | #vulnerable code
public AvProxy bind(String url, Object userID) {
if (testUrls.size() < 10) {
testUrls.add(url);
} else {
testUrls.set(random.nextInt(10), url);
}
if (consistentBuckets.size() < minSize) {
fresh();
}
readWriteLock.readLock().lock();
try {// 注意hash空间问题,之前是Integer,hash值就是字面值,导致hash空间只存在了正数空间
AvProxy hint = hint(userID == null ? String.valueOf(random.nextInt()).hashCode() : userID.hashCode());
if (userID != null && hint != null) {
if (!hint.equals(bindMap.get(userID))) {
// IP 绑定改变事件
}
bindMap.put(userID, hint);
}
return hint;
} finally {
readWriteLock.readLock().unlock();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public AvProxy bind(String url) {
if (testUrls.size() < 10) {
testUrls.add(url);
} else {
testUrls.set(random.nextInt(10), url);
}
if (needFresh()) {
refresh();// 在新线程刷新
}
return smartProxyQueue.getAndAdjustPriority();
} | #vulnerable code
public AvProxy bind(String url) {
if (testUrls.size() < 10) {
testUrls.add(url);
} else {
testUrls.set(random.nextInt(10), url);
}
if (needFresh()) {
refresh();// 在新线程刷新
}
readWriteLock.readLock().lock();
try {
return smartProxyQueue.getAndAdjustPriority();
} finally {
readWriteLock.readLock().unlock();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void refresh() {
if (testUrls.size() == 0) {
return;// 数据还没有进来,不refresh
}
int expectedThreadNumber = expectedRefreshTaskNumber();
if (refreshTaskNumber.get() > expectedThreadNumber) {
// logger.info("当前刷新线程数:{} 大于调度线程数:{} 取消本次IP资源刷新任务", refreshTaskNumber.get(), expectedThreadNumber);
return;
}
if (refreshTaskNumber.incrementAndGet() <= expectedThreadNumber) {
Thread thread = new Thread() {
@Override
public void run() {
try {
logger.info("IP资源刷新开始,当前刷新线程数量:{}...", refreshTaskNumber.get());
doRefresh();
logger.info("IP资源刷新结束...");
} finally {
refreshTaskNumber.decrementAndGet();
}
}
};
thread.setDaemon(true);
thread.start();
}
} | #vulnerable code
public void refresh() {
if (testUrls.size() == 0) {
return;// 数据还没有进来,不refresh
}
int expectedThreadNumber = expectedRefreshTaskNumber();
if (refreshTaskNumber.get() > expectedThreadNumber) {
logger.info("当前刷新线程数:{} 大于调度线程数:{} 取消本次IP资源刷新任务", refreshTaskNumber.get(), expectedThreadNumber);
return;
}
if (refreshTaskNumber.incrementAndGet() <= expectedThreadNumber) {
try {
logger.info("IP资源刷新开始...");
doRefresh();
logger.info("IP资源刷新结束...");
} finally {
refreshTaskNumber.decrementAndGet();
}
}
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNPE() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = getPrintStream(os);
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
try {
sqlLine.runCommands(new DispatchCallback(), "!typeinfo");
String output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
sqlLine.runCommands(new DispatchCallback(), "!nativesql");
output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testNPE() {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = getPrintStream(os);
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
try {
sqlLine.runCommands(new DispatchCallback(), "!typeinfo");
String output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
sqlLine.runCommands(new DispatchCallback(), "!nativesql");
output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#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 testHelpSet() {
final String expected = "1/1 !help set\n"
+ "!set List / set a sqlline variable\n"
+ "\n"
+ "Variables:\n"
+ "\n"
+ "Variable Value Description\n"
+ "=============== ========== "
+ "==================================================\n"
+ "autoCommit true/false "
+ "Enable/disable automatic transaction commit\n"
+ "autoSave true/false Automatically save preferences\n";
checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK),
containsString(expected));
// Make sure that each variable (autoCommit, autoSave, color, etc.) has a
// line in the output of '!help set'
String help = sqlLine.loc("help-set")
+ sqlLine.loc("variables");
final TreeSet<String> propertyNamesMixed =
Arrays.stream(BuiltInProperty.values())
.map(BuiltInProperty::propertyName)
.collect(Collectors.toCollection(TreeSet::new));
for (String p : propertyNamesMixed) {
assertThat(help, containsString("\n" + p + " "));
}
assertThat(propertyNamesMixed.contains("autoCommit"),
is(true));
assertThat(propertyNamesMixed.contains("autocommit"),
is(false));
assertThat(propertyNamesMixed.contains("trimScripts"),
is(true));
while (help.length() > 0) {
int i = help.indexOf("\n", 1);
if (i < 0) {
break;
}
if (i > 78) {
fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i));
}
help = help.substring(i);
}
} | #vulnerable code
@Test
public void testHelpSet() {
final String expected = "1/1 !help set\n"
+ "!set List / set a sqlline variable\n"
+ "\n"
+ "Variables:\n"
+ "\n"
+ "Variable Value Description\n"
+ "=============== ========== "
+ "==================================================\n"
+ "autoCommit true/false "
+ "Enable/disable automatic transaction commit\n"
+ "autoSave true/false Automatically save preferences\n";
checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK),
containsString(expected));
// Make sure that each variable (autoCommit, autoSave, color, etc.) has a
// line in the output of '!help set'
final SqlLine sqlLine = new SqlLine();
String help = sqlLine.loc("help-set")
+ sqlLine.loc("variables");
final TreeSet<String> propertyNamesMixed =
Arrays.stream(BuiltInProperty.values())
.map(BuiltInProperty::propertyName)
.collect(Collectors.toCollection(TreeSet::new));
for (String p : propertyNamesMixed) {
assertThat(help, containsString("\n" + p + " "));
}
assertThat(propertyNamesMixed.contains("autoCommit"),
is(true));
assertThat(propertyNamesMixed.contains("autocommit"),
is(false));
assertThat(propertyNamesMixed.contains("trimScripts"),
is(true));
while (help.length() > 0) {
int i = help.indexOf("\n", 1);
if (i < 0) {
break;
}
if (i > 78) {
fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i));
}
help = help.substring(i);
}
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMaxHistoryFileRows() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n"
+ "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n"
+ "1536743107526:!history\n"
+ "1536743115431:SELECT \\n 2 \\n as \\n c2;\n"
+ "1536743115431:SELECT \\n '213' \\n as \\n c1;\n"
+ "1536743115431:!/ 8\n");
bw.flush();
bw.close();
SqlLine.Status status = begin(sqlLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
final int maxLines = 3;
sqlLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines);
os.reset();
sqlLine.runCommands(dc, "!history");
assertEquals(maxLines + 1,
os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length);
os.reset();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testMaxHistoryFileRows() {
final SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n"
+ "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n"
+ "1536743107526:!history\n"
+ "1536743115431:SELECT \\n 2 \\n as \\n c2;\n"
+ "1536743115431:SELECT \\n '213' \\n as \\n c1;\n"
+ "1536743115431:!/ 8\n");
bw.flush();
bw.close();
SqlLine.Status status = begin(beeLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
final int maxLines = 3;
beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines);
os.reset();
beeLine.runCommands(dc, "!history");
assertEquals(maxLines + 1,
os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length);
os.reset();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 36
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
SqlLine()
{
sqlLineCommandCompleter = new SQLLineCommandCompleter();
// attempt to dynamically load signal handler
try {
Class handlerClass = Class.forName("sqlline.SunSignalHandler");
signalHandler = (SqlLineSignalHandler) handlerClass.newInstance();
} catch (Throwable t) {
handleException(t);
}
} | #vulnerable code
Driver [] scanDriversOLD(String line)
{
long start = System.currentTimeMillis();
Set paths = new HashSet();
Set driverClasses = new HashSet();
for (
StringTokenizer tok =
new StringTokenizer(
System.getProperty("java.ext.dirs"),
System.getProperty("path.separator"));
tok.hasMoreTokens();)
{
File [] files = new File(tok.nextToken()).listFiles();
for (int i = 0; (files != null) && (i < files.length); i++) {
paths.add(files[i].getAbsolutePath());
}
}
for (
StringTokenizer tok =
new StringTokenizer(
System.getProperty("java.class.path"),
System.getProperty("path.separator"));
tok.hasMoreTokens();)
{
paths.add(new File(tok.nextToken()).getAbsolutePath());
}
for (Iterator i = paths.iterator(); i.hasNext();) {
File f = new File((String) i.next());
output(
color().pad(loc("scanning", f.getAbsolutePath()), 60),
false);
try {
ZipFile zf = new ZipFile(f);
int total = zf.size();
int index = 0;
for (
Enumeration zfEnum = zf.entries();
zfEnum.hasMoreElements();)
{
ZipEntry entry = (ZipEntry) zfEnum.nextElement();
String name = entry.getName();
progress(index++, total);
if (name.endsWith(".class")) {
name = name.replace('/', '.');
name = name.substring(0, name.length() - 6);
try {
// check for the string "driver" in the class
// to see if we should load it. Not perfect, but
// it is far too slow otherwise.
if (name.toLowerCase().indexOf("driver") != -1) {
Class c =
Class.forName(
name,
false,
getClass().getClassLoader());
if (Driver.class.isAssignableFrom(c)
&& !(Modifier.isAbstract(
c.getModifiers())))
{
try {
// load and initialize
Class.forName(name);
} catch (Exception e) {
}
driverClasses.add(c.newInstance());
}
}
} catch (Throwable t) {
}
}
}
progress(total, total);
} catch (Exception e) {
}
}
info("scan complete in "
+ (System.currentTimeMillis() - start) + "ms");
return (Driver []) driverClasses.toArray(new Driver[0]);
}
#location 81
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testPromptWithNickname() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
final SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"");
// custom prompt with data from connection
final SqlLineOpts opts = sqlLine.getOpts();
sqlLine.getDatabaseConnection().setNickname("nickname");
opts.set(BuiltInProperty.PROMPT, "%u@%n>");
opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c");
// if nickname is specified for the connection
// it has more priority than prompt.
// Right prompt does not care about nickname
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("0: nickname> "));
assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(),
is("//H20"));
sqlLine.getDatabaseConnection().close();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testPromptWithNickname() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine sqlLine = new SqlLine();
try {
final SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"");
// custom prompt with data from connection
final SqlLineOpts opts = sqlLine.getOpts();
sqlLine.getDatabaseConnection().setNickname("nickname");
opts.set(BuiltInProperty.PROMPT, "%u@%n>");
opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c");
// if nickname is specified for the connection
// it has more priority than prompt.
// Right prompt does not care about nickname
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("0: nickname> "));
assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(),
is("//H20"));
sqlLine.getDatabaseConnection().close();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testInitArgsForSuccessConnection() {
try {
final String[] nicknames = new String[1];
new MockUp<sqlline.DatabaseConnection>() {
@Mock
void setNickname(String nickname) {
nicknames[0] = nickname;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String filename = "file' with spaces";
String[] connectionArgs = {
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"-p", ConnectionSpec.H2.password,
"-nn", "nickname with spaces",
"-log", "target" + File.separator + filename,
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertThat("file with spaces",
Files.exists(Paths.get("target", filename)));
assertEquals("nickname with spaces", nicknames[0]);
} catch (Throwable t) {
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testInitArgsForSuccessConnection() {
try {
final String[] nicknames = new String[1];
new MockUp<sqlline.DatabaseConnection>() {
@Mock
void setNickname(String nickname) {
nicknames[0] = nickname;
}
};
final SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String filename = "file' with spaces";
String[] connectionArgs = new String[] {
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"-p", ConnectionSpec.H2.password,
"-nn", "nickname with spaces",
"-log", "target/" + filename,
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertThat("file with spaces",
Files.exists(Paths.get("target", filename)));
assertEquals("nickname with spaces", nicknames[0]);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ConsoleReader getConsoleReader(InputStream inputStream)
throws IOException
{
Terminal terminal = TerminalFactory.create();
if (inputStream != null) {
// ### NOTE: fix for sf.net bug 879425.
reader =
new ConsoleReader(
inputStream,
System.out);
} else {
reader = new ConsoleReader();
}
// setup history
ByteArrayInputStream historyBuffer = null;
if (new File(opts.getHistoryFile()).isFile()) {
try {
// save the current contents of the history buffer. This gets
// around a bug in JLine where setting the output before the
// input will clobber the history input, but setting the
// input before the output will cause the previous commands
// to not be saved to the buffer.
InputStream historyIn = new BufferedInputStream(
new FileInputStream(
opts.getHistoryFile()));
ByteArrayOutputStream hist = new ByteArrayOutputStream();
int n;
while ((n = historyIn.read()) != -1) {
hist.write(n);
}
historyIn.close();
historyBuffer = new ByteArrayInputStream(hist.toByteArray());
} catch (Exception e) {
handleException(e);
}
}
try {
FileHistory history = new FileHistory( new File (opts.getHistoryFile() ) ) ;
if (null != historyBuffer) {
history.load( historyBuffer );
}
reader.setHistory( history );
} catch (Exception e) {
handleException(e);
}
reader.addCompleter( new SQLLineCompleter() );
return reader;
} | #vulnerable code
public ConsoleReader getConsoleReader(InputStream inputStream)
throws IOException
{
Terminal terminal = Terminal.setupTerminal();
if (inputStream != null) {
// ### NOTE: fix for sf.net bug 879425.
reader =
new ConsoleReader(
inputStream,
new PrintWriter(System.out));
} else {
reader = new ConsoleReader();
}
// setup history
ByteArrayInputStream historyBuffer = null;
if (new File(opts.getHistoryFile()).isFile()) {
try {
// save the current contents of the history buffer. This gets
// around a bug in JLine where setting the output before the
// input will clobber the history input, but setting the
// input before the output will cause the previous commands
// to not be saved to the buffer.
FileInputStream historyIn =
new FileInputStream(
opts.getHistoryFile());
ByteArrayOutputStream hist = new ByteArrayOutputStream();
int n;
while ((n = historyIn.read()) != -1) {
hist.write(n);
}
historyIn.close();
historyBuffer = new ByteArrayInputStream(hist.toByteArray());
} catch (Exception e) {
handleException(e);
}
}
try {
// now set the output for the history
PrintWriter historyOut =
new PrintWriter(new FileWriter(
opts.getHistoryFile()));
reader.getHistory().setOutput(historyOut);
} catch (Exception e) {
handleException(e);
}
try {
// now load in the previous history
if (historyBuffer != null) {
reader.getHistory().load(historyBuffer);
}
} catch (Exception e) {
handleException(e);
}
reader.addCompletor(new SQLLineCompletor());
return reader;
}
#location 37
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMultilineScriptWithH2Comments() {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
final File tmpHistoryFile = createTempFile("queryToExecute", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
final String script = "\n"
+ "\n"
+ "!set incremental true\n"
+ "\n"
+ "\n"
+ "select * from information_schema.tables// ';\n"
+ "// \";"
+ ";\n"
+ "\n"
+ "\n";
bw.write(script);
bw.flush();
}
SqlLine.Status status =
begin(sqlLine, os, false,
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"--run=" + tmpHistoryFile.getAbsolutePath());
assertThat(status, equalTo(SqlLine.Status.OK));
String output = os.toString("UTF8");
final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |"
+ " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testMultilineScriptWithH2Comments() {
final SqlLine sqlLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
final File tmpHistoryFile = createTempFile("queryToExecute", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
final String script = "\n"
+ "\n"
+ "!set incremental true\n"
+ "\n"
+ "\n"
+ "select * from information_schema.tables// ';\n"
+ "// \";"
+ ";\n"
+ "\n"
+ "\n";
bw.write(script);
bw.flush();
}
SqlLine.Status status =
begin(sqlLine, os, false,
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"--run=" + tmpHistoryFile.getAbsolutePath());
assertThat(status, equalTo(SqlLine.Status.OK));
String output = os.toString("UTF8");
final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |"
+ " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 34
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testOutputWithFailingColumnDisplaySize(
@Mocked final JDBCResultSetMetaData meta) {
try {
new Expectations() {
{
meta.getColumnCount();
result = 3;
meta.getColumnLabel(1);
result = "TABLE_CAT";
meta.getColumnLabel(2);
result = "TABLE_SCHEM";
meta.getColumnLabel(3);
result = "TABLE_NAME";
meta.getColumnDisplaySize(1);
result = new Exception("getColumnDisplaySize exception");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"!set incremental true",
"!set maxwidth 80",
"!set verbose true",
"!indexes");
assertThat(os.toString("UTF8"), not(containsString("Exception")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testOutputWithFailingColumnDisplaySize(
@Mocked final JDBCResultSetMetaData meta) {
try {
new Expectations() {
{
meta.getColumnCount();
result = 3;
meta.getColumnLabel(1);
result = "TABLE_CAT";
meta.getColumnLabel(2);
result = "TABLE_SCHEM";
meta.getColumnLabel(3);
result = "TABLE_NAME";
meta.getColumnDisplaySize(1);
result = new Exception("getColumnDisplaySize exception");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"!set incremental true",
"!set maxwidth 80",
"!set verbose true",
"!indexes");
assertThat(os.toString("UTF8"), not(containsString("Exception")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#location 51
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConfirmFlagEffects() {
new MockUp<sqlline.Commands>() {
@Mock
int getUserAnswer(String question, int... allowedAnswers) {
return 'n';
}
};
assertThat(sqlLine.getOpts().getConfirm(), is(false));
assertThat(sqlLine.getOpts().getConfirmPattern(),
is(BuiltInProperty.CONFIRM_PATTERN.defaultValue()));
String script = "CREATE TABLE dummy_test(pk int);\n"
+ "INSERT INTO dummy_test(pk) VALUES(1);\n"
+ "INSERT INTO dummy_test(pk) VALUES(2);\n"
+ "INSERT INTO dummy_test(pk) VALUES(3);\n"
+ "DELETE FROM dummy_test;\n"
+ "DROP TABLE dummy_test;\n";
checkScriptFile(script, true,
equalTo(SqlLine.Status.OK),
containsString(" "));
script = "!set confirm true\n" + script;
checkScriptFile(script, true,
equalTo(SqlLine.Status.OTHER),
containsString(sqlLine.loc("abort-action")));
} | #vulnerable code
@Test
public void testConfirmFlagEffects() {
new MockUp<sqlline.Commands>() {
@Mock
int getUserAnswer(String question, int... allowedAnswers) {
return 'n';
}
};
final SqlLine line = new SqlLine();
assertThat(line.getOpts().getConfirm(), is(false));
assertThat(line.getOpts().getConfirmPattern(), is("default"));
String script = "CREATE TABLE dummy_test(pk int);\n"
+ "INSERT INTO dummy_test(pk) VALUES(1);\n"
+ "INSERT INTO dummy_test(pk) VALUES(2);\n"
+ "INSERT INTO dummy_test(pk) VALUES(3);\n"
+ "DELETE FROM dummy_test;\n"
+ "DROP TABLE dummy_test;\n";
checkScriptFile(script, true,
equalTo(SqlLine.Status.OK),
containsString(" "));
script = "!set confirm true\n" + script;
checkScriptFile(script, true,
equalTo(SqlLine.Status.OTHER),
containsString(line.loc("abort-action")));
}
#location 26
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testOutputWithFailingColumnDisplaySize(
@Mocked final JDBCResultSetMetaData meta) {
try {
new Expectations() {
{
meta.getColumnCount();
result = 3;
meta.getColumnLabel(1);
result = "TABLE_CAT";
meta.getColumnLabel(2);
result = "TABLE_SCHEM";
meta.getColumnLabel(3);
result = "TABLE_NAME";
meta.getColumnDisplaySize(1);
result = new Exception("getColumnDisplaySize exception");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"!set incremental true",
"!set maxwidth 80",
"!set verbose true",
"!indexes");
assertThat(os.toString("UTF8"), not(containsString("Exception")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testOutputWithFailingColumnDisplaySize(
@Mocked final JDBCResultSetMetaData meta) {
try {
new Expectations() {
{
meta.getColumnCount();
result = 3;
meta.getColumnLabel(1);
result = "TABLE_CAT";
meta.getColumnLabel(2);
result = "TABLE_SCHEM";
meta.getColumnLabel(3);
result = "TABLE_NAME";
meta.getColumnDisplaySize(1);
result = new Exception("getColumnDisplaySize exception");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"!set incremental true",
"!set maxwidth 80",
"!set verbose true",
"!indexes");
assertThat(os.toString("UTF8"), not(containsString("Exception")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#location 29
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMaxHistoryFileRows() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n"
+ "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n"
+ "1536743107526:!history\n"
+ "1536743115431:SELECT \\n 2 \\n as \\n c2;\n"
+ "1536743115431:SELECT \\n '213' \\n as \\n c1;\n"
+ "1536743115431:!/ 8\n");
bw.flush();
bw.close();
SqlLine.Status status = begin(sqlLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
final int maxLines = 3;
sqlLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines);
os.reset();
sqlLine.runCommands(dc, "!history");
assertEquals(maxLines + 1,
os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length);
os.reset();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testMaxHistoryFileRows() {
final SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n"
+ "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n"
+ "1536743107526:!history\n"
+ "1536743115431:SELECT \\n 2 \\n as \\n c2;\n"
+ "1536743115431:SELECT \\n '213' \\n as \\n c1;\n"
+ "1536743115431:!/ 8\n");
bw.flush();
bw.close();
SqlLine.Status status = begin(beeLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
final int maxLines = 3;
beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines);
os.reset();
beeLine.runCommands(dc, "!history");
assertEquals(maxLines + 1,
os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length);
os.reset();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 32
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectWithDbPropertyAsParameter2() {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!set maxwidth 80");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
sqlLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
sqlLine.runCommands(dc, "select 1;");
String output = os.toString("UTF8");
final String expected = "Error:";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testConnectWithDbPropertyAsParameter2() {
SqlLine beeLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc, "!set maxwidth 80");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
beeLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
beeLine.runCommands(dc, "select 1;");
String output = os.toString("UTF8");
final String expected = "Error:";
assertThat(output, containsString(expected));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExceptionConfirmPattern() {
try {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
assertThat(sqlLine.getOpts().getConfirm(), is(false));
SqlLine.Status status =
begin(sqlLine, os, false, "-e",
"!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\"");
assertThat(status, equalTo(SqlLine.Status.OK));
assertThat(os.toString("UTF8"), containsString("invalid regex"));
os.reset();
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testExceptionConfirmPattern() {
try {
final SqlLine line = new SqlLine();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
assertThat(line.getOpts().getConfirm(), is(false));
SqlLine.Status status =
begin(line, os, false, "-e",
"!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\"");
assertThat(status, equalTo(SqlLine.Status.OK));
assertThat(os.toString("UTF8"), containsString("invalid regex"));
os.reset();
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void assertFileContains(File file, Matcher matcher)
throws IOException {
final BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), StandardCharsets.UTF_8.name()));
final StringWriter stringWriter = new StringWriter();
for (;;) {
final String line = br.readLine();
if (line == null) {
break;
}
stringWriter.write(line);
stringWriter.write("\n");
}
br.close();
assertThat(toLinux(stringWriter.toString()), matcher);
} | #vulnerable code
private void assertFileContains(File file, Matcher matcher)
throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(file));
final StringWriter stringWriter = new StringWriter();
for (;;) {
final String line = br.readLine();
if (line == null) {
break;
}
stringWriter.write(line);
stringWriter.write("\n");
}
br.close();
assertThat(toLinux(stringWriter.toString()), matcher);
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSave() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String testSqllinePropertiesFile = "test.sqlline.properties";
try {
SqlLine.Status status = begin(sqlLine, os, false,
"--propertiesFile=" + testSqllinePropertiesFile, "-e", "!save");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
assertThat(os.toString("UTF8"),
allOf(containsString("Saving preferences to"),
not(containsString("Saving to /dev/null not supported"))));
os.reset();
sqlLine.runCommands(dc, "!set");
assertThat(os.toString("UTF8"),
allOf(containsString("autoCommit"),
not(containsString("Unknown property:"))));
os.reset();
Files.delete(Paths.get(testSqllinePropertiesFile));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testSave() {
final SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
SqlLine.Status status = begin(beeLine, os, false,
"-e", "!save");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
assertThat(os.toString("UTF8"),
containsString("Saving preferences to"));
os.reset();
beeLine.runCommands(dc, "!set");
assertThat(os.toString("UTF8"),
allOf(containsString("autoCommit"),
not(containsString("Unknown property:"))));
os.reset();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMultilineScriptWithH2Comments() {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
final File tmpHistoryFile = createTempFile("queryToExecute", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
final String script = "\n"
+ "\n"
+ "!set incremental true\n"
+ "\n"
+ "\n"
+ "select * from information_schema.tables// ';\n"
+ "// \";"
+ ";\n"
+ "\n"
+ "\n";
bw.write(script);
bw.flush();
}
SqlLine.Status status =
begin(sqlLine, os, false,
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"--run=" + tmpHistoryFile.getAbsolutePath());
assertThat(status, equalTo(SqlLine.Status.OK));
String output = os.toString("UTF8");
final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |"
+ " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testMultilineScriptWithH2Comments() {
final SqlLine sqlLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
final File tmpHistoryFile = createTempFile("queryToExecute", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
final String script = "\n"
+ "\n"
+ "!set incremental true\n"
+ "\n"
+ "\n"
+ "select * from information_schema.tables// ';\n"
+ "// \";"
+ ";\n"
+ "\n"
+ "\n";
bw.write(script);
bw.flush();
}
SqlLine.Status status =
begin(sqlLine, os, false,
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"--run=" + tmpHistoryFile.getAbsolutePath());
assertThat(status, equalTo(SqlLine.Status.OK));
String output = os.toString("UTF8");
final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |"
+ " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#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 testConnectWithoutPassword() {
new MockUp<sqlline.Commands>() {
@Mock
String readPassword(String url) {
return "";
}
};
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
sqlLine.runCommands(dc, "!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username);
sqlLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testConnectWithoutPassword() {
new MockUp<sqlline.Commands>() {
@Mock
String readPassword(String url) {
return "";
}
};
SqlLine beeLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
beeLine.runCommands(dc, "!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username);
beeLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectWithDbPropertyAsParameter2() {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!set maxwidth 80");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
sqlLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
sqlLine.runCommands(dc, "select 1;");
String output = os.toString("UTF8");
final String expected = "Error:";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testConnectWithDbPropertyAsParameter2() {
SqlLine beeLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc, "!set maxwidth 80");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
beeLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
beeLine.runCommands(dc, "select 1;");
String output = os.toString("UTF8");
final String expected = "Error:";
assertThat(output, containsString(expected));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testCommandHandlerOnStartup() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String[] args = {
"-e", "!set maxwidth 80",
"-ch", "sqlline.extensions.HelloWorldCommandHandler"};
begin(sqlLine, os, false, args);
try {
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!test");
output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello test"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testCommandHandlerOnStartup() {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String[] args = {
"-e", "!set maxwidth 80",
"-ch", "sqlline.extensions.HelloWorldCommandHandler"};
begin(sqlLine, os, false, args);
try {
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!test");
output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello test"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNPE() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = getPrintStream(os);
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
try {
sqlLine.runCommands(new DispatchCallback(), "!typeinfo");
String output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
sqlLine.runCommands(new DispatchCallback(), "!nativesql");
output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testNPE() {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = getPrintStream(os);
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
try {
sqlLine.runCommands(new DispatchCallback(), "!typeinfo");
String output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
sqlLine.runCommands(new DispatchCallback(), "!nativesql");
output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExceptionConfirmPattern() {
try {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
assertThat(sqlLine.getOpts().getConfirm(), is(false));
SqlLine.Status status =
begin(sqlLine, os, false, "-e",
"!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\"");
assertThat(status, equalTo(SqlLine.Status.OK));
assertThat(os.toString("UTF8"), containsString("invalid regex"));
os.reset();
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testExceptionConfirmPattern() {
try {
final SqlLine line = new SqlLine();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
assertThat(line.getOpts().getConfirm(), is(false));
SqlLine.Status status =
begin(line, os, false, "-e",
"!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\"");
assertThat(status, equalTo(SqlLine.Status.OK));
assertThat(os.toString("UTF8"), containsString("invalid regex"));
os.reset();
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#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 testSave() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String testSqllinePropertiesFile = "test.sqlline.properties";
try {
SqlLine.Status status = begin(sqlLine, os, false,
"--propertiesFile=" + testSqllinePropertiesFile, "-e", "!save");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
assertThat(os.toString("UTF8"),
allOf(containsString("Saving preferences to"),
not(containsString("Saving to /dev/null not supported"))));
os.reset();
sqlLine.runCommands(dc, "!set");
assertThat(os.toString("UTF8"),
allOf(containsString("autoCommit"),
not(containsString("Unknown property:"))));
os.reset();
Files.delete(Paths.get(testSqllinePropertiesFile));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testSave() {
final SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
SqlLine.Status status = begin(beeLine, os, false,
"-e", "!save");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
assertThat(os.toString("UTF8"),
containsString("Saving preferences to"));
os.reset();
beeLine.runCommands(dc, "!set");
assertThat(os.toString("UTF8"),
allOf(containsString("autoCommit"),
not(containsString("Unknown property:"))));
os.reset();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExecutionWithNotSupportedMethods(
@Mocked final JDBCDatabaseMetaData meta) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// emulate apache hive behavior
meta.supportsTransactionIsolationLevel(4);
result = new SQLException("Method not supported");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback dc = new DispatchCallback();
sqlLine.initArgs(args, dc);
os.reset();
sqlLine.runCommands(dc,
"!set incremental true",
"values 1;");
final String output = os.toString("UTF8");
final String line0 = "+-------------+";
final String line1 = "| C1 |";
final String line2 = "+-------------+";
final String line3 = "| 1 |";
final String line4 = "+-------------+";
assertThat(output,
CoreMatchers.allOf(containsString(line0),
containsString(line1),
containsString(line2),
containsString(line3),
containsString(line4)));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testExecutionWithNotSupportedMethods(
@Mocked final JDBCDatabaseMetaData meta) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// emulate apache hive behavior
meta.supportsTransactionIsolationLevel(4);
result = new SQLException("Method not supported");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback dc = new DispatchCallback();
sqlLine.initArgs(args, dc);
os.reset();
sqlLine.runCommands(dc,
"!set incremental true",
"values 1;");
final String output = os.toString("UTF8");
final String line0 = "+-------------+";
final String line1 = "| C1 |";
final String line2 = "+-------------+";
final String line3 = "| 1 |";
final String line4 = "+-------------+";
assertThat(output,
CoreMatchers.allOf(containsString(line0),
containsString(line1),
containsString(line2),
containsString(line3),
containsString(line4)));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testPromptWithConnection() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
final SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"");
// custom prompt with data from connection
final SqlLineOpts opts = sqlLine.getOpts();
opts.set(BuiltInProperty.PROMPT, "%u@%n>");
opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c");
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("jdbc:h2:mem:@SA>"));
assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(),
is("//H20"));
sqlLine.getDatabaseConnection().close();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testPromptWithConnection() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine sqlLine = new SqlLine();
try {
final SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"");
// custom prompt with data from connection
final SqlLineOpts opts = sqlLine.getOpts();
opts.set(BuiltInProperty.PROMPT, "%u@%n>");
opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c");
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("jdbc:h2:mem:@SA>"));
assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(),
is("//H20"));
sqlLine.getDatabaseConnection().close();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testCommandHandler() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
try {
final String script = "!commandhandler"
+ " sqlline.extensions.HelloWorld2CommandHandler"
+ " sqlline.extensions.HelloWorldCommandHandler";
sqlLine.runCommands(new DispatchCallback(), script);
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD2"));
final String expected = "Could not add command handler "
+ "sqlline.extensions.HelloWorldCommandHandler as one of commands "
+ "[hello, test] is already present";
assertThat(output, containsString(expected));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello2"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testCommandHandler() {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
try {
final String script = "!commandhandler"
+ " sqlline.extensions.HelloWorld2CommandHandler"
+ " sqlline.extensions.HelloWorldCommandHandler";
sqlLine.runCommands(new DispatchCallback(), script);
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD2"));
final String expected = "Could not add command handler "
+ "sqlline.extensions.HelloWorldCommandHandler as one of commands "
+ "[hello, test] is already present";
assertThat(output, containsString(expected));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello2"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testInitArgsForUserNameAndPasswordWithSpaces() {
try {
final DatabaseConnection[] databaseConnection = new DatabaseConnection[1];
new MockUp<sqlline.DatabaseConnections>() {
@Mock
public void setConnection(DatabaseConnection connection) {
databaseConnection[0] = connection;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
String[] connectionArgs = new String[]{
"-u", ConnectionSpec.H2.url, "-n", "\"user'\\\" name\"",
"-p", "\"user \\\"'\\\"password\"",
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertEquals(ConnectionSpec.H2.url, databaseConnection[0].getUrl());
Properties infoProperties =
FieldReflection.getFieldValue(
databaseConnection[0].getClass().getDeclaredField("info"),
databaseConnection[0]);
assertNotNull(infoProperties);
assertEquals("user'\" name", infoProperties.getProperty("user"));
assertEquals("user \"'\"password",
infoProperties.getProperty("password"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testInitArgsForUserNameAndPasswordWithSpaces() {
try {
final SqlLine sqlLine = new SqlLine();
final DatabaseConnection[] databaseConnection = new DatabaseConnection[1];
new MockUp<sqlline.DatabaseConnections>() {
@Mock
public void setConnection(DatabaseConnection connection) {
databaseConnection[0] = connection;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
String[] connectionArgs = new String[]{
"-u", ConnectionSpec.H2.url, "-n", "\"user'\\\" name\"",
"-p", "\"user \\\"'\\\"password\"",
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertEquals(ConnectionSpec.H2.url, databaseConnection[0].getUrl());
Properties infoProperties =
FieldReflection.getFieldValue(
databaseConnection[0].getClass().getDeclaredField("info"),
databaseConnection[0]);
assertNotNull(infoProperties);
assertEquals("user'\" name", infoProperties.getProperty("user"));
assertEquals("user \"'\"password",
infoProperties.getProperty("password"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
#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 testMetadataForClassHierarchy() {
new MockUp<JDBCConnection>() {
@Mock
public DatabaseMetaData getMetaData() throws SQLException {
return new CustomDatabaseMetadata(
(JDBCConnection) sqlLine.getConnection());
}
};
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ ConnectionSpec.HSQLDB.url + " \""
+ ConnectionSpec.HSQLDB.username + "\" \""
+ ConnectionSpec.HSQLDB.password + "\"");
os.reset();
sqlLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
assertThat(output,
allOf(containsString("TABLE_CAT"),
not(containsString("No such method \"getTables\""))));
} catch (Exception e) {
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testMetadataForClassHierarchy() {
final SqlLine beeLine = new SqlLine();
new MockUp<JDBCConnection>() {
@Mock
public DatabaseMetaData getMetaData() throws SQLException {
return new CustomDatabaseMetadata(
(JDBCConnection) beeLine.getConnection());
}
};
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc, "!connect "
+ ConnectionSpec.HSQLDB.url + " \""
+ ConnectionSpec.HSQLDB.username + "\" \""
+ ConnectionSpec.HSQLDB.password + "\"");
os.reset();
beeLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
assertThat(output,
allOf(containsString("TABLE_CAT"),
not(containsString("No such method \"getTables\""))));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNPE() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = getPrintStream(os);
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
try {
sqlLine.runCommands(new DispatchCallback(), "!typeinfo");
String output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
sqlLine.runCommands(new DispatchCallback(), "!nativesql");
output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testNPE() {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = getPrintStream(os);
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
try {
sqlLine.runCommands(new DispatchCallback(), "!typeinfo");
String output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
sqlLine.runCommands(new DispatchCallback(), "!nativesql");
output = os.toString("UTF8");
assertThat(
output, not(containsString("java.lang.NullPointerException")));
assertThat(output, containsString("No current connection"));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testStartupArgsWithoutUrl() {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testStartupArgsWithoutUrl() {
try {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void manual(String line, DispatchCallback callback)
throws IOException {
InputStream in = SqlLine.class.getResourceAsStream("manual.txt");
if (in == null) {
callback.setToFailure();
sqlLine.error(sqlLine.loc("no-manual"));
return;
}
if (less(in)) {
callback.setToSuccess();
} else {
callback.setToFailure();
}
} | #vulnerable code
public void manual(String line, DispatchCallback callback)
throws IOException {
InputStream in = SqlLine.class.getResourceAsStream("manual.txt");
if (in == null) {
callback.setToFailure();
sqlLine.error(sqlLine.loc("no-manual"));
return;
}
// Workaround for windows because of
// https://github.com/jline/jline3/issues/304
if (System.getProperty("os.name")
.toLowerCase(Locale.ROOT).contains("windows")) {
sillyLess(in);
} else {
try {
org.jline.builtins.Commands.less(sqlLine.getLineReader().getTerminal(),
in, sqlLine.getOutputStream(), sqlLine.getErrorStream(),
null, new String[]{"-I", "--syntax=none"});
} catch (Exception e) {
callback.setToFailure();
sqlLine.error(e);
return;
}
}
callback.setToSuccess();
}
#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 testManual() {
final String expectedLine = "sqlline version";
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
new MockUp<Commands>() {
@Mock
void less(Terminal terminal, InputStream in, PrintStream out,
PrintStream err, Path currentDir, String[] argv) {
}
};
SqlLine.Status status =
begin(sqlLine, baos, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
sqlLine.runCommands(new DispatchCallback(), "!manual");
String output = baos.toString("UTF8");
assertThat(output, containsString(expectedLine));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testManual() {
final String expectedLine = "sqlline version";
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
new MockUp<Commands>() {
@Mock
void less(Terminal terminal, InputStream in, PrintStream out,
PrintStream err, Path currentDir, String[] argv) {
}
};
SqlLine beeLine = new SqlLine();
SqlLine.Status status =
begin(beeLine, baos, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
beeLine.runCommands(new DispatchCallback(), "!manual");
String output = baos.toString("UTF8");
assertThat(output, containsString(expectedLine));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testTimeFormat() {
// Use System.err as it is used in sqlline.SqlLineOpts#set
final PrintStream originalErr = System.err;
try {
final ByteArrayOutputStream errBaos = new ByteArrayOutputStream();
System.setErr(
new PrintStream(errBaos, false, StandardCharsets.UTF_8.name()));
// successful patterns
final String okTimeFormat = "!set timeFormat HH:mm:ss\n";
final String defaultTimeFormat = "!set timeFormat default\n";
final String okDateFormat = "!set dateFormat YYYY-MM-dd\n";
final String defaultDateFormat = "!set dateFormat default\n";
final String okTimestampFormat = "!set timestampFormat default\n";
final String defaultTimestampFormat = "!set timestampFormat default\n";
// successful cases
sqlLine.getOpts().setPropertiesFile(DEV_NULL);
sqlLine.runCommands(new DispatchCallback(), okTimeFormat);
checkScriptFile(okTimeFormat, false, equalTo(SqlLine.Status.OK),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
checkScriptFile(defaultTimeFormat, false, equalTo(SqlLine.Status.OK),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
checkScriptFile(okDateFormat, false, equalTo(SqlLine.Status.OK),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
checkScriptFile(defaultDateFormat, false, equalTo(SqlLine.Status.OK),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
checkScriptFile(okTimestampFormat, false, equalTo(SqlLine.Status.OK),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
checkScriptFile(defaultTimestampFormat, false, equalTo(SqlLine.Status.OK),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
// failed patterns
final String wrongTimeFormat = "!set timeFormat qwerty\n";
final String wrongDateFormat = "!set dateFormat ASD\n";
final String wrongTimestampFormat =
"!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n";
// failed cases
checkScriptFile(wrongTimeFormat, true, equalTo(SqlLine.Status.OTHER),
allOf(containsString("Illegal pattern character 'q'"),
containsString("Exception")));
checkScriptFile(wrongDateFormat, true, equalTo(SqlLine.Status.OTHER),
allOf(containsString("Illegal pattern character 'A'"),
containsString("Exception")));
checkScriptFile(wrongTimestampFormat, true, equalTo(SqlLine.Status.OTHER),
allOf(containsString("Illegal pattern character 'T'"),
containsString("Exception")));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
} finally {
// Set error stream back
System.setErr(originalErr);
}
} | #vulnerable code
@Test
public void testTimeFormat() {
// Use System.err as it is used in sqlline.SqlLineOpts#set
final PrintStream originalErr = System.err;
try {
final ByteArrayOutputStream errBaos = new ByteArrayOutputStream();
System.setErr(
new PrintStream(errBaos, false, StandardCharsets.UTF_8.name()));
// successful patterns
final String okTimeFormat = "!set timeFormat HH:mm:ss\n";
final String defaultTimeFormat = "!set timeFormat default\n";
final String okDateFormat = "!set dateFormat YYYY-MM-dd\n";
final String defaultDateFormat = "!set dateFormat default\n";
final String okTimestampFormat = "!set timestampFormat default\n";
final String defaultTimestampFormat = "!set timestampFormat default\n";
// successful cases
final SqlLine sqlLine = new SqlLine();
sqlLine.runCommands(new DispatchCallback(), okTimeFormat);
assertThat(errBaos.toString("UTF8"),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat);
assertThat(errBaos.toString("UTF8"),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
sqlLine.runCommands(new DispatchCallback(), okDateFormat);
assertThat(errBaos.toString("UTF8"),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
sqlLine.runCommands(new DispatchCallback(), defaultDateFormat);
assertThat(errBaos.toString("UTF8"),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
sqlLine.runCommands(new DispatchCallback(), okTimestampFormat);
assertThat(errBaos.toString("UTF8"),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat);
assertThat(errBaos.toString("UTF8"),
not(
anyOf(containsString("Error setting configuration"),
containsString("Exception"))));
// failed patterns
final String wrongTimeFormat = "!set timeFormat qwerty\n";
final String wrongDateFormat = "!set dateFormat ASD\n";
final String wrongTimestampFormat =
"!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n";
// failed cases
sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat);
assertThat(errBaos.toString("UTF8"),
containsString("Illegal pattern character 'q'"));
sqlLine.runCommands(new DispatchCallback(), wrongDateFormat);
assertThat(errBaos.toString("UTF8"),
containsString("Illegal pattern character 'A'"));
sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat);
assertThat(errBaos.toString("UTF8"),
containsString("Illegal pattern character 'T'"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
} finally {
// Set error stream back
System.setErr(originalErr);
}
}
#location 64
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectWithDbProperty() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
try {
sqlLine.runCommands(dc, "!set maxwidth 80");
// fail attempt
String fakeNonEmptyPassword = "nonEmptyPasswd";
sqlLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE\" "
+ ConnectionSpec.H2.username
+ " \"" + fakeNonEmptyPassword + "\"");
String output = os.toString("UTF8");
final String expected0 = "Error:";
assertThat(output, containsString(expected0));
os.reset();
// success attempt
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
sqlLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" "
+ ConnectionSpec.H2.username + " \""
+ StringUtils.convertBytesToHex(bytes)
+ "\"");
sqlLine.runCommands(dc, "!set incremental true");
sqlLine.runCommands(dc, "!tables");
output = os.toString("UTF8");
final String expected1 = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected1));
sqlLine.runCommands(dc, "select 5;");
output = os.toString("UTF8");
final String expected2 = "Error:";
assertThat(output, containsString(expected2));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!quit");
output = os.toString("UTF8");
assertThat(output,
allOf(not(containsString("Error:")), containsString("!quit")));
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testConnectWithDbProperty() {
SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
try {
beeLine.runCommands(dc, "!set maxwidth 80");
// fail attempt
String fakeNonEmptyPassword = "nonEmptyPasswd";
beeLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE\" "
+ ConnectionSpec.H2.username
+ " \"" + fakeNonEmptyPassword + "\"");
String output = os.toString("UTF8");
final String expected0 = "Error:";
assertThat(output, containsString(expected0));
os.reset();
// success attempt
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
beeLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" "
+ ConnectionSpec.H2.username + " \""
+ StringUtils.convertBytesToHex(bytes)
+ "\"");
beeLine.runCommands(dc, "!set incremental true");
beeLine.runCommands(dc, "!tables");
output = os.toString("UTF8");
final String expected1 = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected1));
beeLine.runCommands(dc, "select 5;");
output = os.toString("UTF8");
final String expected2 = "Error:";
assertThat(output, containsString(expected2));
os.reset();
beeLine.runCommands(new DispatchCallback(), "!quit");
output = os.toString("UTF8");
assertThat(output,
allOf(not(containsString("Error:")), containsString("!quit")));
assertTrue(beeLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testStartupArgsWithoutUrl() {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testStartupArgsWithoutUrl() {
try {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testInitArgsForUserNameAndPasswordWithSpaces() {
try {
final DatabaseConnection[] databaseConnection = new DatabaseConnection[1];
new MockUp<sqlline.DatabaseConnections>() {
@Mock
public void setConnection(DatabaseConnection connection) {
databaseConnection[0] = connection;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
String[] connectionArgs = new String[]{
"-u", ConnectionSpec.H2.url, "-n", "\"user'\\\" name\"",
"-p", "\"user \\\"'\\\"password\"",
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertEquals(ConnectionSpec.H2.url, databaseConnection[0].getUrl());
Properties infoProperties =
FieldReflection.getFieldValue(
databaseConnection[0].getClass().getDeclaredField("info"),
databaseConnection[0]);
assertNotNull(infoProperties);
assertEquals("user'\" name", infoProperties.getProperty("user"));
assertEquals("user \"'\"password",
infoProperties.getProperty("password"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testInitArgsForUserNameAndPasswordWithSpaces() {
try {
final SqlLine sqlLine = new SqlLine();
final DatabaseConnection[] databaseConnection = new DatabaseConnection[1];
new MockUp<sqlline.DatabaseConnections>() {
@Mock
public void setConnection(DatabaseConnection connection) {
databaseConnection[0] = connection;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
String[] connectionArgs = new String[]{
"-u", ConnectionSpec.H2.url, "-n", "\"user'\\\" name\"",
"-p", "\"user \\\"'\\\"password\"",
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertEquals(ConnectionSpec.H2.url, databaseConnection[0].getUrl());
Properties infoProperties =
FieldReflection.getFieldValue(
databaseConnection[0].getClass().getDeclaredField("info"),
databaseConnection[0]);
assertNotNull(infoProperties);
assertEquals("user'\" name", infoProperties.getProperty("user"));
assertEquals("user \"'\"password",
infoProperties.getProperty("password"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
#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 testExecutionWithNotSupportedMethods(
@Mocked final JDBCDatabaseMetaData meta) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// emulate apache hive behavior
meta.supportsTransactionIsolationLevel(4);
result = new SQLException("Method not supported");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback dc = new DispatchCallback();
sqlLine.initArgs(args, dc);
os.reset();
sqlLine.runCommands(dc,
"!set incremental true",
"values 1;");
final String output = os.toString("UTF8");
final String line0 = "+-------------+";
final String line1 = "| C1 |";
final String line2 = "+-------------+";
final String line3 = "| 1 |";
final String line4 = "+-------------+";
assertThat(output,
CoreMatchers.allOf(containsString(line0),
containsString(line1),
containsString(line2),
containsString(line3),
containsString(line4)));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testExecutionWithNotSupportedMethods(
@Mocked final JDBCDatabaseMetaData meta) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// emulate apache hive behavior
meta.supportsTransactionIsolationLevel(4);
result = new SQLException("Method not supported");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback dc = new DispatchCallback();
sqlLine.initArgs(args, dc);
os.reset();
sqlLine.runCommands(dc,
"!set incremental true",
"values 1;");
final String output = os.toString("UTF8");
final String line0 = "+-------------+";
final String line1 = "| C1 |";
final String line2 = "+-------------+";
final String line3 = "| 1 |";
final String line4 = "+-------------+";
assertThat(output,
CoreMatchers.allOf(containsString(line0),
containsString(line1),
containsString(line2),
containsString(line3),
containsString(line4)));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 38
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testCustomPromptHandler() {
sqlLine.runCommands(new DispatchCallback(),
"!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"",
"!prompthandler sqlline.extensions.CustomPromptHandler");
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("my_app (PUBLIC)>"));
sqlLine.runCommands(new DispatchCallback(), "!prompthandler default");
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("0: jdbc:h2:mem:> "));
sqlLine.getDatabaseConnection().close();
} | #vulnerable code
@Test
public void testCustomPromptHandler() {
SqlLine sqlLine = new SqlLine();
sqlLine.runCommands(new DispatchCallback(),
"!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"",
"!prompthandler sqlline.extensions.CustomPromptHandler");
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("my_app (PUBLIC)>"));
sqlLine.runCommands(new DispatchCallback(), "!prompthandler default");
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("0: jdbc:h2:mem:> "));
sqlLine.getDatabaseConnection().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 testOutputWithFailingColumnDisplaySize(
@Mocked final JDBCResultSetMetaData meta) {
try {
new Expectations() {
{
meta.getColumnCount();
result = 3;
meta.getColumnLabel(1);
result = "TABLE_CAT";
meta.getColumnLabel(2);
result = "TABLE_SCHEM";
meta.getColumnLabel(3);
result = "TABLE_NAME";
meta.getColumnDisplaySize(1);
result = new Exception("getColumnDisplaySize exception");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"!set incremental true",
"!set maxwidth 80",
"!set verbose true",
"!indexes");
assertThat(os.toString("UTF8"), not(containsString("Exception")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testOutputWithFailingColumnDisplaySize(
@Mocked final JDBCResultSetMetaData meta) {
try {
new Expectations() {
{
meta.getColumnCount();
result = 3;
meta.getColumnLabel(1);
result = "TABLE_CAT";
meta.getColumnLabel(2);
result = "TABLE_SCHEM";
meta.getColumnLabel(3);
result = "TABLE_NAME";
meta.getColumnDisplaySize(1);
result = new Exception("getColumnDisplaySize exception");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"!set incremental true",
"!set maxwidth 80",
"!set verbose true",
"!indexes");
assertThat(os.toString("UTF8"), not(containsString("Exception")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#location 28
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testStartupArgsWithoutUrl() {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testStartupArgsWithoutUrl() {
try {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url")));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#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 testPromptWithNickname() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
final SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"");
// custom prompt with data from connection
final SqlLineOpts opts = sqlLine.getOpts();
sqlLine.getDatabaseConnection().setNickname("nickname");
opts.set(BuiltInProperty.PROMPT, "%u@%n>");
opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c");
// if nickname is specified for the connection
// it has more priority than prompt.
// Right prompt does not care about nickname
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("0: nickname> "));
assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(),
is("//H20"));
sqlLine.getDatabaseConnection().close();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testPromptWithNickname() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine sqlLine = new SqlLine();
try {
final SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ SqlLineArgsTest.ConnectionSpec.H2.url + " "
+ SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"");
// custom prompt with data from connection
final SqlLineOpts opts = sqlLine.getOpts();
sqlLine.getDatabaseConnection().setNickname("nickname");
opts.set(BuiltInProperty.PROMPT, "%u@%n>");
opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c");
// if nickname is specified for the connection
// it has more priority than prompt.
// Right prompt does not care about nickname
assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(),
is("0: nickname> "));
assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(),
is("//H20"));
sqlLine.getDatabaseConnection().close();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 52
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExecutionWithNotSupportedMethods(
@Mocked final JDBCDatabaseMetaData meta) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// emulate apache hive behavior
meta.supportsTransactionIsolationLevel(4);
result = new SQLException("Method not supported");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback dc = new DispatchCallback();
sqlLine.initArgs(args, dc);
os.reset();
sqlLine.runCommands(dc,
"!set incremental true",
"values 1;");
final String output = os.toString("UTF8");
final String line0 = "+-------------+";
final String line1 = "| C1 |";
final String line2 = "+-------------+";
final String line3 = "| 1 |";
final String line4 = "+-------------+";
assertThat(output,
CoreMatchers.allOf(containsString(line0),
containsString(line1),
containsString(line2),
containsString(line3),
containsString(line4)));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testExecutionWithNotSupportedMethods(
@Mocked final JDBCDatabaseMetaData meta) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// emulate apache hive behavior
meta.supportsTransactionIsolationLevel(4);
result = new SQLException("Method not supported");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback dc = new DispatchCallback();
sqlLine.initArgs(args, dc);
os.reset();
sqlLine.runCommands(dc,
"!set incremental true",
"values 1;");
final String output = os.toString("UTF8");
final String line0 = "+-------------+";
final String line1 = "| C1 |";
final String line2 = "+-------------+";
final String line3 = "| 1 |";
final String line4 = "+-------------+";
assertThat(output,
CoreMatchers.allOf(containsString(line0),
containsString(line1),
containsString(line2),
containsString(line3),
containsString(line4)));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMetadataForClassHierarchy() {
new MockUp<JDBCConnection>() {
@Mock
public DatabaseMetaData getMetaData() throws SQLException {
return new CustomDatabaseMetadata(
(JDBCConnection) sqlLine.getConnection());
}
};
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc, "!connect "
+ ConnectionSpec.HSQLDB.url + " \""
+ ConnectionSpec.HSQLDB.username + "\" \""
+ ConnectionSpec.HSQLDB.password + "\"");
os.reset();
sqlLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
assertThat(output,
allOf(containsString("TABLE_CAT"),
not(containsString("No such method \"getTables\""))));
} catch (Exception e) {
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testMetadataForClassHierarchy() {
final SqlLine beeLine = new SqlLine();
new MockUp<JDBCConnection>() {
@Mock
public DatabaseMetaData getMetaData() throws SQLException {
return new CustomDatabaseMetadata(
(JDBCConnection) beeLine.getConnection());
}
};
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc, "!connect "
+ ConnectionSpec.HSQLDB.url + " \""
+ ConnectionSpec.HSQLDB.username + "\" \""
+ ConnectionSpec.HSQLDB.password + "\"");
os.reset();
beeLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
assertThat(output,
allOf(containsString("TABLE_CAT"),
not(containsString("No such method \"getTables\""))));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConfirmPattern() {
assertThat(sqlLine.getOpts().getConfirm(), is(false));
final ByteArrayOutputStream os = new ByteArrayOutputStream();
begin(sqlLine, os, false, "-e",
"!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\"");
assertThat(sqlLine.getOpts().getConfirmPattern(),
is("^(?i:(TRUNCATE|ALTER))"));
begin(sqlLine, os, false, "-e", "!set confirmPattern default");
assertThat(sqlLine.getOpts().getConfirmPattern(),
is(sqlLine.loc("default-confirm-pattern")));
} | #vulnerable code
@Test
public void testConfirmPattern() {
final SqlLine line = new SqlLine();
assertThat(line.getOpts().getConfirm(), is(false));
final ByteArrayOutputStream os = new ByteArrayOutputStream();
begin(line, os, false, "-e",
"!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\"");
assertThat(line.getOpts().getConfirmPattern(),
is("^(?i:(TRUNCATE|ALTER))"));
begin(line, os, false, "-e", "!set confirmPattern default");
assertThat(line.getOpts().getConfirmPattern(),
is(line.loc("default-confirm-pattern")));
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testRerun() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:!/ 4\n"
+ "1536743104551:!/ 5\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:!/ 7\n"
+ "1536743107526:!history\n"
+ "1536743115431:!/ 3\n"
+ "1536743115431:!/ 8\n");
bw.flush();
SqlLine.Status status = begin(sqlLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc,
"!set incremental true",
"!set maxcolumnwidth 30",
"!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ "\"\"");
os.reset();
sqlLine.runCommands(dc, "!/ 1");
String output = os.toString("UTF8");
final String expected0 = "+----------------------------+";
final String expected1 = "| C1 |";
final String expected2 = "1 row selected";
assertThat(output,
allOf(containsString(expected0),
containsString(expected1),
containsString(expected2)));
os.reset();
sqlLine.runCommands(dc, "!/ 4");
output = os.toString("UTF8");
String expectedLine3 = "Cycled rerun of commands from history [2, 4]";
assertThat(output, containsString(expectedLine3));
os.reset();
sqlLine.runCommands(dc, "!/ 3");
output = os.toString("UTF8");
String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]";
assertThat(output, containsString(expectedLine4));
os.reset();
sqlLine.runCommands(dc, "!/ 8");
output = os.toString("UTF8");
String expectedLine5 = "Cycled rerun of commands from history [8]";
assertThat(output, containsString(expectedLine5));
os.reset();
sqlLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE);
output = os.toString("UTF8");
String expectedLine6 =
"Usage: rerun <offset>, available range of offset is -7..8";
assertThat(output, containsString(expectedLine6));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testRerun() {
final SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:!/ 4\n"
+ "1536743104551:!/ 5\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:!/ 7\n"
+ "1536743107526:!history\n"
+ "1536743115431:!/ 3\n"
+ "1536743115431:!/ 8\n");
bw.flush();
SqlLine.Status status = begin(beeLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc,
"!set incremental true",
"!set maxcolumnwidth 30",
"!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ "\"\"");
os.reset();
beeLine.runCommands(dc, "!/ 1");
String output = os.toString("UTF8");
final String expected0 = "+----------------------------+";
final String expected1 = "| C1 |";
final String expected2 = "1 row selected";
assertThat(output,
allOf(containsString(expected0),
containsString(expected1),
containsString(expected2)));
os.reset();
beeLine.runCommands(dc, "!/ 4");
output = os.toString("UTF8");
String expectedLine3 = "Cycled rerun of commands from history [2, 4]";
assertThat(output, containsString(expectedLine3));
os.reset();
beeLine.runCommands(dc, "!/ 3");
output = os.toString("UTF8");
String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]";
assertThat(output, containsString(expectedLine4));
os.reset();
beeLine.runCommands(dc, "!/ 8");
output = os.toString("UTF8");
String expectedLine5 = "Cycled rerun of commands from history [8]";
assertThat(output, containsString(expectedLine5));
os.reset();
beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE);
output = os.toString("UTF8");
String expectedLine6 =
"Usage: rerun <offset>, available range of offset is -7..8";
assertThat(output, containsString(expectedLine6));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 70
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConfirmFlag() {
try {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
assertThat(sqlLine.getOpts().getConfirm(), is(false));
begin(sqlLine, os, false, "-e", "!set confirm true");
assertThat(sqlLine.getOpts().getConfirm(), is(true));
begin(sqlLine, os, false, "-e", "!set confirm false");
assertThat(sqlLine.getOpts().getConfirm(), is(false));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testConfirmFlag() {
try {
final SqlLine line = new SqlLine();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
assertThat(line.getOpts().getConfirm(), is(false));
begin(line, os, false, "-e", "!set confirm true");
assertThat(line.getOpts().getConfirm(), is(true));
begin(line, os, false, "-e", "!set confirm false");
assertThat(line.getOpts().getConfirm(), is(false));
} catch (Throwable e) {
// fail
throw new RuntimeException(e);
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testRerun() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:!/ 4\n"
+ "1536743104551:!/ 5\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:!/ 7\n"
+ "1536743107526:!history\n"
+ "1536743115431:!/ 3\n"
+ "1536743115431:!/ 8\n");
bw.flush();
SqlLine.Status status = begin(sqlLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc,
"!set incremental true",
"!set maxcolumnwidth 30",
"!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ "\"\"");
os.reset();
sqlLine.runCommands(dc, "!/ 1");
String output = os.toString("UTF8");
final String expected0 = "+----------------------------+";
final String expected1 = "| C1 |";
final String expected2 = "1 row selected";
assertThat(output,
allOf(containsString(expected0),
containsString(expected1),
containsString(expected2)));
os.reset();
sqlLine.runCommands(dc, "!/ 4");
output = os.toString("UTF8");
String expectedLine3 = "Cycled rerun of commands from history [2, 4]";
assertThat(output, containsString(expectedLine3));
os.reset();
sqlLine.runCommands(dc, "!/ 3");
output = os.toString("UTF8");
String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]";
assertThat(output, containsString(expectedLine4));
os.reset();
sqlLine.runCommands(dc, "!/ 8");
output = os.toString("UTF8");
String expectedLine5 = "Cycled rerun of commands from history [8]";
assertThat(output, containsString(expectedLine5));
os.reset();
sqlLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE);
output = os.toString("UTF8");
String expectedLine6 =
"Usage: rerun <offset>, available range of offset is -7..8";
assertThat(output, containsString(expectedLine6));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testRerun() {
final SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final File tmpHistoryFile = createTempFile("tmpHistory", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n"
+ "1536743104551:!/ 4\n"
+ "1536743104551:!/ 5\n"
+ "1536743104551:!/ 2\n"
+ "1536743104551:!/ 7\n"
+ "1536743107526:!history\n"
+ "1536743115431:!/ 3\n"
+ "1536743115431:!/ 8\n");
bw.flush();
SqlLine.Status status = begin(beeLine, os, true,
"--historyfile=" + tmpHistoryFile.getAbsolutePath(),
"-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc,
"!set incremental true",
"!set maxcolumnwidth 30",
"!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ "\"\"");
os.reset();
beeLine.runCommands(dc, "!/ 1");
String output = os.toString("UTF8");
final String expected0 = "+----------------------------+";
final String expected1 = "| C1 |";
final String expected2 = "1 row selected";
assertThat(output,
allOf(containsString(expected0),
containsString(expected1),
containsString(expected2)));
os.reset();
beeLine.runCommands(dc, "!/ 4");
output = os.toString("UTF8");
String expectedLine3 = "Cycled rerun of commands from history [2, 4]";
assertThat(output, containsString(expectedLine3));
os.reset();
beeLine.runCommands(dc, "!/ 3");
output = os.toString("UTF8");
String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]";
assertThat(output, containsString(expectedLine4));
os.reset();
beeLine.runCommands(dc, "!/ 8");
output = os.toString("UTF8");
String expectedLine5 = "Cycled rerun of commands from history [8]";
assertThat(output, containsString(expectedLine5));
os.reset();
beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE);
output = os.toString("UTF8");
String expectedLine6 =
"Usage: rerun <offset>, available range of offset is -7..8";
assertThat(output, containsString(expectedLine6));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 71
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectWithoutPassword() {
new MockUp<sqlline.Commands>() {
@Mock
String readPassword(String url) {
return "";
}
};
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
sqlLine.runCommands(dc, "!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username);
sqlLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testConnectWithoutPassword() {
new MockUp<sqlline.Commands>() {
@Mock
String readPassword(String url) {
return "";
}
};
SqlLine beeLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
beeLine.runCommands(dc, "!connect "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username);
beeLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 27
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectWithDbProperty() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
try {
sqlLine.runCommands(dc, "!set maxwidth 80");
// fail attempt
String fakeNonEmptyPassword = "nonEmptyPasswd";
sqlLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE\" "
+ ConnectionSpec.H2.username
+ " \"" + fakeNonEmptyPassword + "\"");
String output = os.toString("UTF8");
final String expected0 = "Error:";
assertThat(output, containsString(expected0));
os.reset();
// success attempt
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
sqlLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" "
+ ConnectionSpec.H2.username + " \""
+ StringUtils.convertBytesToHex(bytes)
+ "\"");
sqlLine.runCommands(dc, "!set incremental true");
sqlLine.runCommands(dc, "!tables");
output = os.toString("UTF8");
final String expected1 = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected1));
sqlLine.runCommands(dc, "select 5;");
output = os.toString("UTF8");
final String expected2 = "Error:";
assertThat(output, containsString(expected2));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!quit");
output = os.toString("UTF8");
assertThat(output,
allOf(not(containsString("Error:")), containsString("!quit")));
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testConnectWithDbProperty() {
SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
try {
beeLine.runCommands(dc, "!set maxwidth 80");
// fail attempt
String fakeNonEmptyPassword = "nonEmptyPasswd";
beeLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE\" "
+ ConnectionSpec.H2.username
+ " \"" + fakeNonEmptyPassword + "\"");
String output = os.toString("UTF8");
final String expected0 = "Error:";
assertThat(output, containsString(expected0));
os.reset();
// success attempt
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
beeLine.runCommands(dc, "!connect \""
+ ConnectionSpec.H2.url
+ " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" "
+ ConnectionSpec.H2.username + " \""
+ StringUtils.convertBytesToHex(bytes)
+ "\"");
beeLine.runCommands(dc, "!set incremental true");
beeLine.runCommands(dc, "!tables");
output = os.toString("UTF8");
final String expected1 = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected1));
beeLine.runCommands(dc, "select 5;");
output = os.toString("UTF8");
final String expected2 = "Error:";
assertThat(output, containsString(expected2));
os.reset();
beeLine.runCommands(new DispatchCallback(), "!quit");
output = os.toString("UTF8");
assertThat(output,
allOf(not(containsString("Error:")), containsString("!quit")));
assertTrue(beeLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 51
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testInitArgsForSuccessConnection() {
try {
final String[] nicknames = new String[1];
new MockUp<sqlline.DatabaseConnection>() {
@Mock
void setNickname(String nickname) {
nicknames[0] = nickname;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String filename = "file' with spaces";
String[] connectionArgs = {
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"-p", ConnectionSpec.H2.password,
"-nn", "nickname with spaces",
"-log", "target" + File.separator + filename,
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertThat("file with spaces",
Files.exists(Paths.get("target", filename)));
assertEquals("nickname with spaces", nicknames[0]);
} catch (Throwable t) {
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testInitArgsForSuccessConnection() {
try {
final String[] nicknames = new String[1];
new MockUp<sqlline.DatabaseConnection>() {
@Mock
void setNickname(String nickname) {
nicknames[0] = nickname;
}
};
final SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String filename = "file' with spaces";
String[] connectionArgs = new String[] {
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"-p", ConnectionSpec.H2.password,
"-nn", "nickname with spaces",
"-log", "target/" + filename,
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertThat("file with spaces",
Files.exists(Paths.get("target", filename)));
assertEquals("nickname with spaces", nicknames[0]);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 26
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testCommandHandlerOnStartup() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String[] args = {
"-e", "!set maxwidth 80",
"-ch", "sqlline.extensions.HelloWorldCommandHandler"};
begin(sqlLine, os, false, args);
try {
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!test");
output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello test"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | #vulnerable code
@Test
public void testCommandHandlerOnStartup() {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String[] args = {
"-e", "!set maxwidth 80",
"-ch", "sqlline.extensions.HelloWorldCommandHandler"};
begin(sqlLine, os, false, args);
try {
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!test");
output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello test"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
SqlLine()
{
// registerKnownDrivers ();
sqlLineCommandCompleter = new SQLLineCommandCompleter();
// attempt to dynamically load signal handler
try {
Class handlerClass = Class.forName("sqlline.SunSignalHandler");
signalHandler = (SqlLineSignalHandler) handlerClass.newInstance();
} catch (Throwable t) {
handleException(t);
}
} | #vulnerable code
void begin(String [] args, InputStream inputStream)
throws IOException
{
try {
// load the options first, so we can override on the command line
command.load(null, null);
opts.load();
} catch (Exception e) {
handleException(e);
}
ConsoleReader reader = getConsoleReader(inputStream);
if (!(initArgs(args))) {
usage();
return;
}
try {
info(getApplicationTitle());
} catch (Exception e) {
handleException(e);
}
// basic setup done. From this point on, honor opts value for showing exception
initComplete = true;
while (!exit) {
DispatchCallback callback = new DispatchCallback();
try {
callback.setStatus(DispatchCallback.Status.RUNNING);
dispatch(reader.readLine(getPrompt()), callback);
} catch (EOFException eof) {
// CTRL-D
command.quit(null, callback);
} catch (UserInterruptException ioe) {
// CTRL-C
try {
callback.forceKillSqlQuery();
output(loc("command-canceled"));
} catch (SQLException sqle) {
handleException(sqle);
}
} catch (Throwable t) {
handleException(t);
}
}
// ### NOTE jvs 10-Aug-2004: Clean up any outstanding
// connections automatically.
// nothing is done with the callback beyond
command.closeall(null, new DispatchCallback());
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSetNonIntValuesToIntProperties() {
final String headerIntervalScript = "!set headerinterval abc\n";
checkScriptFile(headerIntervalScript, true, equalTo(SqlLine.Status.OK),
containsString(sqlLine.loc("not-a-number", "headerinterval", "abc")));
final String rowLimitScript = "!set rowlimit xxx\n";
checkScriptFile(rowLimitScript, true, equalTo(SqlLine.Status.OK),
containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx")));
} | #vulnerable code
@Test
public void testSetNonIntValuesToIntProperties() {
SqlLine sqlLine = new SqlLine();
final String headerIntervalScript = "!set headerinterval abc\n";
checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK),
containsString(sqlLine.loc("not-a-number", "headerinterval", "abc")));
final String rowLimitScript = "!set rowlimit xxx\n";
checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK),
containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx")));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectWithDbPropertyAsParameter() {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
sqlLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
sqlLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | #vulnerable code
@Test
public void testConnectWithDbPropertyAsParameter() {
SqlLine beeLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
beeLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
beeLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void generatedBeanWithFluentSetterShouldBeCorrectlyPopulated() {
// when
ChainedSetterBean chainedSetterBean = easyRandom.nextObject(ChainedSetterBean.class);
// then
assertThat(chainedSetterBean.getName()).isNotEmpty();
} | #vulnerable code
@Test
void generatedBeanWithFluentSetterShouldBeCorrectlyPopulated() {
// when
FluentSetterBean fluentSetterBean = easyRandom.nextObject(FluentSetterBean.class);
// then
assertThat(fluentSetterBean.getName()).isNotEmpty();
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Populator getPopulatorFromSpringContext(String contextFileName) {
try (AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextFileName)) {
return applicationContext.getBean(Populator.class);
}
} | #vulnerable code
private Populator getPopulatorFromSpringContext(String contextFileName) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextFileName);
return applicationContext.getBean(Populator.class);
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Randomizer<?> getRandomizer(Field field) {
Class<?> fieldType = field.getType();
Pattern patternAnnotation = io.github.benas.randombeans.util.ReflectionUtils
.getAnnotation(field, Pattern.class);
final String regex = patternAnnotation.regexp();
if (fieldType.equals(String.class)) {
return new RegularExpressionRandomizer(regex, random.nextLong());
}
return null;
} | #vulnerable code
public Randomizer<?> getRandomizer(Field field) {
Class<?> fieldType = field.getType();
Pattern patternAnnotation = getAnnotation(field, Pattern.class);
final String regex = patternAnnotation.regexp();
if (fieldType.equals(String.class)) {
return new RegularExpressionRandomizer(regex, random.nextLong());
}
return null;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public <T> List<T> populateBeans(final Class<T> type, final String... excludeFieldsName) {
int size = new RandomDataGenerator().nextInt(1, Short.MAX_VALUE);
return populateBeans(type, size, excludeFieldsName);
} | #vulnerable code
@Override
public <T> List<T> populateBeans(final Class<T> type, final String... excludeFieldsName) {
byte size = (byte) Math.abs((Byte) DefaultRandomizer.getRandomValue(Byte.TYPE));
return populateBeans(type, size, excludeFieldsName);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ArrayPopulator(final EnhancedRandomImpl enhancedRandom) {
this.enhancedRandom = enhancedRandom;
} | #vulnerable code
Object getRandomPrimitiveArray(final Class<?> primitiveType) {
int size = abs(aNewByteRandomizer().getRandomValue());
// TODO A bounty will be offered to anybody that comes with a generic template method for that..
if (primitiveType.equals(Byte.TYPE)) {
byte[] result = new byte[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Byte.TYPE);
}
return result;
}
if (primitiveType.equals(Short.TYPE)) {
short[] result = new short[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Short.TYPE);
}
return result;
}
if (primitiveType.equals(Integer.TYPE)) {
int[] result = new int[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Integer.TYPE);
}
return result;
}
if (primitiveType.equals(Long.TYPE)) {
long[] result = new long[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Long.TYPE);
}
return result;
}
if (primitiveType.equals(Float.TYPE)) {
float[] result = new float[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Float.TYPE);
}
return result;
}
if (primitiveType.equals(Double.TYPE)) {
double[] result = new double[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Double.TYPE);
}
return result;
}
if (primitiveType.equals(Character.TYPE)) {
char[] result = new char[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Character.TYPE);
}
return result;
}
if (primitiveType.equals(Boolean.TYPE)) {
boolean[] result = new boolean[size];
for (int index = 0; index < size; index ++) {
result[index] = enhancedRandom.nextObject(Boolean.TYPE);
}
return result;
}
return null;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldGenerateTheSameValueForTheSameSeed() {
BigDecimal javaVersion = new BigDecimal(System.getProperty("java.specification.version"));
if (javaVersion.compareTo(new BigDecimal("11")) >= 0) {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("en", "CK"));
} else if (javaVersion.compareTo(new BigDecimal("9")) >= 0) {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("sw", "ke"));
} else {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("nl", "be"));
}
} | #vulnerable code
@Test
public void shouldGenerateTheSameValueForTheSameSeed() {
String javaVersion = System.getProperty("java.specification.version");
if (javaVersion.startsWith("9") || javaVersion.startsWith("10")) {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("sw", "ke"));
} else if (javaVersion.startsWith("12")) {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("en", "CK"));
} else {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("nl", "be"));
}
}
#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 shouldGenerateTheSameValueForTheSameSeed() {
String javaVersion = System.getProperty("java.specification.version");
if (javaVersion.startsWith("9") || javaVersion.startsWith("10")) {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("sw", "ke"));
} else {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("nl", "be"));
}
} | #vulnerable code
@Test
public void shouldGenerateTheSameValueForTheSameSeed() {
if (System.getProperty("java.specification.version").startsWith("9")) {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("sw", "ke"));
} else {
assertThat(aNewLocaleRandomizer(SEED).getRandomValue()).isEqualTo(new Locale("nl", "be"));
}
}
#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 testGetDeclaredFields() throws Exception {
BigDecimal javaVersion = new BigDecimal(System.getProperty("java.specification.version"));
if (javaVersion.compareTo(new BigDecimal("9")) >= 0) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22);
} else {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20);
}
} | #vulnerable code
@Test
public void testGetDeclaredFields() throws Exception {
String javaVersion = System.getProperty("java.specification.version");
if (javaVersion.startsWith("9") || javaVersion.startsWith("10")) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22);
} else {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Randomizer<?> getRandomizer(Field field) {
Class<?> fieldType = field.getType();
Size sizeAnnotation = io.github.benas.randombeans.util.ReflectionUtils
.getAnnotation(field, Size.class);
final int min = sizeAnnotation.min();
final int max = sizeAnnotation.max();
if (fieldType.equals(String.class)) {
return new StringRandomizer(charset, min, max, random.nextLong());
}
return null;
} | #vulnerable code
public Randomizer<?> getRandomizer(Field field) {
Class<?> fieldType = field.getType();
Size sizeAnnotation = getAnnotation(field, Size.class);
final int min = sizeAnnotation.min();
final int max = sizeAnnotation.max();
if (fieldType.equals(String.class)) {
return new StringRandomizer(charset, min, max, random.nextLong());
}
return null;
}
#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 testGetDeclaredFields() throws Exception {
String javaVersion = System.getProperty("java.specification.version");
if (javaVersion.startsWith("9") || javaVersion.startsWith("10")) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22);
} else {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20);
}
} | #vulnerable code
@Test
public void testGetDeclaredFields() throws Exception {
if (System.getProperty("java.specification.version").startsWith("9")) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22);
} else {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20);
}
}
#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 testJPopulatorFactoryBeanWithCustomRandomizers() {
Populator populator = getPopulatorFromSpringContext("/application-context-with-custom-randomizers.xml");
// the populator managed by spring should be correctly configured
assertThat(populator).isNotNull();
// the populator should populate valid instances
Person person = populator.populateBean(Person.class);
assertPerson(person);
assertThat(person.getEmail())
.isNotNull()
.isNotEmpty()
.matches(".*@.*\\..*");
} | #vulnerable code
@Test
public void testJPopulatorFactoryBeanWithCustomRandomizers() {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("/application-context-with-custom-randomizers.xml");
Populator populator = (Populator) applicationContext.getBean("populator");
// the populator managed by spring should be correctly configured
assertThat(populator).isNotNull();
// the populator should populate valid instances
Person person = populator.populateBean(Person.class);
assertPerson(person);
System.out.println("person.getEmail() = " + person.getEmail());
assertThat(person.getEmail())
.isNotNull()
.isNotEmpty()
.contains("@");
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
if (messageIsRequest) {
Getter getter = new Getter(helpers);
URL url = getter.getURL(messageInfo);
String host = getter.getHost(messageInfo);
String path = url.getPath();
String firstLineOfHeader = getter.getHeaderFirstLine(messageIsRequest,messageInfo);
LinkedHashMap headers = getter.getHeaderHashMap(messageIsRequest,messageInfo);
IHttpService service = messageInfo.getHttpService();
byte[] body = getter.getBody(messageIsRequest,messageInfo);
boolean isRequestChanged = false;
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null) {
isRequestChanged = true;
}
}
//add/update/append header
if (toolFlag == (toolFlag & checkEnabledFor())) {
//if ((config.isOnlyForScope() && callbacks.isInScope(url))|| !config.isOnlyForScope()) {
if (!config.isOnlyForScope()||callbacks.isInScope(url)){
try {
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
//reference https://support.portswigger.net/customer/portal/questions/17350102-burp-upstream-proxy-settings-and-sethttpservice
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int) (Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
} else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
messageInfo.setHttpService(helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol()));
firstLineOfHeader = firstLineOfHeader.replaceFirst(path, url.toString().split("\\?",0)[0]);
isRequestChanged = true;
//success or failed,need to check?
}
} catch (Exception e) {
e.printStackTrace(stderr);
}
}
}
//set final request
List<String> headerList = getter.HeaderMapToList(firstLineOfHeader,headers);
messageInfo.setRequest(helpers.buildHttpMessage(headerList,body));
if (isRequestChanged) {
//debug
List<String> finalheaders = helpers.analyzeRequest(messageInfo).getHeaders();
//List<String> finalheaders = editer.getHeaderList();//error here:bodyOffset getted twice are different
stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}else {//response
}
} | #vulnerable code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
synchronized (messageInfo) {
if (messageIsRequest) {
boolean isRequestChanged = false;
MessageEditor editer = new MessageEditor(messageIsRequest, messageInfo, helpers);
URL url = editer.getURL();
String path = url.getPath();
String host = editer.getHost();
byte[] body = editer.getBody();
LinkedHashMap<String, String> headers = editer.getHeaderMap();//this will lost the first line
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null) {
isRequestChanged = true;
}
}
if (config.getTmpMap().containsKey(host)) {//自动更新cookie
String cookieValue = config.getTmpMap().get(host);
String[] values = cookieValue.split("::::");
String trueCookie = values[1];
headers.put("Cookie", trueCookie);
isRequestChanged = true;
}
//add/update/append header
if (toolFlag == (toolFlag & checkEnabledFor())) {
//if ((config.isOnlyForScope() && callbacks.isInScope(url))|| !config.isOnlyForScope()) {
if (!config.isOnlyForScope()||callbacks.isInScope(url)){
try {
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
editer.setBody(body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
//reference https://support.portswigger.net/customer/portal/questions/17350102-burp-upstream-proxy-settings-and-sethttpservice
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int) (Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
} else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
editer.setService(
helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol()));
String firstrline = editer.getFirstLineOfHeader().replaceFirst(path, url.toString().split("\\?",0)[0]);
editer.setFirstLineOfHeader(firstrline);
isRequestChanged = true;
//success or failed,need to check?
}
} catch (Exception e) {
e.printStackTrace(stderr);
}
}
}
//set final request
editer.setHeaderMap(headers);
messageInfo = editer.getMessageInfo();
if (isRequestChanged) {
//debug
List<String> finalheaders = helpers.analyzeRequest(messageInfo).getHeaders();
//List<String> finalheaders = editer.getHeaderList();//error here:bodyOffset getted twice are different
stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}
}//sync
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
if (messageIsRequest) {
Getter getter = new Getter(helpers);
URL url = getter.getURL(messageInfo);
String host = getter.getHost(messageInfo);
String path = url.getPath();
String firstLineOfHeader = getter.getHeaderFirstLine(messageIsRequest,messageInfo);
LinkedHashMap headers = getter.getHeaderHashMap(messageIsRequest,messageInfo);
IHttpService service = messageInfo.getHttpService();
byte[] body = getter.getBody(messageIsRequest,messageInfo);
boolean isRequestChanged = false;
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null) {
isRequestChanged = true;
}
}
//add/update/append header
if (toolFlag == (toolFlag & checkEnabledFor())) {
//if ((config.isOnlyForScope() && callbacks.isInScope(url))|| !config.isOnlyForScope()) {
if (!config.isOnlyForScope()||callbacks.isInScope(url)){
try {
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
//reference https://support.portswigger.net/customer/portal/questions/17350102-burp-upstream-proxy-settings-and-sethttpservice
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int) (Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
} else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
messageInfo.setHttpService(helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol()));
firstLineOfHeader = firstLineOfHeader.replaceFirst(path, url.toString().split("\\?",0)[0]);
isRequestChanged = true;
//success or failed,need to check?
}
} catch (Exception e) {
e.printStackTrace(stderr);
}
}
}
//set final request
List<String> headerList = getter.HeaderMapToList(firstLineOfHeader,headers);
messageInfo.setRequest(helpers.buildHttpMessage(headerList,body));
if (isRequestChanged) {
//debug
List<String> finalheaders = helpers.analyzeRequest(messageInfo).getHeaders();
//List<String> finalheaders = editer.getHeaderList();//error here:bodyOffset getted twice are different
stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}else {//response
}
} | #vulnerable code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
synchronized (messageInfo) {
if (messageIsRequest) {
boolean isRequestChanged = false;
MessageEditor editer = new MessageEditor(messageIsRequest, messageInfo, helpers);
URL url = editer.getURL();
String path = url.getPath();
String host = editer.getHost();
byte[] body = editer.getBody();
LinkedHashMap<String, String> headers = editer.getHeaderMap();//this will lost the first line
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null) {
isRequestChanged = true;
}
}
if (config.getTmpMap().containsKey(host)) {//自动更新cookie
String cookieValue = config.getTmpMap().get(host);
String[] values = cookieValue.split("::::");
String trueCookie = values[1];
headers.put("Cookie", trueCookie);
isRequestChanged = true;
}
//add/update/append header
if (toolFlag == (toolFlag & checkEnabledFor())) {
//if ((config.isOnlyForScope() && callbacks.isInScope(url))|| !config.isOnlyForScope()) {
if (!config.isOnlyForScope()||callbacks.isInScope(url)){
try {
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
editer.setBody(body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
//reference https://support.portswigger.net/customer/portal/questions/17350102-burp-upstream-proxy-settings-and-sethttpservice
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int) (Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
} else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
editer.setService(
helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol()));
String firstrline = editer.getFirstLineOfHeader().replaceFirst(path, url.toString().split("\\?",0)[0]);
editer.setFirstLineOfHeader(firstrline);
isRequestChanged = true;
//success or failed,need to check?
}
} catch (Exception e) {
e.printStackTrace(stderr);
}
}
}
//set final request
editer.setHeaderMap(headers);
messageInfo = editer.getMessageInfo();
if (isRequestChanged) {
//debug
List<String> finalheaders = helpers.analyzeRequest(messageInfo).getHeaders();
//List<String> finalheaders = editer.getHeaderList();//error here:bodyOffset getted twice are different
stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}
}//sync
}
#location 121
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String getHTTPBasicCredentials(IHttpRequestResponse messageInfo) throws Exception{
String authHeader = getHeaderValueOf(true, messageInfo, "Authorization").trim();
String[] parts = authHeader.split("\\s");
if (parts.length != 2)
throw new Exception("Wrong number of HTTP Authorization header parts");
if (!parts[0].equalsIgnoreCase("Basic"))
throw new Exception("HTTP authentication must be Basic");
return parts[1];
} | #vulnerable code
public String getHTTPBasicCredentials(IHttpRequestResponse messageInfo) throws Exception{
String authHeader = getHeaderValue(true, messageInfo, "Authorization").trim();
String[] parts = authHeader.split("\\s");
if (parts.length != 2)
throw new Exception("Wrong number of HTTP Authorization header parts");
if (!parts[0].equalsIgnoreCase("Basic"))
throw new Exception("HTTP authentication must be Basic");
return parts[1];
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
if (messageIsRequest) {
Getter getter = new Getter(helpers);
URL url = getter.getURL(messageInfo);
String host = getter.getHost(messageInfo);
String path = url.getPath();
String firstLineOfHeader = getter.getHeaderFirstLine(messageIsRequest,messageInfo);
LinkedHashMap headers = getter.getHeaderHashMap(messageIsRequest,messageInfo);
IHttpService service = messageInfo.getHttpService();
byte[] body = getter.getBody(messageIsRequest,messageInfo);
boolean isRequestChanged = false;
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null) {
isRequestChanged = true;
}
}
//add/update/append header
if (toolFlag == (toolFlag & checkEnabledFor())) {
//if ((config.isOnlyForScope() && callbacks.isInScope(url))|| !config.isOnlyForScope()) {
if (!config.isOnlyForScope()||callbacks.isInScope(url)){
try {
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
//reference https://support.portswigger.net/customer/portal/questions/17350102-burp-upstream-proxy-settings-and-sethttpservice
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int) (Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
} else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
messageInfo.setHttpService(helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol()));
firstLineOfHeader = firstLineOfHeader.replaceFirst(path, url.toString().split("\\?",0)[0]);
isRequestChanged = true;
//success or failed,need to check?
}
} catch (Exception e) {
e.printStackTrace(stderr);
}
}
}
//set final request
List<String> headerList = getter.HeaderMapToList(firstLineOfHeader,headers);
messageInfo.setRequest(helpers.buildHttpMessage(headerList,body));
if (isRequestChanged) {
//debug
List<String> finalheaders = helpers.analyzeRequest(messageInfo).getHeaders();
//List<String> finalheaders = editer.getHeaderList();//error here:bodyOffset getted twice are different
stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}else {//response
}
} | #vulnerable code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
synchronized (messageInfo) {
if (messageIsRequest) {
boolean isRequestChanged = false;
MessageEditor editer = new MessageEditor(messageIsRequest, messageInfo, helpers);
URL url = editer.getURL();
String path = url.getPath();
String host = editer.getHost();
byte[] body = editer.getBody();
LinkedHashMap<String, String> headers = editer.getHeaderMap();//this will lost the first line
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null) {
isRequestChanged = true;
}
}
if (config.getTmpMap().containsKey(host)) {//自动更新cookie
String cookieValue = config.getTmpMap().get(host);
String[] values = cookieValue.split("::::");
String trueCookie = values[1];
headers.put("Cookie", trueCookie);
isRequestChanged = true;
}
//add/update/append header
if (toolFlag == (toolFlag & checkEnabledFor())) {
//if ((config.isOnlyForScope() && callbacks.isInScope(url))|| !config.isOnlyForScope()) {
if (!config.isOnlyForScope()||callbacks.isInScope(url)){
try {
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
editer.setBody(body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
//reference https://support.portswigger.net/customer/portal/questions/17350102-burp-upstream-proxy-settings-and-sethttpservice
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int) (Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
} else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
editer.setService(
helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol()));
String firstrline = editer.getFirstLineOfHeader().replaceFirst(path, url.toString().split("\\?",0)[0]);
editer.setFirstLineOfHeader(firstrline);
isRequestChanged = true;
//success or failed,need to check?
}
} catch (Exception e) {
e.printStackTrace(stderr);
}
}
}
//set final request
editer.setHeaderMap(headers);
messageInfo = editer.getMessageInfo();
if (isRequestChanged) {
//debug
List<String> finalheaders = helpers.analyzeRequest(messageInfo).getHeaders();
//List<String> finalheaders = editer.getHeaderList();//error here:bodyOffset getted twice are different
stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}
}//sync
}
#location 29
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public List<String> possibleHeaderNames(IContextMenuInvocation invocation) {
IHttpRequestResponse[] selectedItems = invocation.getSelectedMessages();
//byte selectedInvocationContext = invocation.getInvocationContext();
Getter getter = new Getter(burp.callbacks.getHelpers());
LinkedHashMap<String, String> headers = getter.getHeaderMap(true, selectedItems[0]);
String tokenHeadersStr = burp.tableModel.getConfigValueByKey("tokenHeaders");
List<String> ResultHeaders = new ArrayList<String>();
if (tokenHeadersStr!= null && headers != null) {
String[] tokenHeaders = tokenHeadersStr.split(",");
List<String> keywords = Arrays.asList(tokenHeaders);
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String item = it.next();
if (containOneOfKeywords(item,keywords,false)) {
ResultHeaders.add(item);
}
}
}
return ResultHeaders;
} | #vulnerable code
public List<String> possibleHeaderNames(IContextMenuInvocation invocation) {
IHttpRequestResponse[] selectedItems = invocation.getSelectedMessages();
//byte selectedInvocationContext = invocation.getInvocationContext();
Getter getter = new Getter(burp.callbacks.getHelpers());
LinkedHashMap<String, String> headers = getter.getHeaderMap(true, selectedItems[0]);
String[] tokenHeaders = burp.tableModel.getConfigValueByKey("tokenHeaders").split(",");
List<String> ResultHeaders = new ArrayList<String>();
if (tokenHeaders!= null) {
List<String> keywords = Arrays.asList(tokenHeaders);
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String item = it.next();
if (containOneOfKeywords(item,keywords,false)) {
ResultHeaders.add(item);
}
}
}
return ResultHeaders;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void removeRows(int[] rows) {
PrintWriter stdout1 = new PrintWriter(BurpExtender.callbacks.getStdout(), true);
synchronized (configEntries) {
//because thread let the delete action not in order, so we must loop in here.
//list length and index changed after every remove.the origin index not point to right item any more.
Arrays.sort(rows); //升序
for (int i=rows.length-1;i>=0 ;i-- ) {//降序删除才能正确删除每个元素
String key = configEntries.get(rows[i]).getKey();
this.fireTableRowsDeleted(rows[i], rows[i]);
configEntries.remove(rows[i]);
stdout1.println("!!! "+key+" deleted");
this.fireTableRowsDeleted(rows[i], rows[i]);
}
}
} | #vulnerable code
public void removeRows(int[] rows) {
PrintWriter stdout1 = new PrintWriter(BurpExtender.callbacks.getStdout(), true);
synchronized (configEntries) {
//because thread let the delete action not in order, so we must loop in here.
//list length and index changed after every remove.the origin index not point to right item any more.
Arrays.sort(rows); //升序
for (int i=rows.length-1;i>=0 ;i-- ) {//降序删除才能正确删除每个元素
String key = configEntries.get(rows[i]).getKey();
this.fireTableRowsDeleted(rows[i], rows[i]);
configEntries.remove(rows[i]);
stdout1.println("!!! "+key+" deleted");
//this.fireTableRowsDeleted(rows[i], rows[i]);
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void startCmdConsole() {
try {
Process process = null;
if (Utils.isWindows()) {
process = Runtime.getRuntime().exec("cmd /c start cmd.exe");
} else if (Utils.isMac()){
process = Runtime.getRuntime().exec("open -n -F -a /Applications/Utilities/Terminal.app");
}else if (Utils.isUnix()) {
process = Runtime.getRuntime().exec("/usr/bin/xterm");
}
process.waitFor();//等待执行完成
} catch (Exception e) {
e.printStackTrace();
}
} | #vulnerable code
public static void startCmdConsole() {
try {
Process process = null;
if (Utils.isWindows()) {
process = Runtime.getRuntime().exec("cmd /c start cmd.exe");
} else {
if (new File("/bin/sh").exists()) {
Runtime.getRuntime().exec("/bin/sh");
}else if (new File("/bin/bash").exists()) {
Runtime.getRuntime().exec("/bin/bash");
}
}
process.waitFor();//等待执行完成
} catch (Exception e) {
e.printStackTrace();
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String getHTTPBasicCredentials(IHttpRequestResponse messageInfo) throws Exception{
String authHeader = getHeaderValueOf(true, messageInfo, "Authorization").trim();
String[] parts = authHeader.split("\\s");
if (parts.length != 2)
throw new Exception("Wrong number of HTTP Authorization header parts");
if (!parts[0].equalsIgnoreCase("Basic"))
throw new Exception("HTTP authentication must be Basic");
return parts[1];
} | #vulnerable code
public String getHTTPBasicCredentials(IHttpRequestResponse messageInfo) throws Exception{
String authHeader = getHeaderValueOf(true, messageInfo, "Authorization").trim();
String[] parts = authHeader.split("\\s");
if (parts.length != 2)
throw new Exception("Wrong number of HTTP Authorization header parts");
if (!parts[0].equalsIgnoreCase("Basic"))
throw new Exception("HTTP authentication must be Basic");
return parts[1];
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public List<String> possibleHeaderNames(IContextMenuInvocation invocation) {
IHttpRequestResponse[] selectedItems = invocation.getSelectedMessages();
//byte selectedInvocationContext = invocation.getInvocationContext();
Getter getter = new Getter(burp.callbacks.getHelpers());
LinkedHashMap<String, String> headers = getter.getHeaderMap(true, selectedItems[0]);
List<String> keywords = Arrays.asList(burp.tableModel.getConfigValueByKey("tokenHeaders").split(","));
List<String> ResultHeaders = new ArrayList<String>();
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String item = it.next();
if (containOneOfKeywords(item,keywords,false)) {
ResultHeaders.add(item);
}
}
return ResultHeaders;
} | #vulnerable code
public List<String> possibleHeaderNames(IContextMenuInvocation invocation) {
IHttpRequestResponse[] selectedItems = invocation.getSelectedMessages();
//byte selectedInvocationContext = invocation.getInvocationContext();
Getter getter = new Getter(burp.callbacks.getHelpers());
LinkedHashMap<String, String> headers = getter.getHeaderMap(true, selectedItems[0]);
List<String> keywords = Arrays.asList(burp.tableModel.getConfigByKey("tokenHeaders").split(","));
List<String> ResultHeaders = new ArrayList<String>();
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String item = it.next();
if (containOneOfKeywords(item,keywords,false)) {
ResultHeaders.add(item);
}
}
return ResultHeaders;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
synchronized (messageInfo) {
if (messageIsRequest) {
String firstRequest = new String(messageInfo.getRequest());
int code = messageInfo.hashCode();
//debug
int bodyOffset = helpers.analyzeRequest(messageInfo).getBodyOffset();
int requestLength = messageInfo.getRequest().length;
boolean isRequestChanged = false;
MessageEditor editer = new MessageEditor(messageIsRequest, messageInfo, helpers);
URL url = editer.getURL();
String host = editer.getHost();
byte[] body = editer.getBody();
LinkedHashMap<String, String> headers = editer.getHeaderMap();//this will lost the first line
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null) {
isRequestChanged = true;
}
;
}
if (config.getTmpMap().containsKey(host)) {//自动更新cookie
String cookieValue = config.getTmpMap().get(host);
String[] values = cookieValue.split("::::");
String trueCookie = values[1];
headers.put("Cookie", trueCookie);
isRequestChanged = true;
}
//add/update/append header
if (toolFlag == (toolFlag & checkEnabledFor())) {
if ((config.isOnlyForScope() && callbacks.isInScope(url))
|| !config.isOnlyForScope()) {
try {
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int) (Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
} else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
messageInfo.setHttpService(
helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol()));
isRequestChanged = true;
//success or failed,need to check?
}
} catch (Exception e) {
e.printStackTrace(stderr);
}
}
}
//set final request
editer.setHeaderMap(headers);
messageInfo = editer.getMessageInfo();
String firstRequest1 = new String(messageInfo.getRequest());
int code1 = messageInfo.hashCode();
//debug
int bodyOffset1 = helpers.analyzeRequest(messageInfo).getBodyOffset();
int requestLength1 = messageInfo.getRequest().length;
// stderr.println (firstRequest);
// stderr.println ("first: bodyOffset "+bodyOffset+" requestLength "+requestLength+" hashcode "+code);
// stderr.println ("second: bodyOffset "+bodyOffset1+" requestLength "+requestLength1+" hashcode "+code1);
// stderr.println (firstRequest1);
// stderr.println ("////////////////////////////////");
if (isRequestChanged) {
//debug
List<String> finalheaders = new MessageEditor(messageIsRequest, messageInfo, helpers).getHeaderList();
stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}
}//sync
} | #vulnerable code
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
if (messageIsRequest){
boolean isRequestChanged = false;
MessageEditor editer = new MessageEditor(messageIsRequest,messageInfo,helpers);
String md5 = editer.getMd5();//to judge message is changed or not
URL url =editer.getURL();
String host = editer.getHost();
byte[] body = editer.getBody();
LinkedHashMap<String, String> headers = editer.getHeaderMap();//this will lost the first line
//remove header
List<ConfigEntry> configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers);
for (ConfigEntry entry : configEntries) {
String key = entry.getKey();
if (headers.remove(key) != null){
isRequestChanged = true;
};
}
if (config.getTmpMap().containsKey(host)) {//自动更新cookie
String cookieValue = config.getTmpMap().get(host);
String[] values = cookieValue.split("::::");
String trueCookie = values[1];
headers.put("Cookie", trueCookie);
isRequestChanged = true;
}
//add/update/append header
if (toolFlag == (toolFlag&checkEnabledFor())){
if((config.isOnlyForScope()&& callbacks.isInScope(url))
|| !config.isOnlyForScope()) {
try{
List<ConfigEntry> updateOrAddEntries = tableModel.getConfigEntries();
for (ConfigEntry entry : updateOrAddEntries) {
String key = entry.getKey();
String value = entry.getValue();
if (value.contains("%host")) {
value = value.replaceAll("%host", host);
//stdout.println("3333"+value);
}
if (value.toLowerCase().contains("%dnslogserver")) {
String dnslog = tableModel.getConfigByKey("DNSlogServer");
Pattern p = Pattern.compile("(?u)%dnslogserver");
Matcher m = p.matcher(value);
while (m.find()) {
String found = m.group(0);
value = value.replaceAll(found, dnslog);
}
}
if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) {
headers.put(key, value);
isRequestChanged = true;
} else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) {
value = headers.get(key) + value;
headers.put(key, value);
isRequestChanged = true;
//stdout.println("2222"+value);
} else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) {
headers.put("Transfer-Encoding", "chunked");
isRequestChanged = true;
try {
boolean useComment = false;
if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) {
useComment = true;
}
String lenStr = this.tableModel.getConfigByKey("Chunked-Length");
int len = 10;
if (lenStr != null) {
len = Integer.parseInt(lenStr);
}
body = Methods.encoding(body, len, useComment);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(stderr);
}
}
}
///proxy function should be here
String proxy = this.tableModel.getConfigByKey("Proxy-ServerList");
String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode");
if (proxy != null) {//if enable is false, will return null.
List<String> proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃
if (mode != null) {//random mode
proxyServerIndex = (int)(Math.random() * proxyList.size());
//proxyServerIndex = new Random().nextInt(proxyList.size());
}else {
proxyServerIndex = (proxyServerIndex + 1) % proxyList.size();
}
String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim();
int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim());
messageInfo.setHttpService(
helpers.buildHttpService(proxyhost,port,messageInfo.getHttpService().getProtocol()));
isRequestChanged = true;
//success or failed,need to check?
}
}
catch(Exception e){
e.printStackTrace(stderr);
}
}
}
//set final request
editer.setHeaderMap(headers);
messageInfo = editer.getMessageInfo();
if (isRequestChanged) {
//debug
List<String> finalheaders = new MessageEditor(messageIsRequest,messageInfo,helpers).getHeaderList();
stdout.println(System.lineSeparator()+"//////////edited request by knife//////////////"+System.lineSeparator());
for (String entry : finalheaders) {
stdout.println(entry);
}
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void readClasspathResource() {
boolean ok = true;
ok |= Str.in ("apple", IO.read ( "classpath://testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:///testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "/testfile.txt" ))
|| die( "two slashes should work" );
puts(IO.list ( "classpath:/org/node" )) ;
//Proper URL
ok |=
Lists.idx (IO.list ( "classpath:/org/node" ), 0).endsWith ( "org/node/file1.txt" )
|| die( );
} | #vulnerable code
@Test
public void readClasspathResource() {
boolean ok = true;
ok |= Str.in ("apple", IO.read ( "classpath://testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:///testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "/testfile.txt" ))
|| die( "two slashes should work" );
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void readClasspathResource() {
boolean ok = true;
ok |= Str.in ("apple", IO.read ( "classpath://testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:///testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "/testfile.txt" ))
|| die( "two slashes should work" );
puts(IO.list ( "classpath:/org/node" )) ;
//Proper URL
ok |=
Lists.idx (IO.list ( "classpath:/org/node" ), 0).endsWith ( "org/node/file1.txt" )
|| die( );
} | #vulnerable code
@Test
public void readClasspathResource() {
boolean ok = true;
ok |= Str.in ("apple", IO.read ( "classpath://testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:///testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "/testfile.txt" ))
|| die( "two slashes should work" );
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Map<String, Pair<Method>> getPropertySetterGetterMethods(
Class<? extends Object> theClass ) {
Method[] methods = theClass.getMethods ( );
Map<String, Pair<Method>> methodMap = new LinkedHashMap<> ( methods.length );
List<Method> getterMethodList = new ArrayList<> ( methods.length );
for ( int index = 0; index < methods.length; index++ ) {
Method method = methods[index];
String name = method.getName ( );
if ( method.getParameterTypes ( ).length == 1
&& method.getReturnType ( ) == void.class
&& name.startsWith ( "set" ) ) {
Pair<Method> pair = new Pair<Method> ( );
pair.setFirst ( method );
String propertyName = slc ( name, 3 );
propertyName = lower ( slc ( propertyName, 0, 1 ) ) + slc ( propertyName, 1 );
methodMap.put ( propertyName, pair );
}
if ( method.getParameterTypes ( ).length > 0
|| method.getReturnType ( ) == void.class
|| !( name.startsWith ( "get" ) || name.startsWith ( "is" ) )
|| name.equals ( "getClass" ) ) {
continue;
}
getterMethodList.add ( method );
}
for ( Method method : getterMethodList ) {
String name = method.getName ( );
String propertyName = null;
if ( name.startsWith ( "is" ) ) {
propertyName = name.substring ( 2 );
} else if ( name.startsWith ( "get" ) ) {
propertyName = name.substring ( 3 );
}
propertyName = lower ( propertyName.substring ( 0, 1 )) + propertyName.substring ( 1 ) ;
Pair<Method> pair = methodMap.get ( propertyName );
if ( pair == null ) {
pair = new Pair<> ( );
methodMap.put ( propertyName, pair );
}
pair.setSecond ( method );
}
return methodMap;
} | #vulnerable code
public static Map<String, Pair<Method>> getPropertySetterGetterMethods(
Class<? extends Object> theClass ) {
Method[] methods = theClass.getMethods ( );
Map<String, Pair<Method>> methodMap = new LinkedHashMap<> ( methods.length );
List<Method> getterMethodList = new ArrayList<> ( methods.length );
for ( int index = 0; index < methods.length; index++ ) {
Method method = methods[index];
String name = method.getName ( );
if ( method.getParameterTypes ( ).length == 1
&& method.getReturnType ( ) == void.class
&& name.startsWith ( "set" ) ) {
Pair<Method> pair = new Pair<Method> ( );
pair.setFirst ( method );
String propertyName = slc ( name, 3 );
propertyName = lower ( slc ( propertyName, 0, 1 ) ) + slc ( propertyName, 1 );
methodMap.put ( propertyName, pair );
}
if ( method.getParameterTypes ( ).length > 0
|| method.getReturnType ( ) == void.class
|| !( name.startsWith ( "get" ) || name.startsWith ( "is" ) )
|| name.equals ( "getClass" ) ) {
continue;
}
getterMethodList.add ( method );
}
for ( Method method : getterMethodList ) {
String name = method.getName ( );
String propertyName = null;
if ( name.startsWith ( "is" ) ) {
propertyName = slc ( name, 2 );
} else if ( name.startsWith ( "get" ) ) {
propertyName = slc ( name, 3 );
}
propertyName = lower ( slc ( propertyName, 0, 1 ) ) + slc ( propertyName, 1 );
Pair<Method> pair = methodMap.get ( propertyName );
if ( pair == null ) {
pair = new Pair<Method> ( );
methodMap.put ( propertyName, pair );
}
pair.setSecond ( method );
}
return methodMap;
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void readClasspathResource() {
boolean ok = true;
ok |= Str.in ("apple", IO.read ( "classpath://testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:///testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "/testfile.txt" ))
|| die( "two slashes should work" );
puts(IO.list ( "classpath:/org/node" )) ;
//Proper URL
ok |=
Lists.idx (IO.list ( "classpath:/org/node" ), 0).endsWith ( "org/node/file1.txt" )
|| die( );
} | #vulnerable code
@Test
public void readClasspathResource() {
boolean ok = true;
ok |= Str.in ("apple", IO.read ( "classpath://testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:///testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.read ( "classpath:testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "testfile.txt" ))
|| die( "two slashes should work" );
//Proper URL
ok |= Str.in ("apple", IO.readFromClasspath ( this.getClass (), "/testfile.txt" ))
|| die( "two slashes should work" );
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void doExecute()
throws MojoExecutionException, MojoFailureException
{
setup();
boolean generated = false;
// java -cp gwt-dev.jar:gwt-user.jar
// com.google.gwt.resources.css.InterfaceGenerator -standalone -typeName some.package.MyCssResource -css
// input.css
if ( cssFiles != null )
{
for ( String file : cssFiles )
{
final String typeName = FilenameUtils.separatorsToSystem( file ).
substring( 0, file.lastIndexOf( '.' ) ).replace( File.separatorChar, '.' );
final File javaOutput =
new File( getGenerateDirectory(), typeName.replace( '.', File.separatorChar ) + ".java" );
final StringBuilder content = new StringBuilder();
out = new StreamConsumer()
{
public void consumeLine( String line )
{
content.append( line ).append( SystemUtils.LINE_SEPARATOR );
}
};
for ( Resource resource : (List<Resource>) getProject().getResources() )
{
final File candidate = new File( resource.getDirectory(), file );
if ( candidate.exists() )
{
if ( buildContext.isUptodate( javaOutput, candidate ) )
{
getLog().debug( javaOutput.getAbsolutePath() + " is up to date. Generation skipped" );
// up to date, but still need to report generated-sources directory as sourceRoot
generated = true;
break;
}
getLog().info( "Generating " + javaOutput + " with typeName " + typeName );
ensureTargetPackageExists( getGenerateDirectory(), typeName );
try
{
new JavaCommand( "com.google.gwt.resources.css.InterfaceGenerator" )
.withinScope( Artifact.SCOPE_COMPILE )
.arg( "-standalone" )
.arg( "-typeName" )
.arg( typeName )
.arg( "-css" )
.arg( candidate.getAbsolutePath() )
.withinClasspath( getGwtDevJar() )
.withinClasspath( getGwtUserJar() )
.execute();
final OutputStreamWriter outputWriter =
new OutputStreamWriter( buildContext.newFileOutputStream( javaOutput ) , encoding );
try {
outputWriter.write( content.toString() );
} finally {
IOUtil.close( outputWriter );
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "Failed to write to file: " + javaOutput );
}
generated = true;
break;
}
}
if ( content.length() == 0 )
{
throw new MojoExecutionException( "cannot generate java source from file " + file + "." );
}
}
}
if ( generated )
{
getLog().debug( "add compile source root " + getGenerateDirectory() );
addCompileSourceRoot( getGenerateDirectory() );
}
} | #vulnerable code
public void doExecute()
throws MojoExecutionException, MojoFailureException
{
setup();
boolean generated = false;
// java -cp gwt-dev.jar:gwt-user.jar
// com.google.gwt.resources.css.InterfaceGenerator -standalone -typeName some.package.MyCssResource -css
// input.css
if ( cssFiles != null )
{
for ( String file : cssFiles )
{
final String typeName = FilenameUtils.separatorsToSystem( file ).
substring( 0, file.lastIndexOf( '.' ) ).replace( File.separatorChar, '.' );
final File javaOutput =
new File( getGenerateDirectory(), typeName.replace( '.', File.separatorChar ) + ".java" );
final StringBuilder content = new StringBuilder();
out = new StreamConsumer()
{
public void consumeLine( String line )
{
content.append( line ).append( SystemUtils.LINE_SEPARATOR );
}
};
for ( Resource resource : (List<Resource>) getProject().getResources() )
{
final File candidate = new File( resource.getDirectory(), file );
if ( candidate.exists() )
{
getLog().info( "Generating " + javaOutput + " with typeName " + typeName );
ensureTargetPackageExists( getGenerateDirectory(), typeName );
try
{
new JavaCommand( "com.google.gwt.resources.css.InterfaceGenerator" )
.withinScope( Artifact.SCOPE_COMPILE )
.arg( "-standalone" )
.arg( "-typeName" )
.arg( typeName )
.arg( "-css" )
.arg( candidate.getAbsolutePath() )
.withinClasspath( getGwtDevJar() )
.withinClasspath( getGwtUserJar() )
.execute();
final FileWriter outputWriter = new FileWriter( javaOutput );
outputWriter.write( content.toString() );
outputWriter.close();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Failed to write to file: " + javaOutput );
}
generated = true;
break;
}
}
if ( content.length() == 0 )
{
throw new MojoExecutionException( "cannot generate java source from file " + file + "." );
}
}
}
if ( generated )
{
getLog().debug( "add compile source root " + getGenerateDirectory() );
addCompileSourceRoot( getGenerateDirectory() );
}
}
#location 51
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void doExecute()
throws MojoExecutionException, MojoFailureException
{
setup();
boolean generated = false;
// java -cp gwt-dev.jar:gwt-user.jar
// com.google.gwt.resources.css.InterfaceGenerator -standalone -typeName some.package.MyCssResource -css
// input.css
if ( cssFiles != null )
{
for ( String file : cssFiles )
{
final String typeName = FilenameUtils.separatorsToSystem( file ).
substring( 0, file.lastIndexOf( '.' ) ).replace( File.separatorChar, '.' );
final File javaOutput =
new File( getGenerateDirectory(), typeName.replace( '.', File.separatorChar ) + ".java" );
final StringBuilder content = new StringBuilder();
out = new StreamConsumer()
{
public void consumeLine( String line )
{
content.append( line ).append( SystemUtils.LINE_SEPARATOR );
}
};
for ( Resource resource : (List<Resource>) getProject().getResources() )
{
final File candidate = new File( resource.getDirectory(), file );
if ( candidate.exists() )
{
if ( buildContext.isUptodate( javaOutput, candidate ) )
{
getLog().debug( javaOutput.getAbsolutePath() + " is up to date. Generation skipped" );
// up to date, but still need to report generated-sources directory as sourceRoot
generated = true;
break;
}
getLog().info( "Generating " + javaOutput + " with typeName " + typeName );
ensureTargetPackageExists( getGenerateDirectory(), typeName );
try
{
new JavaCommand( "com.google.gwt.resources.css.InterfaceGenerator" )
.withinScope( Artifact.SCOPE_COMPILE )
.arg( "-standalone" )
.arg( "-typeName" )
.arg( typeName )
.arg( "-css" )
.arg( candidate.getAbsolutePath() )
.withinClasspath( getGwtDevJar() )
.withinClasspath( getGwtUserJar() )
.execute();
final OutputStreamWriter outputWriter =
new OutputStreamWriter( buildContext.newFileOutputStream( javaOutput ) , encoding );
try {
outputWriter.write( content.toString() );
} finally {
IOUtil.close( outputWriter );
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "Failed to write to file: " + javaOutput );
}
generated = true;
break;
}
}
if ( content.length() == 0 )
{
throw new MojoExecutionException( "cannot generate java source from file " + file + "." );
}
}
}
if ( generated )
{
getLog().debug( "add compile source root " + getGenerateDirectory() );
addCompileSourceRoot( getGenerateDirectory() );
}
} | #vulnerable code
public void doExecute()
throws MojoExecutionException, MojoFailureException
{
setup();
boolean generated = false;
// java -cp gwt-dev.jar:gwt-user.jar
// com.google.gwt.resources.css.InterfaceGenerator -standalone -typeName some.package.MyCssResource -css
// input.css
if ( cssFiles != null )
{
for ( String file : cssFiles )
{
final String typeName = FilenameUtils.separatorsToSystem( file ).
substring( 0, file.lastIndexOf( '.' ) ).replace( File.separatorChar, '.' );
final File javaOutput =
new File( getGenerateDirectory(), typeName.replace( '.', File.separatorChar ) + ".java" );
final StringBuilder content = new StringBuilder();
out = new StreamConsumer()
{
public void consumeLine( String line )
{
content.append( line ).append( SystemUtils.LINE_SEPARATOR );
}
};
for ( Resource resource : (List<Resource>) getProject().getResources() )
{
final File candidate = new File( resource.getDirectory(), file );
if ( candidate.exists() )
{
getLog().info( "Generating " + javaOutput + " with typeName " + typeName );
ensureTargetPackageExists( getGenerateDirectory(), typeName );
try
{
new JavaCommand( "com.google.gwt.resources.css.InterfaceGenerator" )
.withinScope( Artifact.SCOPE_COMPILE )
.arg( "-standalone" )
.arg( "-typeName" )
.arg( typeName )
.arg( "-css" )
.arg( candidate.getAbsolutePath() )
.withinClasspath( getGwtDevJar() )
.withinClasspath( getGwtUserJar() )
.execute();
final FileWriter outputWriter = new FileWriter( javaOutput );
outputWriter.write( content.toString() );
outputWriter.close();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Failed to write to file: " + javaOutput );
}
generated = true;
break;
}
}
if ( content.length() == 0 )
{
throw new MojoExecutionException( "cannot generate java source from file " + file + "." );
}
}
}
if ( generated )
{
getLog().debug( "add compile source root " + getGenerateDirectory() );
addCompileSourceRoot( getGenerateDirectory() );
}
}
#location 51
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void profile() throws IOException {
BaseConfiguration config = new BaseConfiguration();
config.addProperty(Graph.GRAPH, ElasticGraph.class.getName());
config.addProperty("elasticsearch.cluster.name", "test");
config.addProperty("elasticsearch.index.name", "graph");
config.addProperty("elasticsearch.refresh", true);
config.addProperty("elasticsearch.client", ElasticService.ClientType.NODE.toString());
startWatch("graph initalization");
ElasticGraph graph = new ElasticGraph(config);
stopWatch("graph initalization");
startWatch("add vertices");
int count = 10000;
for(int i = 0; i < count; i++)
graph.addVertex();
stopWatch("add vertices");
startWatch("vertex iterator");
Iterator<Vertex> vertexIterator = graph.iterators().vertexIterator();
stopWatch("vertex iterator");
startWatch("add edges");
vertexIterator.forEachRemaining(v -> v.addEdge("bla", v));
stopWatch("add edges");
startWatch("edge iterator");
Iterator<Edge> edgeIterator = graph.iterators().edgeIterator();
stopWatch("edge iterator");
sw.print();
System.out.println("-----");
graph.elasticService.collectData();
graph.close();
} | #vulnerable code
@Test
public void profile() throws IOException {
BaseConfiguration config = new BaseConfiguration();
config.addProperty(Graph.GRAPH, ElasticGraph.class.getName());
config.addProperty("elasticsearch.cluster.name", "test");
String indexName = "graph";
config.addProperty("elasticsearch.index.name", indexName.toLowerCase());
config.addProperty("elasticsearch.refresh", true);
config.addProperty("elasticsearch.client", ElasticService.ClientType.NODE.toString());
startWatch();
ElasticGraph graph = new ElasticGraph(config);
stopWatch("graph initalization");
startWatch();
int count = 1000;
for(int i = 0; i < count; i++)
graph.addVertex();
stopWatch("add vertices");
startWatch();
Iterator<Vertex> vertexIterator = graph.iterators().vertexIterator();
stopWatch("vertex iterator");
startWatch();
vertexIterator.forEachRemaining(v -> v.addEdge("bla", v));
stopWatch("add edges");
startWatch();
Iterator<Edge> edgeIterator = graph.iterators().edgeIterator();
stopWatch("edge iterator");
}
#location 30
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void hasNot() throws IOException {
BaseConfiguration config = new BaseConfiguration();
config.addProperty("elasticsearch.cluster.name", "test");
config.addProperty("elasticsearch.index.name", "graph");
config.addProperty("elasticsearch.refresh", true);
config.addProperty("elasticsearch.client", ElasticService.ClientType.NODE);
ElasticGraph graph = new ElasticGraph(config);
((DefaultSchemaProvider)graph.elasticService.schemaProvider).clearAllData();
Vertex vertex = graph.addVertex(T.label, "test_doc", T.id, "1", "name", "eliran", "age", 24);
Vertex vertex1 = graph.addVertex(T.label, "test_doc", T.id, "2", "name", "ran");
Vertex vertex2 = graph.addVertex(T.label, "test_doc", T.id, "3", "name", "chiko");
Vertex vertex3 = graph.addVertex(T.label, "test_doc", T.id, "4", "name", "medico");
vertex2.addEdge("heardof",vertex,T.id,"111");
vertex.addEdge("knows",vertex1);
vertex.addEdge("heardof",vertex3);
//graph.V("1").outE("heardof").next();
//vertex1.addEdge("knows",vertex);
Element knows = graph.E("111").has(T.label, "heardof").next();
Object out = graph.V("1").out().next();
Object in = graph.V("1").in().next();
int i=1;
graph.close();
} | #vulnerable code
@Test
public void hasNot() throws IOException {
BaseConfiguration config = new BaseConfiguration();
config.addProperty(Graph.GRAPH, ElasticGraph.class.getName());
config.addProperty("elasticsearch.cluster.name", "test2");
String indexName = "graph2";
config.addProperty("elasticsearch.index.name", indexName.toLowerCase());
config.addProperty("elasticsearch.local", true);
config.addProperty("elasticsearch.refresh", true);
config.addProperty("elasticsearch.client", "NODE");
ElasticGraph graph = new ElasticGraph(config);
((DefaultSchemaProvider)graph.elasticService.schemaProvider).clearAllData();
Vertex vertex = graph.addVertex(T.label, "test_doc", T.id, "1", "name", "eliran", "age", 24);
Vertex vertex1 = graph.addVertex(T.label, "test_doc", T.id, "2", "name", "ran");
Vertex vertex2 = graph.addVertex(T.label, "test_doc", T.id, "3", "name", "chiko");
Vertex vertex3 = graph.addVertex(T.label, "test_doc", T.id, "4", "name", "medico");
vertex2.addEdge("heardof",vertex,T.id,"111");
vertex.addEdge("knows",vertex1);
vertex.addEdge("heardof",vertex3);
//graph.V("1").outE("heardof").next();
//vertex1.addEdge("knows",vertex);
Element knows = graph.E("111").has(T.label, "heardof").next();
Object out = graph.V("1").out().next();
Object in = graph.V("1").in().next();
int i=1;
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("execute");
try {
// get classes we need with reflection
Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell");
// create a GroovyShell to run scripts in
Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass));
// TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts?
// run the scripts
int scriptNum = 1;
for (String script : scripts) {
Closer closer = Closer.create();
try {
try {
URL url = new URL(script);
// it's a URL to a script
getLog().info("Fetching Groovy script from " + url.toString() + ".");
BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream())));
StringBuilder scriptSource = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
scriptSource.append(line).append("\n");
}
if (!scriptSource.toString().isEmpty()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString());
}
} catch (MalformedURLException e) {
// it's not a URL to a script, treat as a script body
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script);
} catch (Throwable throwable) {
throw closer.rethrow(throwable);
} finally {
closer.close();
}
} catch (IOException ioe) {
if (continueExecuting) {
getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe);
} else {
throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe);
}
}
scriptNum++;
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
}
} | #vulnerable code
public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("execute");
try {
// get classes we need with reflection
Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell");
// create a GroovyShell to run scripts in
Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass));
// TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts?
// run the scripts
int scriptNum = 1;
for (String script : scripts) {
Closer closer = Closer.create();
try {
try {
URL url = new URL(script);
// it's a URL to a script
getLog().info("Fetching Groovy script from " + url.toString() + ".");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder scriptSource = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
scriptSource.append(line).append("\n");
}
if (!scriptSource.toString().isEmpty()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString());
}
} catch (MalformedURLException e) {
// it's not a URL to a script, treat as a script body
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script);
} catch (Throwable throwable) {
throw closer.rethrow(throwable);
} finally {
closer.close();
}
} catch (IOException ioe) {
if (continueExecuting) {
getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe);
} else {
throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe);
}
}
scriptNum++;
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
}
}
#location 31
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testScriptString() throws Exception {
File file = tmpDir.newFile();
String line = "hello world";
executeMojo.scripts = new String[] { "new File('" + file.getAbsolutePath().replaceAll("\\\\", "/") + "').withWriter { w -> w << '" + line +"' }" };
executeMojo.execute();
BufferedReader reader = new BufferedReader(new FileReader(file));
LineReader lineReader = new LineReader(reader);
String actualLine = lineReader.readLine();
reader.close();
Assert.assertEquals(line, actualLine);
} | #vulnerable code
@Test
public void testScriptString() throws Exception {
File file = tmpDir.newFile();
String line = "hello world";
executeMojo.scripts = new String[] { "new File('" + file.getAbsolutePath().replaceAll("\\\\", "/") + "').withWriter { w -> w << '" + line +"' }" };
executeMojo.execute();
LineReader lineReader = new LineReader(new BufferedReader(new FileReader(file)));
String actualLine = lineReader.readLine();
Assert.assertEquals(line, actualLine);
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("execute");
try {
// get classes we need with reflection
Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell");
// create a GroovyShell to run scripts in
Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass));
// TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts?
// run the scripts
int scriptNum = 1;
for (String script : scripts) {
BufferedReader reader = null;
try {
URL url = new URL(script);
// it's a URL to a script
getLog().info("Fetching Groovy script from " + url.toString() + ".");
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder scriptSource = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
scriptSource.append(line).append("\n");
}
if (!scriptSource.toString().isEmpty()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString());
}
} catch (MalformedURLException e) {
// it's not a URL to a script, treat as a script body
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script);
} catch (IOException e) {
if (continueExecuting) {
getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", e);
} else {
throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", e);
}
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
// if we can't close the steam there's nothing more we can do
}
}
scriptNum++;
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
}
} | #vulnerable code
public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("execute");
try {
// get classes we need with reflection
Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell");
// create a GroovyShell to run scripts in
Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass));
// TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts?
// run the scripts
int scriptNum = 1;
for (String script : scripts) {
try {
URL url = new URL(script);
// it's a URL to a script
getLog().info("Fetching Groovy script from " + url.toString() + ".");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder scriptSource = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
scriptSource.append(line).append("\n");
}
if (!scriptSource.toString().isEmpty()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString());
}
} catch (MalformedURLException e) {
// it's not a URL to a script, treat as a script body
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script);
} catch (IOException e) {
if (continueExecuting) {
getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", e);
} else {
throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", e);
}
}
scriptNum++;
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
}
}
#location 29
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.