instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void begin(VehicleRoute route) { currentLoad = (int) stateManager.getRouteState(route, StateIdFactory.LOAD_AT_BEGINNING).toDouble(); this.route = route; }
#vulnerable code @Override public void begin(VehicleRoute route) { currentLoad = (int) stateManager.getRouteState(route, StateIdFactory.LOAD_AT_DEPOT).toDouble(); this.route = route; } #location 3 #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){ BufferedReader reader = getReader(filename); String line = null; boolean firstline = true; Coordinate depotCoord = null; int customerCount=0; Integer nuOfCustomer = 0; while((line=readLine(reader))!=null){ String trimedLine = line.trim(); if(trimedLine.startsWith("//")) continue; String[] tokens = trimedLine.split("\\s+"); if(firstline){ nuOfCustomer=Integer.parseInt(tokens[0]); customerCount=0; firstline=false; } else if(customerCount<=nuOfCustomer) { if(customerCount == 0){ depotCoord = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); } else{ Service.Builder serviceBuilder = Service.Builder.newInstance(tokens[0]).addSizeDimension(0, Integer.parseInt(tokens[3])); serviceBuilder.setCoord(Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]))); vrpBuilder.addJob(serviceBuilder.build()); } customerCount++; } else if(trimedLine.startsWith("v")){ VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("type_"+tokens[1]).addCapacityDimension(0, Integer.parseInt(tokens[2])); int nuOfVehicles = 1; if(vrphType.equals(VrphType.FSMF)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); } else if(vrphType.equals(VrphType.FSMFD)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.FSMD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.HVRPD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if (vrphType.equals(VrphType.HVRPFD)){ if(tokens.length > 4){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } for(int i=0;i<nuOfVehicles;i++){ VehicleTypeImpl type = typeBuilder.build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("vehicle_"+tokens[1]+"_"+i) .setStartLocationCoordinate(depotCoord).setType(type).build(); vrpBuilder.addVehicle(vehicle); } } } closeReader(reader); }
#vulnerable code public void read(String filename){ BufferedReader reader = getReader(filename); String line = null; boolean firstline = true; Coordinate depotCoord = null; int customerCount=0; Integer nuOfCustomer = 0; while((line=readLine(reader))!=null){ String trimedLine = line.trim(); if(trimedLine.startsWith("//")) continue; String[] tokens = trimedLine.split("\\s+"); if(firstline){ nuOfCustomer=Integer.parseInt(tokens[0]); customerCount=0; firstline=false; } else if(customerCount<=nuOfCustomer) { if(customerCount == 0){ depotCoord = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); } else{ Service.Builder serviceBuilder = Service.Builder.newInstance(tokens[0], Integer.parseInt(tokens[3])); serviceBuilder.setCoord(Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]))); vrpBuilder.addJob(serviceBuilder.build()); } customerCount++; } else if(trimedLine.startsWith("v")){ VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("type_"+tokens[1], Integer.parseInt(tokens[2])); int nuOfVehicles = 1; if(vrphType.equals(VrphType.FSMF)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); } else if(vrphType.equals(VrphType.FSMFD)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.FSMD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.HVRPD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if (vrphType.equals(VrphType.HVRPFD)){ if(tokens.length > 4){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } for(int i=0;i<nuOfVehicles;i++){ VehicleTypeImpl type = typeBuilder.build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("vehicle_"+tokens[1]+"_"+i) .setLocationCoord(depotCoord).setType(type).build(); vrpBuilder.addVehicle(vehicle); } } } closeReader(reader); } #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 skillViolationAtAct2_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(1), route); assertTrue(violated); }
#vulnerable code @Test public void skillViolationAtAct2_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(1),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 public void read(String fileName){ vrpBuilder.setFleetSize(FleetSize.INFINITE); BufferedReader reader = getReader(fileName); int vehicleCapacity = 0; double serviceTime = 0.0; double endTime = Double.MAX_VALUE; int counter = 0; String line = null; while((line = readLine(reader)) != null){ line = line.replace("\r", ""); line = line.trim(); String[] tokens = line.split(" "); if(counter == 0){ vehicleCapacity = Integer.parseInt(tokens[1].trim()); endTime = Double.parseDouble(tokens[2].trim()); serviceTime = Double.parseDouble(tokens[3].trim()); } else if(counter == 1){ Coordinate depotCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance("christophidesType").addCapacityDimension(0, vehicleCapacity). setCostPerDistance(1.0).build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("christophidesVehicle").setLatestArrival(endTime).setStartLocationCoordinate(depotCoord). setType(vehicleType).build(); vrpBuilder.addVehicle(vehicle); } else{ Coordinate customerCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); int demand = Integer.parseInt(tokens[2].trim()); String customer = Integer.valueOf(counter-1).toString(); Service service = Service.Builder.newInstance(customer).addSizeDimension(0, demand).setServiceTime(serviceTime).setCoord(customerCoord).build(); vrpBuilder.addJob(service); } counter++; } close(reader); }
#vulnerable code public void read(String fileName){ vrpBuilder.setFleetSize(FleetSize.INFINITE); BufferedReader reader = getReader(fileName); int vehicleCapacity = 0; double serviceTime = 0.0; double endTime = Double.MAX_VALUE; int counter = 0; String line = null; while((line = readLine(reader)) != null){ line = line.replace("\r", ""); line = line.trim(); String[] tokens = line.split(" "); if(counter == 0){ vehicleCapacity = Integer.parseInt(tokens[1].trim()); endTime = Double.parseDouble(tokens[2].trim()); serviceTime = Double.parseDouble(tokens[3].trim()); } else if(counter == 1){ Coordinate depotCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance("christophidesType", vehicleCapacity). setCostPerDistance(1.0).build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("christophidesVehicle").setLatestArrival(endTime).setLocationCoord(depotCoord). setType(vehicleType).build(); vrpBuilder.addVehicle(vehicle); } else{ Coordinate customerCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); int demand = Integer.parseInt(tokens[2].trim()); String customer = Integer.valueOf(counter-1).toString(); Service service = Service.Builder.newInstance(customer, demand).setServiceTime(serviceTime).setCoord(customerCoord).build(); vrpBuilder.addJob(service); } counter++; } close(reader); } #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 testStatesOfAct2(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(30.0, states.getActivityState(act2, StateFactory.COSTS).toDouble(),0.05); assertEquals(10.0, states.getActivityState(act2, StateFactory.LOAD).toDouble(),0.05); assertEquals(40.0, states.getActivityState(act2, StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); }
#vulnerable code @Test public void testStatesOfAct2(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(30.0, states.getActivityState(tour.getActivities().get(1), StateFactory.COSTS).toDouble(),0.05); assertEquals(10.0, states.getActivityState(tour.getActivities().get(1), StateFactory.LOAD).toDouble(),0.05); // assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateTypes.EARLIEST_OPERATION_START_TIME).toDouble(),0.05); assertEquals(40.0, states.getActivityState(tour.getActivities().get(1), StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); } #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 whenWritingVehicleV2_readingItsLocationsCoordsAgainReturnsCorrectLocationsCoords(){ 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("startLoc", Coordinate.newInstance(1, 2))) .setEndLocation(TestUtils.loc("endLoc",Coordinate.newInstance(4, 5))).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(1.0,v.getStartLocation().getCoordinate().getX(),0.01); assertEquals(2.0,v.getStartLocation().getCoordinate().getY(),0.01); assertEquals(4.0,v.getEndLocation().getCoordinate().getX(),0.01); assertEquals(5.0,v.getEndLocation().getCoordinate().getY(),0.01); }
#vulnerable code @Test public void whenWritingVehicleV2_readingItsLocationsCoordsAgainReturnsCorrectLocationsCoords(){ 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("startLoc").setStartLocationCoordinate(Coordinate.newInstance(1, 2)) .setEndLocationId("endLoc").setEndLocationCoordinate(Coordinate.newInstance(4, 5)).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(1.0,v.getStartLocationCoordinate().getX(),0.01); assertEquals(2.0,v.getStartLocationCoordinate().getY(),0.01); assertEquals(4.0,v.getEndLocationCoordinate().getX(),0.01); assertEquals(5.0,v.getEndLocationCoordinate().getY(),0.01); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private JsonNode buildTree_and_getRoot_fromFile(File jsonFile){ JsonNode node = null; try { ObjectMapper objectMapper = new ObjectMapper(); node = objectMapper.readTree(new FileReader(jsonFile)).path(JsonConstants.PROBLEM); } catch (IOException e) { e.printStackTrace(); System.exit(1); } return node; }
#vulnerable code private JsonNode buildTree_and_getRoot_fromFile(File jsonFile){ JsonNode node = null; try { ObjectMapper objectMapper = new ObjectMapper(); String jsonContent = ""; BufferedReader reader = new BufferedReader(new FileReader(jsonFile)); String line; while((line = reader.readLine()) != null) jsonContent += line; reader.close(); node = objectMapper.readTree(jsonContent); } catch (IOException e) { e.printStackTrace(); System.exit(1); } return node; } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String matrixFile){ BufferedReader reader = getBufferedReader(matrixFile); String line; boolean isEdgeWeights = false; int fromIndex = 0; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("EDGE_WEIGHT_SECTION")){ isEdgeWeights = true; continue; } if(line.startsWith("DEMAND_SECTION")){ isEdgeWeights = false; continue; } if(isEdgeWeights){ String[] tokens = line.split("\\s+"); String fromId = "" + (fromIndex + 1); for(int i=0;i<tokens.length;i++){ double distance = Double.parseDouble(tokens[i]); String toId = "" + (i+1); costMatrixBuilder.addTransportDistance(fromId,toId,distance); costMatrixBuilder.addTransportTime(fromId, toId, distance); } fromIndex++; } } close(reader); }
#vulnerable code public void read(String matrixFile){ BufferedReader reader = getBufferedReader(matrixFile); String line; boolean isEdgeWeights = false; int fromIndex = 0; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("EDGE_WEIGHT_SECTION")){ isEdgeWeights = true; continue; } if(line.startsWith("DEMAND_SECTION")){ isEdgeWeights = false; continue; } if(isEdgeWeights){ String[] tokens = line.split("\\s+"); String fromId = "" + (fromIndex + 1); for(int i=0;i<tokens.length;i++){ double distance = Double.parseDouble(tokens[i]); String toId = "" + (i+1); costMatrixBuilder.addTransportDistance(fromId,toId,distance); costMatrixBuilder.addTransportTime(fromId, toId, distance); } fromIndex++; } } } #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 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 @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 HttpResponse execute() throws Exception { StringBuilder requestBody = new StringBuilder(); if (request.getEntity() != null) { String content = ObjectMapperSingleton.getContext(request.getEntity().getClass()).writer().writeValueAsString(request.getEntity()); requestBody.append(content); } else if (request.hasJson()) { requestBody.append(request.getJson()); } try { connection.setRequestMethod(request.getMethod().name()); if (requestBody.length() > 0) { System.out.println(requestBody.toString()); connection.setDoOutput(true); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(requestBody.toString().getBytes()); out.flush(); } byte[] data = ByteStreams.toByteArray(connection.getInputStream()); System.out.println(new String(data)); return HttpResponseImpl.wrap(connection.getHeaderFields(), connection.getResponseCode(), connection.getResponseMessage(), data); } catch (IOException ex) { ex.printStackTrace(); throw ex; } finally { connection.disconnect(); } }
#vulnerable code public HttpResponse execute() throws Exception { StringBuilder requestBody = new StringBuilder(); if (request.getEntity() != null) { String content = ObjectMapperSingleton.getContext(request.getEntity().getClass()).writer().writeValueAsString(request.getEntity()); requestBody.append(content); } else if (request.hasJson()) { requestBody.append(request.getJson()); } StringBuilder contentBuilder = new StringBuilder(); BufferedReader in = null; try { connection.setRequestMethod(request.getMethod().name()); if (requestBody.length() > 0) { System.out.println(requestBody.toString()); connection.setDoOutput(true); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(requestBody.toString().getBytes()); out.flush(); } in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { contentBuilder.append(inputLine); } } catch (IOException ex) { ex.printStackTrace(System.out); in = new BufferedReader(new InputStreamReader( connection.getErrorStream())); String inputLine; while ((inputLine = in.readLine()) != null) { contentBuilder.append(inputLine); } } finally { if (in != null) { in.close(); } } HttpResponseImpl responseImpl = HttpResponseImpl.wrap(connection.getHeaderFields(), connection.getResponseCode(), connection.getResponseMessage(), connection.getInputStream()); connection.disconnect(); return responseImpl; } #location 35 #vulnerability type RESOURCE_LEAK
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 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 @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 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 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 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 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 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 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 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 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 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 5 #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 52 #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 NULL_DEREFERENCE
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 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 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 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 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 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 @Test void customRegistryTest() { // given class Amount { @NotNull @Digits(integer = 12, fraction = 3) protected BigDecimal amount; } class DiscountEffect { @Digits(integer = 6, fraction = 4) protected BigDecimal percentage; protected Amount amount; @Digits(integer = 12, fraction = 3) protected BigDecimal quantity; @NotNull @DecimalMax("65535") @DecimalMin("1") protected Integer size; } class Discount { @NotNull @Size(min = 1) @Valid protected List<DiscountEffect> discountEffects; } CustomRandomizerRegistry registry = new CustomRandomizerRegistry(); registry.registerRandomizer(BigDecimal.class, new BigDecimalRangeRandomizer(new Double(5d), new Double(10d), Integer.valueOf(3))); registry.registerRandomizer(Integer.class, new IntegerRangeRandomizer(5, 10)); EasyRandomParameters parameters = new EasyRandomParameters() .randomizerRegistry(registry); EasyRandom easyRandom = new EasyRandom(parameters); // when Discount discount = easyRandom.nextObject(Discount.class); // then assertThat(discount.discountEffects) .isNotEmpty() .allSatisfy(discountEffect -> { assertThat(discountEffect).isNotNull(); assertThat(discountEffect.percentage).isBetween(new BigDecimal("5.000"), new BigDecimal("10.000")); assertThat(discountEffect.quantity).isBetween(new BigDecimal("5.000"), new BigDecimal("10.000")); assertThat(discountEffect.amount.amount).isBetween(new BigDecimal("5.000"), new BigDecimal("10.000")); assertThat(discountEffect.size).isBetween(5, 10); }); }
#vulnerable code @Test void customRegistryTest() { // given class Salary { @Digits(integer = 2, fraction = 2) // OSS developer salary.. :-) private BigDecimal amount; } EasyRandomParameters parameters = new EasyRandomParameters() .randomizerRegistry(new MyCustomBeanValidationRandomizerRegistry()); EasyRandom easyRandom = new EasyRandom(parameters); // when Salary salary = easyRandom.nextObject(Salary.class); // then assertThat(salary).isNotNull(); assertThat(salary.amount).isLessThanOrEqualTo(new BigDecimal("99.99")); } #location 18 #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 @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 @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 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 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 @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 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 @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.
#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(), sourceEncoding))); 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 = 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); } } #location 22 #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 { usePluginClassLoader = true; if (groovyVersionSupportsAction()) { logGroovyVersion("execute"); logPluginClasspath(); if (getLog().isDebugEnabled()) { try { getLog().debug("Project test classpath:\n" + project.getTestClasspathElements()); } catch (DependencyResolutionRequiredException e) { getLog().warn("Unable to log project test classpath", e); } } if (scripts == null || scripts.length == 0) { getLog().info("No scripts specified for execution. Skipping."); return; } final SecurityManager sm = System.getSecurityManager(); try { System.setSecurityManager(new NoExitSecurityManager()); // 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)); initializeProperties(); for (Object k : properties.keySet()) { String key = (String) k; ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.get(key)); } // 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; if (sourceEncoding != null) { reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); } else { 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 or the plugin?", 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); } finally { System.setSecurityManager(sm); } } else { getLog().error("Your Groovy version (" + getGroovyVersion() + ") doesn't support script execution. The minimum version of Groovy required is " + minGroovyVersion + ". Skipping script execution."); } }
#vulnerable code public void execute() throws MojoExecutionException, MojoFailureException { usePluginClassLoader = true; if (groovyVersionSupportsAction()) { logGroovyVersion("execute"); if (scripts == null || scripts.length == 0) { getLog().info("No scripts specified for execution. Skipping."); return; } final SecurityManager sm = System.getSecurityManager(); try { System.setSecurityManager(new NoExitSecurityManager()); // 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)); initializeProperties(); for (Object k : properties.keySet()) { String key = (String) k; ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.get(key)); } // 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; if (sourceEncoding != null) { reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); } else { 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 or the plugin?", 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); } finally { System.setSecurityManager(sm); } } else { getLog().error("Your Groovy version (" + getGroovyVersion() + ") doesn't support script execution. The minimum version of Groovy required is " + minGroovyVersion + ". Skipping script execution."); } } #location 38 #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 { if (groovyVersionSupportsAction()) { logGroovyVersion("execute"); if (scripts == null || scripts.length == 0) { getLog().info("No scripts specified for execution. Skipping."); return; } final SecurityManager sm = System.getSecurityManager(); try { System.setSecurityManager(new NoExitSecurityManager()); // 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)); initializeProperties(); for (Object k : properties.keySet()) { String key = (String) k; ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.get(key)); } // 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; if (sourceEncoding != null) { reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); } else { 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); } finally { System.setSecurityManager(sm); } } else { getLog().error("Your Groovy version (" + getGroovyVersion() + ") doesn't support script execution. The minimum version of Groovy required is " + minGroovyVersion + ". Skipping script execution."); } }
#vulnerable code public void execute() throws MojoExecutionException, MojoFailureException { if (groovyVersionSupportsAction()) { logGroovyVersion("execute"); if (scripts == null || scripts.length == 0) { getLog().info("No scripts specified for execution. Skipping."); return; } 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)); initializeProperties(); for (Object k : properties.keySet()) { String key = (String) k; ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.get(key)); } // 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; if (sourceEncoding != null) { reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); } else { 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); } } else { getLog().error("Your Groovy version (" + getGroovyVersion() + ") doesn't support script execution. The minimum version of Groovy required is " + minGroovyVersion + ". Skipping script execution."); } } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void read(SelectionKey key) throws Exception { SocketChannel channel = (SocketChannel) key.channel(); DataBuffer buf = buffers.get(channel); if (buf.readData(channel)) { InputStream is = new ByteArrayInputStream(buf.data); DataInputStream dis = new DataInputStream(is); AbstractDataReader reader = new DefaultDataReader(dis); DataBusProtocol.DistMLMessage req = DataBusProtocol.DistMLMessage.readDistMLMessage(reader, model); if (req instanceof DataBusProtocol.CloseRequest) {// worker disconnected try { key.cancel(); ((SocketChannel) key.channel()).socket().close(); } catch (IOException e){} log("client disconnected: " + ((SocketChannel) key.channel()).getRemoteAddress()); } else { DataBusProtocol.DistMLMessage res = handle(req); int len = res.sizeAsBytes(model); // ByteArrayOutputStream bdos = new ByteArrayOutputStream(len + 4); // DataOutputStream dos = new DataOutputStream(bdos); // dos.writeInt(len); // res.write(dos, model); buf.resBuf = ByteBuffer.allocate(len+4); AbstractDataWriter out = new ByteBufferDataWriter(buf.resBuf); out.writeInt(len); res.write(out, model); buf.resBuf.flip(); key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); //log("register with OP_WRITE: " + key + ", " + key.interestOps()); // channel.socket().getOutputStream().write(bdos.toByteArray()); } } }
#vulnerable code private void read(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); DataBuffer buf = buffers.get(channel); if (buf.readData(channel)) { InputStream is = new ByteArrayInputStream(buf.data); DataInputStream dis = new DataInputStream(is); DataBusProtocol.DistMLMessage req = DataBusProtocol.DistMLMessage.readDistMLMessage(dis, model); if (req instanceof DataBusProtocol.CloseRequest) {// worker disconnected try { key.cancel(); ((SocketChannel) key.channel()).socket().close(); } catch (IOException e){} log("client disconnected: " + ((SocketChannel) key.channel()).getRemoteAddress()); } else { DataBusProtocol.DistMLMessage res = handle(req); int len = res.sizeAsBytes(model); ByteArrayOutputStream bdos = new ByteArrayOutputStream(len + 4); DataOutputStream dos = new DataOutputStream(bdos); dos.writeInt(len); res.write(dos, model); buf.resBuf = ByteBuffer.allocate(len+4); buf.resBuf.put(bdos.toByteArray()); buf.resBuf.flip(); key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); //log("register with OP_WRITE: " + key + ", " + key.interestOps()); // channel.socket().getOutputStream().write(bdos.toByteArray()); } } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void parse(String[] args) { if(instance!=null) return; try { if (args.length != 1) { System.err.println("USAGE: configFile"); System.exit(2); } File zooCfgFile = new File(args[0]); if (!zooCfgFile.exists()) { LOG.error(zooCfgFile.toString() + " file is missing"); System.exit(2); } Properties cfg = new Properties(); FileInputStream zooCfgStream = new FileInputStream(zooCfgFile); try { cfg.load(zooCfgStream); } finally { zooCfgStream.close(); } ArrayList<QuorumServer> servers = new ArrayList<QuorumServer>(); String dataDir = null; String dataLogDir = null; int clientPort = 0; int tickTime = 0; int initLimit = 0; int syncLimit = 0; int electionAlg = 3; int electionPort = 2182; for (Entry<Object, Object> entry : cfg.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (key.equals("dataDir")) { dataDir = value; } else if (key.equals("dataLogDir")) { dataLogDir = value; } else if (key.equals("clientPort")) { clientPort = Integer.parseInt(value); } else if (key.equals("tickTime")) { tickTime = Integer.parseInt(value); } else if (key.equals("initLimit")) { initLimit = Integer.parseInt(value); } else if (key.equals("syncLimit")) { syncLimit = Integer.parseInt(value); } else if (key.equals("electionAlg")) { electionAlg = Integer.parseInt(value); } else if (key.equals("electionPort")) { electionPort = Integer.parseInt(value); } else if (key.startsWith("server.")) { int dot = key.indexOf('.'); long sid = Long.parseLong(key.substring(dot + 1)); String parts[] = value.split(":"); if (parts.length != 2) { LOG.error(value + " does not have the form host:port"); } InetSocketAddress addr = new InetSocketAddress(parts[0], Integer.parseInt(parts[1])); servers.add(new QuorumServer(sid, addr)); } else { System.setProperty("zookeeper." + key, value); } } if (dataDir == null) { LOG.error("dataDir is not set"); System.exit(2); } if (dataLogDir == null) { dataLogDir = dataDir; } else { if (!new File(dataLogDir).isDirectory()) { LOG.error("dataLogDir " + dataLogDir+ " is missing."); System.exit(2); } } if (clientPort == 0) { LOG.error("clientPort is not set"); System.exit(2); } if (tickTime == 0) { LOG.error("tickTime is not set"); System.exit(2); } if (servers.size() > 1 && initLimit == 0) { LOG.error("initLimit is not set"); System.exit(2); } if (servers.size() > 1 && syncLimit == 0) { LOG.error("syncLimit is not set"); System.exit(2); } QuorumPeerConfig conf = new QuorumPeerConfig(clientPort, dataDir, dataLogDir); conf.tickTime = tickTime; conf.initLimit = initLimit; conf.syncLimit = syncLimit; conf.electionAlg = electionAlg; conf.electionPort = electionPort; conf.servers = servers; if (servers.size() > 1) { File myIdFile = new File(dataDir, "myid"); if (!myIdFile.exists()) { LOG.error(myIdFile.toString() + " file is missing"); System.exit(2); } BufferedReader br = new BufferedReader(new FileReader(myIdFile)); String myIdString; try { myIdString = br.readLine(); } finally { br.close(); } try { conf.serverId = Long.parseLong(myIdString); } catch (NumberFormatException e) { LOG.error(myIdString + " is not a number"); System.exit(2); } } instance=conf; } catch (Exception e) { LOG.error("FIXMSG",e); System.exit(2); } }
#vulnerable code public static void parse(String[] args) { if(instance!=null) return; try { if (args.length != 1) { System.err.println("USAGE: configFile"); System.exit(2); } File zooCfgFile = new File(args[0]); if (!zooCfgFile.exists()) { LOG.error(zooCfgFile.toString() + " file is missing"); System.exit(2); } Properties cfg = new Properties(); cfg.load(new FileInputStream(zooCfgFile)); ArrayList<QuorumServer> servers = new ArrayList<QuorumServer>(); String dataDir = null; String dataLogDir = null; int clientPort = 0; int tickTime = 0; int initLimit = 0; int syncLimit = 0; int electionAlg = 3; int electionPort = 2182; for (Entry<Object, Object> entry : cfg.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (key.equals("dataDir")) { dataDir = value; } else if (key.equals("dataLogDir")) { dataLogDir = value; } else if (key.equals("clientPort")) { clientPort = Integer.parseInt(value); } else if (key.equals("tickTime")) { tickTime = Integer.parseInt(value); } else if (key.equals("initLimit")) { initLimit = Integer.parseInt(value); } else if (key.equals("syncLimit")) { syncLimit = Integer.parseInt(value); } else if (key.equals("electionAlg")) { electionAlg = Integer.parseInt(value); } else if (key.equals("electionPort")) { electionPort = Integer.parseInt(value); } else if (key.startsWith("server.")) { int dot = key.indexOf('.'); long sid = Long.parseLong(key.substring(dot + 1)); String parts[] = value.split(":"); if (parts.length != 2) { LOG.error(value + " does not have the form host:port"); } InetSocketAddress addr = new InetSocketAddress(parts[0], Integer.parseInt(parts[1])); servers.add(new QuorumServer(sid, addr)); } else { System.setProperty("zookeeper." + key, value); } } if (dataDir == null) { LOG.error("dataDir is not set"); System.exit(2); } if (dataLogDir == null) { dataLogDir = dataDir; } else { if (!new File(dataLogDir).isDirectory()) { LOG.error("dataLogDir " + dataLogDir+ " is missing."); System.exit(2); } } if (clientPort == 0) { LOG.error("clientPort is not set"); System.exit(2); } if (tickTime == 0) { LOG.error("tickTime is not set"); System.exit(2); } if (servers.size() > 1 && initLimit == 0) { LOG.error("initLimit is not set"); System.exit(2); } if (servers.size() > 1 && syncLimit == 0) { LOG.error("syncLimit is not set"); System.exit(2); } QuorumPeerConfig conf = new QuorumPeerConfig(clientPort, dataDir, dataLogDir); conf.tickTime = tickTime; conf.initLimit = initLimit; conf.syncLimit = syncLimit; conf.electionAlg = electionAlg; conf.electionPort = electionPort; conf.servers = servers; if (servers.size() > 1) { File myIdFile = new File(dataDir, "myid"); if (!myIdFile.exists()) { LOG.error(myIdFile.toString() + " file is missing"); System.exit(2); } BufferedReader br = new BufferedReader(new FileReader(myIdFile)); String myIdString = br.readLine(); try { conf.serverId = Long.parseLong(myIdString); } catch (NumberFormatException e) { LOG.error(myIdString + " is not a number"); System.exit(2); } } instance=conf; } catch (Exception e) { LOG.error("FIXMSG",e); System.exit(2); } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void ruok(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void ruok(String host, int port) { try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void dump(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void dump(String host, int port) { try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void kill(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void kill(String host, int port) { try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CppGenerator(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist, File outputDirectory) { this.outputDirectory = outputDirectory; mName = (new File(name)).getName(); mInclFiles = ilist; mRecList = rlist; }
#vulnerable code void genCode() throws IOException { outputDirectory.mkdirs(); FileWriter cc = new FileWriter(new File(outputDirectory, mName+".cc")); FileWriter hh = new FileWriter(new File(outputDirectory, mName+".hh")); hh.write("#ifndef __"+mName.toUpperCase().replace('.','_')+"__\n"); hh.write("#define __"+mName.toUpperCase().replace('.','_')+"__\n"); hh.write("#include \"recordio.hh\"\n"); for (Iterator i = mInclFiles.iterator(); i.hasNext();) { JFile f = (JFile) i.next(); hh.write("#include \""+f.getName()+".hh\"\n"); } cc.write("#include \""+mName+".hh\"\n"); for (Iterator i = mRecList.iterator(); i.hasNext();) { JRecord jr = (JRecord) i.next(); jr.genCppCode(hh, cc); } hh.write("#endif //"+mName.toUpperCase().replace('.','_')+"__\n"); hh.close(); cc.close(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CppGenerator(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist, File outputDirectory) { this.outputDirectory = outputDirectory; mName = (new File(name)).getName(); mInclFiles = ilist; mRecList = rlist; }
#vulnerable code void genCode() throws IOException { outputDirectory.mkdirs(); FileWriter cc = new FileWriter(new File(outputDirectory, mName+".cc")); FileWriter hh = new FileWriter(new File(outputDirectory, mName+".hh")); hh.write("#ifndef __"+mName.toUpperCase().replace('.','_')+"__\n"); hh.write("#define __"+mName.toUpperCase().replace('.','_')+"__\n"); hh.write("#include \"recordio.hh\"\n"); for (Iterator i = mInclFiles.iterator(); i.hasNext();) { JFile f = (JFile) i.next(); hh.write("#include \""+f.getName()+".hh\"\n"); } cc.write("#include \""+mName+".hh\"\n"); for (Iterator i = mRecList.iterator(); i.hasNext();) { JRecord jr = (JRecord) i.next(); jr.genCppCode(hh, cc); } hh.write("#endif //"+mName.toUpperCase().replace('.','_')+"__\n"); hh.close(); cc.close(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void ruok(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void ruok(String host, int port) { try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void getTraceMask(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv)); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void getTraceMask(String host, int port) { try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv)); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void kill(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void kill(String host, int port) { try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[4]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static void generateFile(File outputDir, int maj, int min, int micro, int rev, String buildDate) { String path = PACKAGE_NAME.replaceAll("\\.", "/"); File pkgdir = new File(outputDir, path); if (!pkgdir.exists()) { // create the pkg directory boolean ret = pkgdir.mkdirs(); if (!ret) { System.out.println("Cannnot create directory: " + path); System.exit(1); } } else if (!pkgdir.isDirectory()) { // not a directory System.out.println(path + " is not a directory."); System.exit(1); } File file = new File(pkgdir, TYPE_NAME + ".java"); FileWriter w = null; try { w = new FileWriter(file); w.write("// Do not edit!\n// File generated by org.apache.zookeeper" + ".version.util.VerGen.\n"); w.write("package " + PACKAGE_NAME + ";\n\n"); w.write("public interface " + TYPE_NAME + " {\n"); w.write(" public static final int MAJOR=" + maj + ";\n"); w.write(" public static final int MINOR=" + min + ";\n"); w.write(" public static final int MICRO=" + micro + ";\n"); w.write(" public static final int REVISION=" + rev + ";\n"); w.write(" public static final String BUILD_DATE=\"" + buildDate + "\";\n"); w.write("}\n"); } catch (IOException e) { System.out.println("Unable to generate version.Info file: " + e.getMessage()); System.exit(1); } finally { if (w != null) { try { w.close(); } catch (IOException e) { System.out.println("Unable to close file writer" + e.getMessage()); } } } }
#vulnerable code static void generateFile(File outputDir, int maj, int min, int micro, int rev, String buildDate) { String path = PACKAGE_NAME.replaceAll("\\.", "/"); File pkgdir = new File(outputDir, path); if (!pkgdir.exists()) { // create the pkg directory boolean ret = pkgdir.mkdirs(); if (!ret) { System.out.println("Cannnot create directory: " + path); System.exit(1); } } else if (!pkgdir.isDirectory()) { // not a directory System.out.println(path + " is not a directory."); System.exit(1); } File file = new File(pkgdir, TYPE_NAME + ".java"); try { FileWriter w = new FileWriter(file); w.write("// Do not edit!\n// File generated by org.apache.zookeeper" + ".version.util.VerGen.\n"); w.write("package " + PACKAGE_NAME + ";\n\n"); w.write("public interface " + TYPE_NAME + " {\n"); w.write(" public static final int MAJOR=" + maj + ";\n"); w.write(" public static final int MINOR=" + min + ";\n"); w.write(" public static final int MICRO=" + micro + ";\n"); w.write(" public static final int REVISION=" + rev + ";\n"); w.write(" public static final String BUILD_DATE=\"" + buildDate + "\";\n"); w.write("}\n"); w.close(); } catch (IOException e) { System.out.println("Unable to generate version.Info file: " + e.getMessage()); System.exit(1); } } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void dump(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void dump(String host, int port) { try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void shutdown() { synchronized (this) { finished = true; queuedRequests.clear(); notifyAll(); } nextProcessor.shutdown(); }
#vulnerable code public void shutdown() { finished = true; queuedRequests.clear(); synchronized (this) { notifyAll(); } nextProcessor.shutdown(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setTraceMask(String host, int port, String traceMaskStr) { Socket s = null; try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); long traceMask = Long.parseLong(traceMaskStr, 8); req.putInt(ByteBuffer.wrap("stmk".getBytes()).getInt()); req.putLong(traceMask); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv) + " masks=0" + Long.toOctalString(traceMask)); assert (retv == traceMask); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void setTraceMask(String host, int port, String traceMaskStr) { try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); long traceMask = Long.parseLong(traceMaskStr, 8); req.putInt(ByteBuffer.wrap("stmk".getBytes()).getInt()); req.putLong(traceMask); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv) + " masks=0" + Long.toOctalString(traceMask)); assert (retv == traceMask); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CGenerator(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist, File outputDirectory) { this.outputDirectory = outputDirectory; mName = (new File(name)).getName(); mInclFiles = ilist; mRecList = rlist; }
#vulnerable code void genCode() throws IOException { outputDirectory.mkdirs(); FileWriter c = new FileWriter(new File(outputDirectory, mName+".c")); FileWriter h = new FileWriter(new File(outputDirectory, mName+".h")); h.write("#ifndef __"+mName.toUpperCase().replace('.','_')+"__\n"); h.write("#define __"+mName.toUpperCase().replace('.','_')+"__\n"); h.write("#include \"recordio.h\"\n"); for (Iterator i = mInclFiles.iterator(); i.hasNext();) { JFile f = (JFile) i.next(); h.write("#include \""+f.getName()+".h\"\n"); } // required for compilation from C++ h.write("\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"); c.write("#include <stdlib.h>\n"); // need it for calloc() & free() c.write("#include \""+mName+".h\"\n\n"); for (Iterator i = mRecList.iterator(); i.hasNext();) { JRecord jr = (JRecord) i.next(); jr.genCCode(h, c); } h.write("\n#ifdef __cplusplus\n}\n#endif\n\n"); h.write("#endif //"+mName.toUpperCase().replace('.','_')+"__\n"); h.close(); c.close(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void getTraceMask(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv)); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void getTraceMask(String host, int port) { try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv)); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CGenerator(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist, File outputDirectory) { this.outputDirectory = outputDirectory; mName = (new File(name)).getName(); mInclFiles = ilist; mRecList = rlist; }
#vulnerable code void genCode() throws IOException { outputDirectory.mkdirs(); FileWriter c = new FileWriter(new File(outputDirectory, mName+".c")); FileWriter h = new FileWriter(new File(outputDirectory, mName+".h")); h.write("#ifndef __"+mName.toUpperCase().replace('.','_')+"__\n"); h.write("#define __"+mName.toUpperCase().replace('.','_')+"__\n"); h.write("#include \"recordio.h\"\n"); for (Iterator i = mInclFiles.iterator(); i.hasNext();) { JFile f = (JFile) i.next(); h.write("#include \""+f.getName()+".h\"\n"); } // required for compilation from C++ h.write("\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"); c.write("#include <stdlib.h>\n"); // need it for calloc() & free() c.write("#include \""+mName+".h\"\n\n"); for (Iterator i = mRecList.iterator(); i.hasNext();) { JRecord jr = (JRecord) i.next(); jr.genCCode(h, c); } h.write("\n#ifdef __cplusplus\n}\n#endif\n\n"); h.write("#endif //"+mName.toUpperCase().replace('.','_')+"__\n"); h.close(); c.close(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Vote lookForLeader() throws InterruptedException { HashMap<Long, Vote> recvset = new HashMap<Long, Vote>(); HashMap<Long, Vote> outofelection = new HashMap<Long, Vote>(); int notTimeout = finalizeWait; synchronized(this){ logicalclock++; updateProposal(self.getId(), self.getLastLoggedZxid()); } LOG.info("New election: " + proposedZxid); sendNotifications(); /* * Loop in which we exchange notifications until we find a leader */ while (self.getPeerState() == ServerState.LOOKING) { /* * Remove next notification from queue, times out after 2 times * the termination time */ Notification n = recvqueue.poll(notTimeout, TimeUnit.MILLISECONDS); /* * Sends more notifications if haven't received enough. * Otherwise processes new notification. */ if(n == null){ if(manager.haveDelivered()){ sendNotifications(); } else { manager.connectAll(); } /* * Exponential backoff */ int tmpTimeOut = notTimeout*2; notTimeout = (tmpTimeOut < maxNotificationInterval? tmpTimeOut : maxNotificationInterval); LOG.info("Notification time out: " + notTimeout); } else { //notTimeout = finalizeWait; switch (n.state) { case LOOKING: // If notification > current, replace and send messages out LOG.info("Notification: " + n.leader + ", " + n.zxid + ", " + n.epoch + ", " + self.getId() + ", " + self.getPeerState() + ", " + n.state + ", " + n.sid); if (n.epoch > logicalclock) { LOG.debug("Increasing logical clock: " + n.epoch); logicalclock = n.epoch; recvset.clear(); if(totalOrderPredicate(n.leader, n.zxid, self.getId(), self.getLastLoggedZxid())) updateProposal(n.leader, n.zxid); else updateProposal(self.getId(), self.getLastLoggedZxid()); sendNotifications(); } else if (n.epoch < logicalclock) { LOG.info("n.epoch < logicalclock"); break; } else if (totalOrderPredicate(n.leader, n.zxid, proposedLeader, proposedZxid)) { LOG.info("Updating proposal"); updateProposal(n.leader, n.zxid); sendNotifications(); } LOG.info("Adding vote"); recvset.put(n.sid, new Vote(n.leader, n.zxid, n.epoch)); //If have received from all nodes, then terminate if (self.quorumPeers.size() == recvset.size()) { self.setPeerState((proposedLeader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); leaveInstance(); return new Vote(proposedLeader, proposedZxid); } else if (termPredicate(recvset, new Vote(proposedLeader, proposedZxid, logicalclock))) { //Otherwise, wait for a fixed amount of time LOG.debug("Passed predicate"); // Verify if there is any change in the proposed leader while((n = recvqueue.poll(finalizeWait, TimeUnit.MILLISECONDS)) != null){ if(totalOrderPredicate(n.leader, n.zxid, proposedLeader, proposedZxid)){ recvqueue.put(n); break; } } if (n == null) { self.setPeerState((proposedLeader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); LOG.info("About to leave instance:" + proposedLeader + ", " + proposedZxid + ", " + self.getId() + ", " + self.getPeerState()); leaveInstance(); return new Vote(proposedLeader, proposedZxid); } } break; case LEADING: /* * There is at most one leader for each epoch, so if a peer claims to * be the leader for an epoch, then that peer must be the leader (no * arbitrary failures assumed). Now, if there is no quorum supporting * this leader, then processes will naturally move to a new epoch. */ if(n.epoch == logicalclock){ self.setPeerState((n.leader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); leaveInstance(); return new Vote(n.leader, n.zxid); } case FOLLOWING: LOG.info("Notification: " + n.leader + ", " + n.zxid + ", " + n.epoch + ", " + self.getId() + ", " + self.getPeerState() + ", " + n.state + ", " + n.sid); outofelection.put(n.sid, new Vote(n.leader, n.zxid, n.epoch, n.state)); if (termPredicate(outofelection, new Vote(n.leader, n.zxid, n.epoch, n.state)) && checkLeader(outofelection, n.leader, n.epoch)) { synchronized(this){ logicalclock = n.epoch; self.setPeerState((n.leader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); } leaveInstance(); return new Vote(n.leader, n.zxid); } break; default: break; } } } return null; }
#vulnerable code public Vote lookForLeader() throws InterruptedException { HashMap<Long, Vote> recvset = new HashMap<Long, Vote>(); HashMap<Long, Vote> outofelection = new HashMap<Long, Vote>(); int notTimeout = finalizeWait; synchronized(this){ logicalclock++; updateProposal(self.getId(), self.getLastLoggedZxid()); } LOG.info("New election: " + proposedZxid); sendNotifications(); /* * Loop in which we exchange notifications until we find a leader */ while (self.getPeerState() == ServerState.LOOKING) { /* * Remove next notification from queue, times out after 2 times * the termination time */ Notification n = recvqueue.poll(notTimeout, TimeUnit.MILLISECONDS); /* * Sends more notifications if haven't received enough. * Otherwise processes new notification. */ if(n == null){ if(manager.haveDelivered()){ sendNotifications(); } else { manager.connectAll(); } /* * Exponential backoff */ int tmpTimeOut = notTimeout*2; notTimeout = (tmpTimeOut < maxNotificationInterval? tmpTimeOut : maxNotificationInterval); LOG.info("Notification time out: " + notTimeout); } else { //notTimeout = finalizeWait; switch (n.state) { case LOOKING: // If notification > current, replace and send messages out LOG.info("Notification: " + n.leader + ", " + n.zxid + ", " + n.epoch + ", " + self.getId() + ", " + self.getPeerState() + ", " + n.state + ", " + n.sid); if (n.epoch > logicalclock) { logicalclock = n.epoch; recvset.clear(); if(totalOrderPredicate(n.leader, n.zxid, self.getId(), self.getLastLoggedZxid())) updateProposal(n.leader, n.zxid); else updateProposal(self.getId(), self.getLastLoggedZxid()); sendNotifications(); } else if (n.epoch < logicalclock) { LOG.info("n.epoch < logicalclock"); break; } else if (totalOrderPredicate(n.leader, n.zxid, proposedLeader, proposedZxid)) { LOG.info("Updating proposal"); updateProposal(n.leader, n.zxid); sendNotifications(); } LOG.info("Adding vote"); recvset.put(n.sid, new Vote(n.leader, n.zxid, n.epoch)); //If have received from all nodes, then terminate if (self.quorumPeers.size() == recvset.size()) { self.setPeerState((proposedLeader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); leaveInstance(); return new Vote(proposedLeader, proposedZxid); } else if (termPredicate(recvset, new Vote(proposedLeader, proposedZxid, logicalclock))) { //Otherwise, wait for a fixed amount of time LOG.debug("Passed predicate"); // Verify if there is any change in the proposed leader while((n = recvqueue.poll(finalizeWait, TimeUnit.MILLISECONDS)) != null){ if(totalOrderPredicate(n.leader, n.zxid, proposedLeader, proposedZxid)){ recvqueue.put(n); break; } } if (n == null) { self.setPeerState((proposedLeader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); LOG.info("About to leave instance:" + proposedLeader + ", " + proposedZxid + ", " + self.getId() + ", " + self.getPeerState()); leaveInstance(); return new Vote(proposedLeader, proposedZxid); } } break; case LEADING: /* * There is at most one leader for each epoch, so if a peer claims to * be the leader for an epoch, then that peer must be the leader (no * arbitrary failures assumed). Now, if there is no quorum supporting * this leader, then processes will naturally move to a new epoch. */ if(n.epoch == logicalclock){ self.setPeerState((n.leader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); leaveInstance(); return new Vote(n.leader, n.zxid); } case FOLLOWING: LOG.info("Notification: " + n.leader + ", " + n.zxid + ", " + n.epoch + ", " + self.getId() + ", " + self.getPeerState() + ", " + n.state + ", " + n.sid); outofelection.put(n.sid, new Vote(n.leader, n.zxid, n.epoch, n.state)); if (termPredicate(outofelection, new Vote(n.leader, n.zxid, n.epoch, n.state)) && checkLeader(outofelection, n.leader, n.epoch)) { synchronized(this){ logicalclock = n.epoch; self.setPeerState((n.leader == self.getId()) ? ServerState.LEADING: ServerState.FOLLOWING); } leaveInstance(); return new Vote(n.leader, n.zxid); } break; default: break; } } } return null; } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void dump(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void dump(String host, int port) { try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt()); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setTraceMask(String host, int port, String traceMaskStr) { Socket s = null; try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); long traceMask = Long.parseLong(traceMaskStr, 8); req.putInt(ByteBuffer.wrap("stmk".getBytes()).getInt()); req.putLong(traceMask); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv) + " masks=0" + Long.toOctalString(traceMask)); assert (retv == traceMask); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
#vulnerable code public static void setTraceMask(String host, int port, String traceMaskStr) { try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); long traceMask = Long.parseLong(traceMaskStr, 8); req.putInt(ByteBuffer.wrap("stmk".getBytes()).getInt()); req.putLong(traceMask); Socket s = null; s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[8]; int rc = is.read(resBytes); ByteBuffer res = ByteBuffer.wrap(resBytes); long retv = res.getLong(); System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv) + " masks=0" + Long.toOctalString(traceMask)); assert (retv == traceMask); } catch (IOException ioe) { LOG.warn("Unexpected exception", ioe); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code boolean initiateConnection(SocketChannel s, Long sid) { try { // Sending id and challenge byte[] msgBytes = new byte[8]; ByteBuffer msgBuffer = ByteBuffer.wrap(msgBytes); msgBuffer.putLong(self.getId()); msgBuffer.position(0); s.write(msgBuffer); } catch (IOException e) { LOG.warn("Exception reading or writing challenge: ", e); return false; } // If lost the challenge, then drop the new connection if (sid > self.getId()) { try { LOG.info("Have smaller server identifier, so dropping the connection: (" + sid + ", " + self.getId() + ")"); s.socket().close(); } catch (IOException e) { LOG.warn("Ignoring exception when closing socket or trying to " + "reopen connection: ", e); } // Otherwise proceed with the connection } else { SendWorker sw = new SendWorker(s, sid); RecvWorker rw = new RecvWorker(s, sid); sw.setRecv(rw); if (senderWorkerMap .containsKey(sid)) { SendWorker vsw = senderWorkerMap.get(sid); if(vsw != null) vsw.finish(); else LOG.error("No SendWorker for this identifier (" + sid + ")"); } else { LOG.error("Cannot open channel to server " + sid); } if (!queueSendMap.containsKey(sid)) { queueSendMap.put(sid, new ArrayBlockingQueue<ByteBuffer>( CAPACITY)); } senderWorkerMap.put(sid, sw); sw.start(); rw.start(); return true; } return false; }
#vulnerable code boolean initiateConnection(SocketChannel s, Long sid) { try { // Sending id and challenge byte[] msgBytes = new byte[8]; ByteBuffer msgBuffer = ByteBuffer.wrap(msgBytes); msgBuffer.putLong(self.getId()); msgBuffer.position(0); s.write(msgBuffer); } catch (IOException e) { LOG.warn("Exception reading or writing challenge: ", e); return false; } // If lost the challenge, then drop the new connection if (sid > self.getId()) { try { LOG.info("Have smaller server identifier, so dropping the connection: (" + sid + ", " + self.getId() + ")"); s.socket().close(); } catch (IOException e) { LOG.warn("Ignoring exception when closing socket or trying to " + "reopen connection: ", e); } // Otherwise proceed with the connection } else { SendWorker sw = new SendWorker(s, sid); RecvWorker rw = new RecvWorker(s, sid); sw.setRecv(rw); if (senderWorkerMap .containsKey(sid)) { SendWorker vsw = senderWorkerMap.get(sid); if(vsw != null) vsw.finish(); else LOG.error("No SendWorker for this identifier (" + sid + ")"); } if (!queueSendMap.containsKey(sid)) { queueSendMap.put(sid, new ArrayBlockingQueue<ByteBuffer>( CAPACITY)); } senderWorkerMap.put(sid, sw); sw.start(); rw.start(); return true; } return false; } #location 34 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close() { // unregister from JMX try { if(jmxConnectionBean != null){ MBeanRegistry.getInstance().unregister(jmxConnectionBean); } } catch (Exception e) { LOG.warn("Failed to unregister with JMX", e); } jmxConnectionBean = null; if (closed) { return; } closed = true; synchronized (factory.cnxns) { factory.cnxns.remove(this); } if (zk != null) { zk.removeCnxn(this); } LOG.info("closing session:0x" + Long.toHexString(sessionId) + " NIOServerCnxn: " + sock); try { /* * The following sequence of code is stupid! You would think that * only sock.close() is needed, but alas, it doesn't work that way. * If you just do sock.close() there are cases where the socket * doesn't actually close... */ sock.socket().shutdownOutput(); } catch (IOException e) { // This is a relatively common exception that we can't avoid LOG.debug("ignoring exception during output shutdown", e); } try { sock.socket().shutdownInput(); } catch (IOException e) { // This is a relatively common exception that we can't avoid LOG.debug("ignoring exception during input shutdown", e); } try { sock.socket().close(); } catch (IOException e) { LOG.warn("ignoring exception during socket close", e); } try { sock.close(); // XXX The next line doesn't seem to be needed, but some posts // to forums suggest that it is needed. Keep in mind if errors in // this section arise. // factory.selector.wakeup(); } catch (IOException e) { LOG.warn("ignoring exception during socketchannel close", e); } sock = null; if (sk != null) { try { // need to cancel this selection key from the selector sk.cancel(); } catch (Exception e) { LOG.warn("ignoring exception during selectionkey cancel", e); } } }
#vulnerable code public void close() { // unregister from JMX try { if(jmxConnectionBean != null){ MBeanRegistry.getInstance().unregister(jmxConnectionBean); } } catch (Exception e) { LOG.warn("Failed to unregister with JMX", e); } jmxConnectionBean = null; if (closed) { return; } closed = true; synchronized (factory.cnxns) { factory.cnxns.remove(this); } if (zk != null) { zk.removeCnxn(this); } ZooTrace.logTraceMessage(LOG, ZooTrace.SESSION_TRACE_MASK, "close NIOServerCnxn: " + sock); try { /* * The following sequence of code is stupid! You would think that * only sock.close() is needed, but alas, it doesn't work that way. * If you just do sock.close() there are cases where the socket * doesn't actually close... */ sock.socket().shutdownOutput(); } catch (IOException e) { // This is a relatively common exception that we can't avoid } try { sock.socket().shutdownInput(); } catch (IOException e) { LOG.warn("ignoring exception during input shutdown", e); } try { sock.socket().close(); } catch (IOException e) { LOG.warn("ignoring exception during socket close", e); } try { sock.close(); // XXX The next line doesn't seem to be needed, but some posts // to forums suggest that it is needed. Keep in mind if errors in // this section arise. // factory.selector.wakeup(); } catch (IOException e) { LOG.warn("ignoring exception during socketchannel close", e); } sock = null; if (sk != null) { try { // need to cancel this selection key from the selector sk.cancel(); } catch (Exception e) { LOG.warn("ignoring exception during selectionkey cancel", e); } } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") protected void onCommand(RTMPConnection conn, Channel channel, Header header, Notify notify) { super.onCommand(conn, channel, header, notify); System.out.println("onInvoke - header: " + header.toString() + " notify: " + notify.toString()); Object obj = notify.getCall().getArguments().length > 0 ? notify.getCall().getArguments()[0] : null; if (obj instanceof Map) { Map<String, String> map = (Map<String, String>) obj; String code = map.get("code"); if (StatusCodes.NS_PLAY_STOP.equals(code)) { finished = true; disconnect(); System.out.println("Disconnected"); } } }
#vulnerable code @SuppressWarnings("unchecked") protected void onCommand(RTMPConnection conn, Channel channel, Header header, Notify notify) { super.onCommand(conn, channel, header, notify); System.out.println("onInvoke, header = " + header.toString()); System.out.println("onInvoke, notify = " + notify.toString()); Object obj = notify.getCall().getArguments().length > 0 ? notify.getCall().getArguments()[0] : null; if (obj instanceof Map) { Map<String, String> map = (Map<String, String>) obj; String code = map.get("code"); if (StatusCodes.NS_PLAY_STOP.equals(code)) { synchronized (ClientTest.class) { finished = true; ClientTest.class.notifyAll(); } disconnect(); System.out.println("Disconnected"); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private KeyValuePair rdbLoadObject(int rdbtype) throws IOException { switch (rdbtype) { /* * | <content> | * | string contents | */ case RDB_TYPE_STRING: KeyStringValueString o0 = new KeyStringValueString(); EncodedString val = rdbLoadEncodedStringObject(); o0.setValueRdbType(rdbtype); o0.setValue(val.string); o0.setRawBytes(val.rawBytes); return o0; /* * | <len> | <content> | * | 1 or 5 bytes | string contents | */ case RDB_TYPE_LIST: long len = rdbLoadLen().len; KeyStringValueList<String> o1 = new KeyStringValueList<>(); List<String> list = new ArrayList<>(); for (int i = 0; i < len; i++) { String element = rdbLoadEncodedStringObject().string; list.add(element); } o1.setValueRdbType(rdbtype); o1.setValue(list); return o1; /* * | <len> | <content> | * | 1 or 5 bytes | string contents | */ case RDB_TYPE_SET: len = rdbLoadLen().len; KeyStringValueSet o2 = new KeyStringValueSet(); Set<String> set = new LinkedHashSet<>(); for (int i = 0; i < len; i++) { String element = rdbLoadEncodedStringObject().string; set.add(element); } o2.setValueRdbType(rdbtype); o2.setValue(set); return o2; /* * | <len> | <content> | <score> | * | 1 or 5 bytes | string contents | double content | */ case RDB_TYPE_ZSET: len = rdbLoadLen().len; KeyStringValueZSet o3 = new KeyStringValueZSet(); Set<ZSetEntry> zset = new LinkedHashSet<>(); while (len > 0) { String element = rdbLoadEncodedStringObject().string; double score = rdbLoadDoubleValue(); zset.add(new ZSetEntry(element, score)); len--; } o3.setValueRdbType(rdbtype); o3.setValue(zset); return o3; /* * | <len> | <content> | <score> | * | 1 or 5 bytes | string contents | binary double | */ case RDB_TYPE_ZSET_2: /* rdb version 8*/ len = rdbLoadLen().len; KeyStringValueZSet o5 = new KeyStringValueZSet(); zset = new LinkedHashSet<>(); while (len > 0) { String element = rdbLoadEncodedStringObject().string; double score = rdbLoadBinaryDoubleValue(); zset.add(new ZSetEntry(element, score)); len--; } o5.setValueRdbType(rdbtype); o5.setValue(zset); return o5; /* * | <len> | <content> | * | 1 or 5 bytes | string contents | */ case RDB_TYPE_HASH: len = rdbLoadLen().len; KeyStringValueHash o4 = new KeyStringValueHash(); Map<String, String> map = new LinkedHashMap<>(); while (len > 0) { String field = rdbLoadEncodedStringObject().string; String value = rdbLoadEncodedStringObject().string; map.put(field, value); len--; } o4.setValueRdbType(rdbtype); o4.setValue(map); return o4; /* * |<zmlen> | <len> |"foo" | <len> | <free> | "bar" |<zmend> | * | 1 byte | 1 or 5 byte | content |1 or 5 byte | 1 byte | content | 1 byte | */ case RDB_TYPE_HASH_ZIPMAP: ByteArray aux = rdbLoadPlainStringObject(); RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueHash o9 = new KeyStringValueHash(); map = new LinkedHashMap<>(); int zmlen = BaseRdbParser.LenHelper.zmlen(stream); while (true) { int zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream); if (zmEleLen == 255) { o9.setValueRdbType(rdbtype); o9.setValue(map); return o9; } String field = BaseRdbParser.StringHelper.str(stream, zmEleLen); zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream); if (zmEleLen == 255) { o9.setValueRdbType(rdbtype); o9.setValue(map); return o9; } int free = BaseRdbParser.LenHelper.free(stream); String value = BaseRdbParser.StringHelper.str(stream, zmEleLen); BaseRdbParser.StringHelper.skip(stream, free); map.put(field, value); } /* * |<encoding>| <length-of-contents>| <contents> | * | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element | */ case RDB_TYPE_SET_INTSET: aux = rdbLoadPlainStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueSet o11 = new KeyStringValueSet(); set = new LinkedHashSet<>(); int encoding = BaseRdbParser.LenHelper.encoding(stream); int lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream); for (int i = 0; i < lenOfContent; i++) { switch (encoding) { case 2: set.add(String.valueOf(stream.readInt(2))); break; case 4: set.add(String.valueOf(stream.readInt(4))); break; case 8: set.add(String.valueOf(stream.readLong(8))); break; default: throw new AssertionError("Expect encoding [2,4,8] but:" + encoding); } } o11.setValueRdbType(rdbtype); o11.setValue(set); return o11; /* * |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>| * | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte | */ case RDB_TYPE_LIST_ZIPLIST: aux = rdbLoadPlainStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueList<String> o10 = new KeyStringValueList<>(); list = new ArrayList<>(); int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream); int zltail = BaseRdbParser.LenHelper.zltail(stream); int zllen = BaseRdbParser.LenHelper.zllen(stream); for (int i = 0; i < zllen; i++) { list.add(BaseRdbParser.StringHelper.zipListEntry(stream)); } int zlend = BaseRdbParser.LenHelper.zlend(stream); if (zlend != 255) { throw new AssertionError("zlend expected 255 but " + zlend); } o10.setValueRdbType(rdbtype); o10.setValue(list); return o10; /* * |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>| * | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte | */ case RDB_TYPE_ZSET_ZIPLIST: aux = rdbLoadPlainStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueZSet o12 = new KeyStringValueZSet(); zset = new LinkedHashSet<>(); zlbytes = BaseRdbParser.LenHelper.zlbytes(stream); zltail = BaseRdbParser.LenHelper.zltail(stream); zllen = BaseRdbParser.LenHelper.zllen(stream); while (zllen > 0) { String element = BaseRdbParser.StringHelper.zipListEntry(stream); zllen--; double score = Double.valueOf(BaseRdbParser.StringHelper.zipListEntry(stream)); zllen--; zset.add(new ZSetEntry(element, score)); } zlend = BaseRdbParser.LenHelper.zlend(stream); if (zlend != 255) { throw new AssertionError("zlend expected 255 but " + zlend); } o12.setValueRdbType(rdbtype); o12.setValue(zset); return o12; /* * |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>| * | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte | */ case RDB_TYPE_HASH_ZIPLIST: aux = rdbLoadPlainStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueHash o13 = new KeyStringValueHash(); map = new LinkedHashMap<>(); zlbytes = BaseRdbParser.LenHelper.zlbytes(stream); zltail = BaseRdbParser.LenHelper.zltail(stream); zllen = BaseRdbParser.LenHelper.zllen(stream); while (zllen > 0) { String field = BaseRdbParser.StringHelper.zipListEntry(stream); zllen--; String value = BaseRdbParser.StringHelper.zipListEntry(stream); zllen--; map.put(field, value); } zlend = BaseRdbParser.LenHelper.zlend(stream); if (zlend != 255) { throw new AssertionError("zlend expected 255 but " + zlend); } o13.setValueRdbType(rdbtype); o13.setValue(map); return o13; /* rdb version 7*/ case RDB_TYPE_LIST_QUICKLIST: len = rdbLoadLen().len; KeyStringValueList<ByteArray> o14 = new KeyStringValueList<>(); List<ByteArray> byteList = new ArrayList<>(); for (int i = 0; i < len; i++) { ByteArray element = (ByteArray) rdbGenericLoadStringObject(RDB_LOAD_NONE); byteList.add(element); } o14.setValueRdbType(rdbtype); o14.setValue(byteList); return o14; case RDB_TYPE_MODULE: /* rdb version 8*/ //|6|6|6|6|6|6|6|6|6|10| char[] c = new char[9]; long moduleid = rdbLoadLen().len; keyStringValueModule o6 = new keyStringValueModule(); for (int i = 0; i < c.length; i++) { c[i] = MODULE_SET[(int) (moduleid & 63)]; moduleid >>>= 6; } String moduleName = new String(c); int moduleVersion = (int) (moduleid & 1023); ModuleHandler handler = lookupModuleHandler(moduleName,moduleVersion); o6.setValueRdbType(rdbtype); o6.setValue(handler.rdbLoad(in)); return o6; default: throw new AssertionError("Un-except value-type:" + rdbtype); } }
#vulnerable code private KeyValuePair rdbLoadObject(int rdbtype) throws IOException { switch (rdbtype) { /* * | <content> | * | string contents | */ case REDIS_RDB_TYPE_STRING: KeyStringValueString o0 = new KeyStringValueString(); EncodedString val = rdbLoadEncodedStringObject(); o0.setValueRdbType(rdbtype); o0.setValue(val.string); o0.setRawBytes(val.rawBytes); return o0; /* * | <len> | <content> | * | 1 or 5 bytes | string contents | */ case REDIS_RDB_TYPE_LIST: long len = rdbLoadLen().len; KeyStringValueList<String> o1 = new KeyStringValueList<>(); List<String> list = new ArrayList<>(); for (int i = 0; i < len; i++) { String element = rdbLoadEncodedStringObject().string; list.add(element); } o1.setValueRdbType(rdbtype); o1.setValue(list); return o1; /* * | <len> | <content> | * | 1 or 5 bytes | string contents | */ case REDIS_RDB_TYPE_SET: len = rdbLoadLen().len; KeyStringValueSet o2 = new KeyStringValueSet(); Set<String> set = new LinkedHashSet<>(); for (int i = 0; i < len; i++) { String element = rdbLoadEncodedStringObject().string; set.add(element); } o2.setValueRdbType(rdbtype); o2.setValue(set); return o2; /* * | <len> | <content> | <score> | * | 1 or 5 bytes | string contents | double content | */ case REDIS_RDB_TYPE_ZSET: len = rdbLoadLen().len; KeyStringValueZSet o3 = new KeyStringValueZSet(); Set<ZSetEntry> zset = new LinkedHashSet<>(); while (len > 0) { String element = rdbLoadEncodedStringObject().string; double score = rdbLoadDoubleValue(); zset.add(new ZSetEntry(element, score)); len--; } o3.setValueRdbType(rdbtype); o3.setValue(zset); return o3; /* * | <len> | <content> | <score> | * | 1 or 5 bytes | string contents | binary double | */ case REDIS_RDB_TYPE_ZSET_2: /* rdb version 8*/ len = rdbLoadLen().len; KeyStringValueZSet o5 = new KeyStringValueZSet(); zset = new LinkedHashSet<>(); while (len > 0) { String element = rdbLoadEncodedStringObject().string; double score = rdbLoadBinaryDoubleValue(); zset.add(new ZSetEntry(element, score)); len--; } o5.setValueRdbType(rdbtype); o5.setValue(zset); return o5; /* * | <len> | <content> | * | 1 or 5 bytes | string contents | */ case REDIS_RDB_TYPE_HASH: len = rdbLoadLen().len; KeyStringValueHash o4 = new KeyStringValueHash(); Map<String, String> map = new LinkedHashMap<>(); while (len > 0) { String field = rdbLoadEncodedStringObject().string; String value = rdbLoadEncodedStringObject().string; map.put(field, value); len--; } o4.setValueRdbType(rdbtype); o4.setValue(map); return o4; /* * |<zmlen> | <len> |"foo" | <len> | <free> | "bar" |<zmend> | * | 1 byte | 1 or 5 byte | content |1 or 5 byte | 1 byte | content | 1 byte | */ case REDIS_RDB_TYPE_HASH_ZIPMAP: ByteArray aux = rdbLoadRawStringObject(); RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueHash o9 = new KeyStringValueHash(); map = new LinkedHashMap<>(); int zmlen = BaseRdbParser.LenHelper.zmlen(stream); while (true) { int zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream); if (zmEleLen == 255) { o9.setValueRdbType(rdbtype); o9.setValue(map); return o9; } String field = BaseRdbParser.StringHelper.str(stream, zmEleLen); zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream); if (zmEleLen == 255) { o9.setValueRdbType(rdbtype); o9.setValue(map); return o9; } int free = BaseRdbParser.LenHelper.free(stream); String value = BaseRdbParser.StringHelper.str(stream, zmEleLen); BaseRdbParser.StringHelper.skip(stream, free); map.put(field, value); } /* * |<encoding>| <length-of-contents>| <contents> | * | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element | */ case REDIS_RDB_TYPE_SET_INTSET: aux = rdbLoadRawStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueSet o11 = new KeyStringValueSet(); set = new LinkedHashSet<>(); int encoding = BaseRdbParser.LenHelper.encoding(stream); int lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream); for (int i = 0; i < lenOfContent; i++) { switch (encoding) { case 2: set.add(String.valueOf(stream.readInt(2))); break; case 4: set.add(String.valueOf(stream.readInt(4))); break; case 8: set.add(String.valueOf(stream.readLong(8))); break; default: throw new AssertionError("Expect encoding [2,4,8] but:" + encoding); } } o11.setValueRdbType(rdbtype); o11.setValue(set); return o11; /* * |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>| * | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte | */ case REDIS_RDB_TYPE_LIST_ZIPLIST: aux = rdbLoadRawStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueList<String> o10 = new KeyStringValueList<>(); list = new ArrayList<>(); int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream); int zltail = BaseRdbParser.LenHelper.zltail(stream); int zllen = BaseRdbParser.LenHelper.zllen(stream); for (int i = 0; i < zllen; i++) { list.add(BaseRdbParser.StringHelper.zipListEntry(stream)); } int zlend = BaseRdbParser.LenHelper.zlend(stream); if (zlend != 255) { throw new AssertionError("zlend expected 255 but " + zlend); } o10.setValueRdbType(rdbtype); o10.setValue(list); return o10; /* * |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>| * | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte | */ case REDIS_RDB_TYPE_ZSET_ZIPLIST: aux = rdbLoadRawStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueZSet o12 = new KeyStringValueZSet(); zset = new LinkedHashSet<>(); zlbytes = BaseRdbParser.LenHelper.zlbytes(stream); zltail = BaseRdbParser.LenHelper.zltail(stream); zllen = BaseRdbParser.LenHelper.zllen(stream); while (zllen > 0) { String element = BaseRdbParser.StringHelper.zipListEntry(stream); zllen--; double score = Double.valueOf(BaseRdbParser.StringHelper.zipListEntry(stream)); zllen--; zset.add(new ZSetEntry(element, score)); } zlend = BaseRdbParser.LenHelper.zlend(stream); if (zlend != 255) { throw new AssertionError("zlend expected 255 but " + zlend); } o12.setValueRdbType(rdbtype); o12.setValue(zset); return o12; /* * |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>| * | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte | */ case REDIS_RDB_TYPE_HASH_ZIPLIST: aux = rdbLoadRawStringObject(); stream = new RedisInputStream(new ByteArrayInputStream(aux)); KeyStringValueHash o13 = new KeyStringValueHash(); map = new LinkedHashMap<>(); zlbytes = BaseRdbParser.LenHelper.zlbytes(stream); zltail = BaseRdbParser.LenHelper.zltail(stream); zllen = BaseRdbParser.LenHelper.zllen(stream); while (zllen > 0) { String field = BaseRdbParser.StringHelper.zipListEntry(stream); zllen--; String value = BaseRdbParser.StringHelper.zipListEntry(stream); zllen--; map.put(field, value); } zlend = BaseRdbParser.LenHelper.zlend(stream); if (zlend != 255) { throw new AssertionError("zlend expected 255 but " + zlend); } o13.setValueRdbType(rdbtype); o13.setValue(map); return o13; /* rdb version 7*/ case REDIS_RDB_TYPE_LIST_QUICKLIST: len = rdbLoadLen().len; KeyStringValueList<ByteArray> o14 = new KeyStringValueList<>(); List<ByteArray> byteList = new ArrayList<>(); for (int i = 0; i < len; i++) { ByteArray element = rdbLoadRawStringObject(); byteList.add(element); } o14.setValueRdbType(rdbtype); o14.setValue(byteList); return o14; case REDIS_RDB_TYPE_MODULE: /* rdb version 8*/ //|6|6|6|6|6|6|6|6|6|10| char[] c = new char[9]; long moduleid = rdbLoadLen().len; keyStringValueModule o6 = new keyStringValueModule(); for (int i = 0; i < c.length; i++) { c[i] = MODULE_SET[(int) (moduleid & 63)]; moduleid >>>= 6; } String moduleName = new String(c); int moduleVersion = (int) (moduleid & 1023); ModuleHandler handler = lookupModuleHandler(moduleName,moduleVersion); o6.setValueRdbType(rdbtype); o6.setValue(handler.rdbLoad(in)); return o6; default: throw new AssertionError("Un-except value-type:" + rdbtype); } } #location 109 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void open() throws IOException { try { doOpen(); } finally { close(); } }
#vulnerable code @Override public void open() throws IOException { for (int i = 0; i < configuration.getRetries() || configuration.getRetries() <= 0; i++) { try { connect(); if (configuration.getAuthPassword() != null) auth(configuration.getAuthPassword()); sendSlavePort(); sendSlaveIp(); sendSlaveCapa(); //reset retries i = 0; logger.info("PSYNC " + configuration.getMasterRunId() + " " + String.valueOf(configuration.getOffset())); send("PSYNC".getBytes(), configuration.getMasterRunId().getBytes(), String.valueOf(configuration.getOffset()).getBytes()); final String reply = (String) reply(); SyncMode syncMode = trySync(reply); //bug fix. if (syncMode == SyncMode.PSYNC && connected.get()) { //heart beat send REPLCONF ACK ${slave offset} synchronized (this) { heartBeat = new Timer("heart beat"); //bug fix. in this point closed by other thread. multi-thread issue heartBeat.schedule(new TimerTask() { @Override public void run() { try { send("REPLCONF".getBytes(), "ACK".getBytes(), String.valueOf(configuration.getOffset()).getBytes()); } catch (IOException e) { //NOP } } }, configuration.getHeartBeatPeriod(), configuration.getHeartBeatPeriod()); logger.info("heart beat started."); } } //sync command while (connected.get()) { Object obj = replyParser.parse(new OffsetHandler() { @Override public void handle(long len) { configuration.addOffset(len); } }); //command if (obj instanceof Object[]) { if (configuration.isVerbose() && logger.isDebugEnabled()) logger.debug(Arrays.deepToString((Object[]) obj)); Object[] command = (Object[]) obj; CommandName cmdName = CommandName.name((String) command[0]); Object[] params = new Object[command.length - 1]; System.arraycopy(command, 1, params, 0, params.length); final CommandParser<? extends Command> operations; //if command do not register. ignore if ((operations = commands.get(cmdName)) == null) continue; //do command replyParser Command parsedCommand = operations.parse(cmdName, params); //submit event this.submitEvent(parsedCommand); } else { if (logger.isInfoEnabled()) logger.info("Redis reply:" + obj); } } //connected = false break; } catch (/*bug fix*/IOException e) { //close socket manual if (!connected.get()) { break; } logger.error("socket error", e); //connect refused //connect timeout //read timeout //connect abort //server disconnect connection EOFException close(); //retry psync in next loop. logger.info("reconnect to redis-server. retry times:" + (i + 1)); try { Thread.sleep(configuration.getRetryTimeInterval()); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } } doCloseListener(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException, URISyntaxException { final OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("/path/to/dump.rdb"))); final RawByteListener rawByteListener = new RawByteListener() { @Override public void handle(byte... rawBytes) { try { out.write(rawBytes); } catch (IOException ignore) { } } }; //save rdb from remote server Replicator replicator = new RedisReplicator("redis://127.0.0.1:6379"); replicator.addRdbListener(new RdbListener() { @Override public void preFullSync(Replicator replicator) { replicator.addRawByteListener(rawByteListener); } @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { } @Override public void postFullSync(Replicator replicator, long checksum) { replicator.removeRawByteListener(rawByteListener); try { out.close(); replicator.close(); } catch (IOException ignore) { } } }); replicator.open(); //check rdb file replicator = new RedisReplicator("redis:///path/to/dump.rdb"); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { System.out.println(kv); } }); replicator.open(); }
#vulnerable code public static void main(String[] args) throws IOException { final FileOutputStream out = new FileOutputStream(new File("./src/test/resources/dump.rdb")); final RawByteListener rawByteListener = new RawByteListener() { @Override public void handle(byte... rawBytes) { try { out.write(rawBytes); } catch (IOException ignore) { } } }; //save rdb from remote server Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener() { @Override public void preFullSync(Replicator replicator) { replicator.addRawByteListener(rawByteListener); } @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { } @Override public void postFullSync(Replicator replicator, long checksum) { replicator.removeRawByteListener(rawByteListener); try { out.close(); replicator.close(); } catch (IOException ignore) { } } }); replicator.open(); //check rdb file replicator = new RedisReplicator(new File("./src/test/resources/dump.rdb"), FileType.RDB, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { System.out.println(kv); } }); replicator.open(); } #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 testSync() throws Exception { RedisReplicator replicator = new RedisReplicator(new File("dump.rdb")); replicator.addRdbFilter(new RdbFilter() { @Override public boolean accept(KeyValuePair<?> kv) { return kv.getKey().startsWith("SESSION"); } }); replicator.addRdbListener(new RdbListener() { @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { System.out.println(kv); } }); replicator.open(); //socket replicator = new RedisReplicator("127.0.0.1", 6379); replicator.addRdbListener(new RdbListener() { @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { System.out.println(kv); } }); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { System.out.println(command); } }); replicator.open(); }
#vulnerable code @Test public void testSync() throws Exception { RedisReplicator replicator = new RedisReplicator(RedisReplicatorTest.class.getClassLoader().getResourceAsStream("dump.rdb")); replicator.addRdbFilter(new RdbFilter() { @Override public boolean accept(KeyValuePair<?> kv) { return kv.getKey().startsWith("SESSION"); } }); replicator.addRdbListener(new RdbListener() { @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { System.out.println(kv); } }); replicator.open(); replicator.close(); //socket replicator = new RedisReplicator("127.0.0.1", 6379); replicator.addRdbListener(new RdbListener() { @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { System.out.println(kv); } }); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { System.out.println(command); } }); replicator.open(); } #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 testSsl1() throws IOException { // setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks"); // Replicator replicator = new RedisReplicator("localhost", 56379, // Configuration.defaultSetting().setSsl(true) // .setReadTimeout(0) // .setSslSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()) // .setHostnameVerifier(new BasicHostnameVerifier()) // .setSslParameters(new SSLParameters())); // final AtomicInteger acc = new AtomicInteger(0); // Jedis jedis = null; // try { // jedis = new Jedis("127.0.0.1", 6379); // jedis.set("ssl1", "true"); // } finally { // jedis.close(); // } // replicator.addRdbFilter(new RdbFilter() { // @Override // public boolean accept(KeyValuePair<?> kv) { // return kv.getKey().equals("ssl1"); // } // }); // replicator.addRdbListener(new RdbListener() { // @Override // public void preFullSync(Replicator replicator) { // } // // @Override // public void handle(Replicator replicator, KeyValuePair<?> kv) { // acc.incrementAndGet(); // } // // @Override // public void postFullSync(Replicator replicator, long checksum) { // Jedis jedis = null; // try { // jedis = new Jedis("127.0.0.1", 6379); // jedis.del("ssl1"); // } finally { // jedis.close(); // } // try { // replicator.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // }); // replicator.addCloseListener(new CloseListener() { // @Override // public void handle(Replicator replicator) { // System.out.println("close testSsl1"); // assertEquals(1, acc.get()); // } // }); // replicator.open(); }
#vulnerable code @Test public void testSsl1() throws IOException { setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks"); Replicator replicator = new RedisReplicator("localhost", 56379, Configuration.defaultSetting().setSsl(true) .setReadTimeout(0) .setSslSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()) .setHostnameVerifier(new BasicHostnameVerifier()) .setSslParameters(new SSLParameters())); final AtomicInteger acc = new AtomicInteger(0); Jedis jedis = null; try { jedis = new Jedis("127.0.0.1", 6379); jedis.set("ssl1", "true"); } finally { jedis.close(); } replicator.addRdbFilter(new RdbFilter() { @Override public boolean accept(KeyValuePair<?> kv) { return kv.getKey().equals("ssl1"); } }); replicator.addRdbListener(new RdbListener() { @Override public void preFullSync(Replicator replicator) { } @Override public void handle(Replicator replicator, KeyValuePair<?> kv) { acc.incrementAndGet(); } @Override public void postFullSync(Replicator replicator, long checksum) { Jedis jedis = null; try { jedis = new Jedis("127.0.0.1", 6379); jedis.del("ssl1"); } finally { jedis.close(); } try { replicator.close(); } catch (IOException e) { e.printStackTrace(); } } }); replicator.addCloseListener(new CloseListener() { @Override public void handle(Replicator replicator) { System.out.println("close testSsl1"); assertEquals(1, acc.get()); } }); replicator.open(); } #location 57 #vulnerability type RESOURCE_LEAK