output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#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
private void copyStylesheet(final File outputDirectory) {
getLog().info("Using stylesheet from " + stylesheetFile.getAbsolutePath() + ".");
try {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(stylesheetFile), stylesheetEncoding));
StringBuilder css = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
css.append(line).append("\n");
}
File outfile = new File(outputDirectory, "stylesheet.css");
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), stylesheetEncoding));
bufferedWriter.write(css.toString());
} finally {
FileUtils.closeQuietly(bufferedReader);
FileUtils.closeQuietly(bufferedWriter);
}
} catch (IOException e) {
getLog().warn("Unable to copy specified stylesheet (" + stylesheetFile.getAbsolutePath() + ").");
}
} | #vulnerable code
private void copyStylesheet(final File outputDirectory) {
getLog().info("Using stylesheet from " + stylesheetFile.getAbsolutePath() + ".");
Closer closer = Closer.create();
try {
try {
BufferedReader bufferedReader = closer.register(new BufferedReader(new InputStreamReader(new FileInputStream(stylesheetFile), stylesheetEncoding)));
StringBuilder css = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
css.append(line).append("\n");
}
File outfile = new File(outputDirectory, "stylesheet.css");
BufferedWriter bufferedWriter = closer.register(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), stylesheetEncoding)));
bufferedWriter.write(css.toString());
} catch (Throwable throwable) {
throw closer.rethrow(throwable);
} finally {
closer.close();
}
} catch (IOException e) {
getLog().warn("Unable to copy specified stylesheet (" + stylesheetFile.getAbsolutePath() + ").");
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onReceive(Object msg) {
if (msg instanceof DataBusProtocol.PartialDataRequest) {// Fetch partial parameters
DataBusProtocol.PartialDataRequest req = (DataBusProtocol.PartialDataRequest)msg;
Matrix data = model.getMatrix(req.matrixName).localCache;
KeyCollection rows = req.rows;
KeyCollection cols = req.cols;
log("partial data request received: " + req.matrixName + ", " + req.rows + ", " + rows);
if (rows instanceof KeyList) {
log("keylist size = " + rows.size());
}
Matrix result = data.subMatrix(rows, cols);
log("send data: " + result + ", row size = " + result.getRowKeys().size());
getSender().tell(new DataBusProtocol.Data(req.matrixName, result), getSelf());
} else if (msg instanceof DataBusProtocol.FetchDataRequest) { // Fetch parameters of one layer
DataBusProtocol.FetchDataRequest req = (DataBusProtocol.FetchDataRequest)msg;
Matrix data = model.getMatrix(req.matrixName).localCache;
log("data request received: " + data.getRowKeys());
getSender().tell(new DataBusProtocol.Data(req.matrixName, data), getSelf());
} else if (msg instanceof DataBusProtocol.PushDataRequest) {
log("update push request received.");
DataBusProtocol.PushDataRequest req = (DataBusProtocol.PushDataRequest)msg;
for (DataBusProtocol.Data update : req.dataList) {
if (req.initializeOnly) {
log("replacing local cache: " + update.data);
DMatrix m = model.getMatrix(update.matrixName);
if (m.localCache == null) {
m.setLocalCache(update.data);
}
else {
m.mergeMatrix(update.data);
}
}
else {
log("merge begin");
model.mergeUpdate(this.parameterServerIndex, update.matrixName, update.data);
log("merge done");
}
}
// Always return successful current now
getSender().tell(new DataBusProtocol.PushDataResponse(true), getSelf());
} else unhandled(msg);
} | #vulnerable code
@Override
public void onReceive(Object msg) {
if (msg instanceof DataBusProtocol.PartialDataRequest) {// Fetch partial parameters
DataBusProtocol.PartialDataRequest req = (DataBusProtocol.PartialDataRequest)msg;
Matrix data = model.getMatrix(req.matrixName).localCache;
KeyCollection rows = req.rows;
KeyCollection cols = req.cols;
log("partial data request received: " + req.matrixName + ", " + req.rows + ", " + rows);
if (rows instanceof KeyList) {
log("keylist size = " + rows.size());
}
Matrix result = data.subMatrix(rows, cols);
log("send data: " + result + ", row size = " + result.getRowKeys().size());
getSender().tell(new DataBusProtocol.Data(req.matrixName, result), getSelf());
} else if (msg instanceof DataBusProtocol.FetchDataRequest) { // Fetch parameters of one layer
DataBusProtocol.FetchDataRequest req = (DataBusProtocol.FetchDataRequest)msg;
Matrix data = model.getMatrix(req.matrixName).localCache;
log("data request received: " + data.getRowKeys());
getSender().tell(new DataBusProtocol.Data(req.matrixName, data), getSelf());
} else if (msg instanceof DataBusProtocol.PushDataRequest) {
log("update push request received.");
DataBusProtocol.PushDataRequest req = (DataBusProtocol.PushDataRequest)msg;
for (DataBusProtocol.Data update : req.dataList) {
if (req.replace) {
log("replacing local cache: " + update.data);
model.getMatrix(update.matrixName).setLocalCache(update.data);
}
else {
log("merge begin");
model.mergeUpdate(this.parameterServerIndex, update.matrixName, update.data);
log("merge done");
}
}
// Always return successful current now
getSender().tell(new DataBusProtocol.PushDataResponse(true), getSelf());
} else unhandled(msg);
}
#location 32
#vulnerability type NULL_DEREFERENCE | 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 List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
List<IScanIssue> issues = new ArrayList<IScanIssue>();
// Current insertion point
byte[] insertionPointBaseValue = insertionPoint.getBaseValue().getBytes();
int magicPos = helpers.indexOf(insertionPointBaseValue, serializeMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64 = helpers.indexOf(insertionPointBaseValue, base64Magic, false, 0, insertionPointBaseValue.length);
int magicPosAsciiHex = helpers.indexOf(insertionPointBaseValue, asciiHexMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64Gzip = helpers.indexOf(insertionPointBaseValue, base64GzipMagic, false, 0, insertionPointBaseValue.length);
int magicPosGzip = helpers.indexOf(insertionPointBaseValue, gzipMagic, false, 0, insertionPointBaseValue.length);
byte[] request = baseRequestResponse.getRequest();
IRequestInfo requestInfo = helpers.analyzeRequest(baseRequestResponse);
if(magicPos > -1 || magicPosBase64 > -1 || magicPosAsciiHex > -1 || magicPosBase64Gzip > -1 || magicPosGzip > -1) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = new HashMap<String,String>();
// URLDNS
if(enableActiveScanURLDNSChecks.isSelected()) {
String urlDnsCollaboratorUrl = collaboratorContext.generatePayload(true);
byte[] urldnsFinalPayload = createUrlDnsVector(payloadURLDNS,urlDnsCollaboratorUrl);
currentPayloads.put("URLDNS", urldnsFinalPayload);
dnsCollaboratorUrls.put("URLDNS", urlDnsCollaboratorUrl);
}
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
if(enableActiveScanDNSChecks.isSelected()) {
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload, currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newPayload = null;
if(magicPos > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = insertionPoint.buildRequest(newPayload);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
// Adding of marker for the vulnerability report
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStart = 0;
int markerEnd = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStart = helpers.indexOf(newRequest, helpers.urlEncode(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(currentPayloads.get(currentKey)).length;
}else if(magicPosBase64 > -1) {
markerStart = helpers.indexOf(newRequest, Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Base64.encodeBase64URLSafe(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded in Base64)";
} else if(magicPosAsciiHex > -1) {
markerStart = helpers.indexOf(newRequest, Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes()).length;
issueName = issueName + " (encoded in Ascii HEX)";
} else if(magicPosBase64Gzip > -1) {
//Need to use more comprehensive URL encoding as / doesn't get encoded
try {
markerStart = helpers.indexOf(newRequest, URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes().length;
issueName = issueName + " (encoded in Base64 and Gzipped)";
}
catch (Exception ex) {
stderr.println(ex.getMessage());
}
} else {
markerStart = helpers.indexOf(newRequest, gzipData(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(gzipData(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStart,markerEnd});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
else if(!urlBodyAlreadyScanned.contains(requestInfo.getUrl().toExternalForm())){ //Check for full body insertion point if not already tested
// Full body insertion point
int bodyOffset = requestInfo.getBodyOffset();
magicPos = helpers.indexOf(request, serializeMagic, false, 0, request.length);
magicPosBase64 = helpers.indexOf(request, base64Magic, false, 0, request.length);
magicPosAsciiHex = helpers.indexOf(request, asciiHexMagic, false, 0, request.length);
magicPosBase64Gzip = helpers.indexOf(request, base64GzipMagic, false, 0, request.length);
magicPosGzip = helpers.indexOf(request, gzipMagic, false, 0, request.length);
// Add the url to the urlBodyAlreadyScanned arraylist in order to avoid duplicate scanning of the body
urlBodyAlreadyScanned.add(requestInfo.getUrl().toExternalForm());
if((magicPos > -1 && magicPos == bodyOffset) || (magicPosBase64 > -1 && magicPosBase64 == bodyOffset) || (magicPosAsciiHex > -1 && magicPosAsciiHex == bodyOffset) || (magicPosBase64Gzip > -1 && magicPosBase64Gzip == bodyOffset) || (magicPosGzip > -1 && magicPosGzip == bodyOffset)) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = new HashMap<String,String>();
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
// URLDNS
if(enableActiveScanURLDNSChecks.isSelected()) {
String urlDnsCollaboratorUrl = collaboratorContext.generatePayload(true);
byte[] urldnsFinalPayload = createUrlDnsVector(payloadURLDNS,urlDnsCollaboratorUrl);
currentPayloads.put("URLDNS", urldnsFinalPayload);
dnsCollaboratorUrls.put("URLDNS", urlDnsCollaboratorUrl);
}
// DNS
if(enableActiveScanDNSChecks.isSelected()) {
//currentPayloads = new HashMap<String,byte[]>();
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload,currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
List<String> headers = requestInfo.getHeaders();
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newBody = null;
if(magicPos > -1) {
// Put directly the payload
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
// Encode the payload in Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
// Encode the payload in Ascii HEX
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
// Encode/compress the payload in Gzip and Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
// Encode/compress the payload with Gzip
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = helpers.buildHttpMessage(headers, newBody);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = (long)((((float)(endTime - startTime))) / 1000000000L); //divide by 1000000 to get milliseconds.
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStartPos = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStartPos = helpers.indexOf(newRequest, serializeMagic, false, 0, newRequest.length);
} else if(magicPosBase64 > -1) {
markerStartPos = helpers.indexOf(newRequest, base64Magic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64)";
} else if (magicPosAsciiHex > -1) {
markerStartPos = helpers.indexOf(newRequest, asciiHexMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Ascii HEX)";
} else if (magicPosBase64Gzip > -1) {
markerStartPos = helpers.indexOf(newRequest, base64GzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64 and Gzipped)";
} else {
markerStartPos = helpers.indexOf(newRequest, gzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStartPos,newRequest.length});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
}
if(issues.size() > 0) {
//stdout.println("Reporting " + issues.size() + " active results");
return issues;
} else {
return null;
}
} | #vulnerable code
public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
List<IScanIssue> issues = new ArrayList<IScanIssue>();
// Current insertion point
byte[] insertionPointBaseValue = insertionPoint.getBaseValue().getBytes();
int magicPos = helpers.indexOf(insertionPointBaseValue, serializeMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64 = helpers.indexOf(insertionPointBaseValue, base64Magic, false, 0, insertionPointBaseValue.length);
int magicPosAsciiHex = helpers.indexOf(insertionPointBaseValue, asciiHexMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64Gzip = helpers.indexOf(insertionPointBaseValue, base64GzipMagic, false, 0, insertionPointBaseValue.length);
int magicPosGzip = helpers.indexOf(insertionPointBaseValue, gzipMagic, false, 0, insertionPointBaseValue.length);
byte[] request = baseRequestResponse.getRequest();
IRequestInfo requestInfo = helpers.analyzeRequest(baseRequestResponse);
if(magicPos > -1 || magicPosBase64 > -1 || magicPosAsciiHex > -1 || magicPosBase64Gzip > -1 || magicPosGzip > -1) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = null;
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
if(enableActiveScanDNSChecks.isSelected()) {
//currentPayloads = new HashMap<String,byte[]>();
dnsCollaboratorUrls = new HashMap<String,String>();
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload, currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newPayload = null;
if(magicPos > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = insertionPoint.buildRequest(newPayload);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
// Adding of marker for the vulnerability report
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStart = 0;
int markerEnd = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStart = helpers.indexOf(newRequest, helpers.urlEncode(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(currentPayloads.get(currentKey)).length;
}else if(magicPosBase64 > -1) {
markerStart = helpers.indexOf(newRequest, Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Base64.encodeBase64URLSafe(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded in Base64)";
} else if(magicPosAsciiHex > -1) {
markerStart = helpers.indexOf(newRequest, Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes()).length;
issueName = issueName + " (encoded in Ascii HEX)";
} else if(magicPosBase64Gzip > -1) {
//Need to use more comprehensive URL encoding as / doesn't get encoded
try {
markerStart = helpers.indexOf(newRequest, URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes().length;
issueName = issueName + " (encoded in Base64 and Gzipped)";
}
catch (Exception ex) {
stderr.println(ex.getMessage());
}
} else {
markerStart = helpers.indexOf(newRequest, gzipData(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(gzipData(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStart,markerEnd});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
else if(!urlBodyAlreadyScanned.contains(requestInfo.getUrl().toExternalForm())){ //Check for full body insertion point if not already tested
// Full body insertion point
int bodyOffset = requestInfo.getBodyOffset();
magicPos = helpers.indexOf(request, serializeMagic, false, 0, request.length);
magicPosBase64 = helpers.indexOf(request, base64Magic, false, 0, request.length);
magicPosAsciiHex = helpers.indexOf(request, asciiHexMagic, false, 0, request.length);
magicPosBase64Gzip = helpers.indexOf(request, base64GzipMagic, false, 0, request.length);
magicPosGzip = helpers.indexOf(request, gzipMagic, false, 0, request.length);
// Add the url to the urlBodyAlreadyScanned arraylist in order to avoid duplicate scanning of the body
urlBodyAlreadyScanned.add(requestInfo.getUrl().toExternalForm());
if((magicPos > -1 && magicPos == bodyOffset) || (magicPosBase64 > -1 && magicPosBase64 == bodyOffset) || (magicPosAsciiHex > -1 && magicPosAsciiHex == bodyOffset) || (magicPosBase64Gzip > -1 && magicPosBase64Gzip == bodyOffset) || (magicPosGzip > -1 && magicPosGzip == bodyOffset)) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = null;
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
if(enableActiveScanDNSChecks.isSelected()) {
//currentPayloads = new HashMap<String,byte[]>();
dnsCollaboratorUrls = new HashMap<String,String>();
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload,currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
List<String> headers = requestInfo.getHeaders();
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newBody = null;
if(magicPos > -1) {
// Put directly the payload
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
// Encode the payload in Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
// Encode the payload in Ascii HEX
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
// Encode/compress the payload in Gzip and Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
// Encode/compress the payload with Gzip
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = helpers.buildHttpMessage(headers, newBody);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = (long)((((float)(endTime - startTime))) / 1000000000L); //divide by 1000000 to get milliseconds.
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStartPos = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStartPos = helpers.indexOf(newRequest, serializeMagic, false, 0, newRequest.length);
} else if(magicPosBase64 > -1) {
markerStartPos = helpers.indexOf(newRequest, base64Magic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64)";
} else if (magicPosAsciiHex > -1) {
markerStartPos = helpers.indexOf(newRequest, asciiHexMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Ascii HEX)";
} else if (magicPosBase64Gzip > -1) {
markerStartPos = helpers.indexOf(newRequest, base64GzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64 and Gzipped)";
} else {
markerStartPos = helpers.indexOf(newRequest, gzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStartPos,newRequest.length});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
}
if(issues.size() > 0) {
//stdout.println("Reporting " + issues.size() + " active results");
return issues;
} else {
return null;
}
}
#location 86
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
List<IScanIssue> issues = new ArrayList<IScanIssue>();
// Current insertion point
byte[] insertionPointBaseValue = insertionPoint.getBaseValue().getBytes();
int magicPos = helpers.indexOf(insertionPointBaseValue, serializeMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64 = helpers.indexOf(insertionPointBaseValue, base64Magic, false, 0, insertionPointBaseValue.length);
int magicPosAsciiHex = helpers.indexOf(insertionPointBaseValue, asciiHexMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64Gzip = helpers.indexOf(insertionPointBaseValue, base64GzipMagic, false, 0, insertionPointBaseValue.length);
int magicPosGzip = helpers.indexOf(insertionPointBaseValue, gzipMagic, false, 0, insertionPointBaseValue.length);
if(magicPos > -1 || magicPosBase64 > -1 || magicPosAsciiHex > -1 || magicPosBase64Gzip > -1 || magicPosGzip > -1) {
Set<String> payloadKeys = payloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newPayload = null;
if(magicPos > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPos),payloads.get(currentKey));
} else if(magicPosBase64 > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64),Base64.encodeBase64URLSafe(payloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosAsciiHex),Hex.encodeHexString(payloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64Gzip),Base64.encodeBase64(gzipData(payloads.get(currentKey))));
} else {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosGzip),gzipData(payloads.get(currentKey)));
}
byte[] newRequest = insertionPoint.buildRequest(newPayload);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
if(((int)duration) >= 10){
// Vulnerability founded
// Adding of marker for the vulnerability report
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStart = 0;
int markerEnd = 0;
String issueName = "";
if(magicPos > -1) {
markerStart = helpers.indexOf(newRequest, helpers.urlEncode(payloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(payloads.get(currentKey)).length;
issueName = activeScanIssue + currentKey;
}else if(magicPosBase64 > -1) {
markerStart = helpers.indexOf(newRequest, Base64.encodeBase64URLSafe(payloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Base64.encodeBase64URLSafe(payloads.get(currentKey))).length;
issueName = activeScanIssue + currentKey + " (encoded in Base64)";
} else if(magicPosAsciiHex > -1) {
markerStart = helpers.indexOf(newRequest, Hex.encodeHexString(payloads.get(currentKey)).getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Hex.encodeHexString(payloads.get(currentKey)).getBytes()).length;
issueName = activeScanIssue + currentKey + " (encoded in Ascii HEX)";
} else if(magicPosBase64Gzip > -1) {
//Need to use more comprehensive URL encoding as / doesn't get encoded
try {
markerStart = helpers.indexOf(newRequest, URLEncoder.encode(new String(Base64.encodeBase64(gzipData(payloads.get(currentKey)))), "UTF-8").getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + URLEncoder.encode(new String(Base64.encodeBase64(gzipData(payloads.get(currentKey)))), "UTF-8").getBytes().length;
issueName = activeScanIssue + currentKey + " (encoded in Base64 and Gzipped)";
}
catch (Exception ex) {
stderr.println(ex.getMessage());
}
} else {
markerStart = helpers.indexOf(newRequest, gzipData(payloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(gzipData(payloads.get(currentKey))).length;
issueName = activeScanIssue + currentKey + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStart,markerEnd});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + currentKey + ".",
activeScanRemediationDetail));
}
}
}
else { //Check for full body insertion point now
// Full body insertion point
byte[] request = baseRequestResponse.getRequest();
IRequestInfo requestInfo = helpers.analyzeRequest(request);
int bodyOffset = requestInfo.getBodyOffset();
magicPos = helpers.indexOf(request, serializeMagic, false, 0, request.length);
magicPosBase64 = helpers.indexOf(request, base64Magic, false, 0, request.length);
magicPosAsciiHex = helpers.indexOf(request, asciiHexMagic, false, 0, request.length);
magicPosBase64Gzip = helpers.indexOf(request, base64GzipMagic, false, 0, request.length);
magicPosGzip = helpers.indexOf(request, gzipMagic, false, 0, request.length);
if((magicPos > -1 && magicPos == bodyOffset) || (magicPosBase64 > -1 && magicPosBase64 == bodyOffset) || (magicPosAsciiHex > -1 && magicPosAsciiHex == bodyOffset) || (magicPosBase64Gzip > -1 && magicPosBase64Gzip == bodyOffset) || (magicPosGzip > -1 && magicPosGzip == bodyOffset)) {
List<String> headers = requestInfo.getHeaders();
Set<String> payloadKeys = payloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newBody = null;
if(magicPos > -1) {
// Put directly the payload
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPos),payloads.get(currentKey));
} else if(magicPosBase64 > -1) {
// Encode the payload in Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64),Base64.encodeBase64URLSafe(payloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
// Encode the payload in Ascii HEX
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosAsciiHex),Hex.encodeHexString(payloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
// Encode/compress the payload in Gzip and Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64Gzip),Base64.encodeBase64(gzipData(payloads.get(currentKey))));
} else {
// Encode/compress the payload with Gzip
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosGzip),gzipData(payloads.get(currentKey)));
}
byte[] newRequest = helpers.buildHttpMessage(headers, newBody);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = (long)((((float)(endTime - startTime))) / 1000000000L); //divide by 1000000 to get milliseconds.
if(((int)duration) >= 10){
// Vulnerability founded
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStartPos = 0;
String issueName = "";
if(magicPos > -1) {
markerStartPos = helpers.indexOf(newRequest, serializeMagic, false, 0, newRequest.length);
issueName = activeScanIssue + currentKey;
} else if(magicPosBase64 > -1) {
markerStartPos = helpers.indexOf(newRequest, base64Magic, false, 0, newRequest.length);
issueName = activeScanIssue + currentKey + " (encoded in Base64)";
} else if (magicPosAsciiHex > -1) {
markerStartPos = helpers.indexOf(newRequest, asciiHexMagic, false, 0, newRequest.length);
issueName = activeScanIssue + currentKey + " (encoded in Ascii HEX)";
} else if (magicPosBase64Gzip > -1) {
markerStartPos = helpers.indexOf(newRequest, base64GzipMagic, false, 0, newRequest.length);
issueName = activeScanIssue + currentKey + " (encoded in Base64 and Gzipped)";
} else {
markerStartPos = helpers.indexOf(newRequest, gzipMagic, false, 0, newRequest.length);
issueName = activeScanIssue + currentKey + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStartPos,newRequest.length});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + currentKey + ".",
activeScanRemediationDetail));
}
}
}
}
if(issues.size() > 0) {
//stdout.println("Reporting " + issues.size() + " active results");
return issues;
} else {
return null;
}
} | #vulnerable code
@Override
public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
List<IScanIssue> issues = new ArrayList<IScanIssue>();
stdout.println(insertionPoint.getBaseValue());
// Full body insertion point
byte[] request = baseRequestResponse.getRequest();
IRequestInfo requestInfo = helpers.analyzeRequest(request);
int bodyOffset = requestInfo.getBodyOffset();
int magicPos = helpers.indexOf(request, serializeMagic, false, 0, request.length);
int magicPosBase64 = helpers.indexOf(request, base64Magic, false, 0, request.length);
int magicPosAsciiHex = helpers.indexOf(request, asciiHexMagic, false, 0, request.length);
int magicPosBase64Gzip = helpers.indexOf(request, base64GzipMagic, false, 0, request.length);
int magicPosGzip = helpers.indexOf(request, gzipMagic, false, 0, request.length);
// if((magicPos > -1 && magicPos >= bodyOffset) || (magicPosBase64 > -1 && magicPosBase64 >= bodyOffset) || (magicPosAsciiHex > -1 && magicPosAsciiHex >= bodyOffset) || (magicPosBase64Gzip > -1 && magicPosBase64Gzip >= bodyOffset) || (magicPosGzip > -1 && magicPosGzip >= bodyOffset)) {
// List<String> headers = requestInfo.getHeaders();
// Set<String> payloadKeys = payloads.keySet();
// Iterator<String> iter = payloadKeys.iterator();
// String currentKey;
// while (iter.hasNext()) {
// currentKey = iter.next();
// byte[] newBody = null;
// if(magicPos > -1) {
// // Put directly the payload
// newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPos),payloads.get(currentKey));
// } else if(magicPosBase64 > -1) {
// // Encode the payload in Base64
// newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64),Base64.encodeBase64URLSafe(payloads.get(currentKey)));
// } else if(magicPosAsciiHex > -1) {
// // Encode the payload in Ascii HEX
// newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosAsciiHex),Hex.encodeHexString(payloads.get(currentKey)).getBytes());
// } else if(magicPosBase64Gzip > -1) {
// // Encode/compress the payload in Gzip and Base64
// newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64Gzip),helpers.urlEncode(Base64.encodeBase64(gzipData(payloads.get(currentKey)))));
// } else {
// // Encode/compress the payload with Gzip
// newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosGzip),gzipData(payloads.get(currentKey)));
// }
// byte[] newRequest = helpers.buildHttpMessage(headers, newBody);
// long startTime = System.nanoTime();
// IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
// long endTime = System.nanoTime();
// long duration = (long)((((float)(endTime - startTime))) / 1000000000L); //divide by 1000000 to get milliseconds.
// if(((int)duration) >= 10){
// // Vulnerability founded
// List<int[]> requestMarkers = new ArrayList<int[]>();
// int markerStartPos = 0;
// String issueName = "";
// if(magicPos > -1) {
// markerStartPos = helpers.indexOf(newRequest, serializeMagic, false, 0, newRequest.length);
// issueName = activeScanIssue + currentKey;
// } else if(magicPosBase64 > -1) {
// markerStartPos = helpers.indexOf(newRequest, base64Magic, false, 0, newRequest.length);
// issueName = activeScanIssue + currentKey + " (encoded in Base64)";
// } else if (magicPosAsciiHex > -1) {
// markerStartPos = helpers.indexOf(newRequest, asciiHexMagic, false, 0, newRequest.length);
// issueName = activeScanIssue + currentKey + " (encoded in Ascii HEX)";
// } else if (magicPosBase64Gzip > -1) {
// markerStartPos = helpers.indexOf(newRequest, base64GzipMagic, false, 0, newRequest.length);
// issueName = activeScanIssue + currentKey + " (encoded in Base64 and Gzipped)";
// } else {
// markerStartPos = helpers.indexOf(newRequest, gzipMagic, false, 0, newRequest.length);
// issueName = activeScanIssue + currentKey + " (encoded/compressed with Gzip)";
// }
// requestMarkers.add(new int[]{markerStartPos,newRequest.length});
// issues.add(new CustomScanIssue(
// baseRequestResponse.getHttpService(),
// helpers.analyzeRequest(baseRequestResponse).getUrl(),
// new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
// issueName,
// activeScanSeverity,
// activeScanConfidence,
// activeScanIssueDetail + currentKey + ".",
// activeScanRemediationDetail));
// }
// }
// }
// Current insertion point
byte[] insertionPointBaseValue = insertionPoint.getBaseValue().getBytes();
magicPos = helpers.indexOf(insertionPointBaseValue, serializeMagic, false, 0, insertionPointBaseValue.length);
magicPosBase64 = helpers.indexOf(insertionPointBaseValue, base64Magic, false, 0, insertionPointBaseValue.length);
magicPosAsciiHex = helpers.indexOf(insertionPointBaseValue, asciiHexMagic, false, 0, insertionPointBaseValue.length);
magicPosBase64Gzip = helpers.indexOf(insertionPointBaseValue, base64GzipMagic, false, 0, insertionPointBaseValue.length);
magicPosGzip = helpers.indexOf(insertionPointBaseValue, gzipMagic, false, 0, insertionPointBaseValue.length);
stdout.println(magicPosBase64Gzip);
if(magicPos > -1 || magicPosBase64 > -1 || magicPosAsciiHex > -1 || magicPosBase64Gzip > -1 || magicPosGzip > -1) {
Set<String> payloadKeys = payloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newPayload = null;
if(magicPos > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPos),payloads.get(currentKey));
} else if(magicPosBase64 > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64),Base64.encodeBase64URLSafe(payloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosAsciiHex),Hex.encodeHexString(payloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64Gzip),Base64.encodeBase64(gzipData(payloads.get(currentKey))));
} else {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosGzip),gzipData(payloads.get(currentKey)));
}
byte[] newRequest = insertionPoint.buildRequest(newPayload);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
if(((int)duration) >= 10){
// Vulnerability founded
stdout.println(new String(newRequest));
//stdout.println(new String(helpers.urlEncode(Base64.encodeBase64(gzipData(payloads.get(currentKey))))));
try {
stdout.println(URLEncoder.encode(new String(Base64.encodeBase64(gzipData(payloads.get(currentKey)))), "UTF-8"));
} catch (Exception ex) {
stderr.println(ex.getMessage());
}
// Adding of marker for the vulnerability report
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStart = 0;
int markerEnd = 0;
String issueName = "";
if(magicPos > -1) {
markerStart = helpers.indexOf(newRequest, helpers.urlEncode(payloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(payloads.get(currentKey)).length;
issueName = activeScanIssue + currentKey;
}else if(magicPosBase64 > -1) {
markerStart = helpers.indexOf(newRequest, Base64.encodeBase64URLSafe(payloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Base64.encodeBase64URLSafe(payloads.get(currentKey))).length;
issueName = activeScanIssue + currentKey + " (encoded in Base64)";
} else if(magicPosAsciiHex > -1) {
markerStart = helpers.indexOf(newRequest, Hex.encodeHexString(payloads.get(currentKey)).getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Hex.encodeHexString(payloads.get(currentKey)).getBytes()).length;
issueName = activeScanIssue + currentKey + " (encoded in Ascii HEX)";
} else if(magicPosBase64Gzip > -1) {
//Need to use more comprehensive URL encoding as / doesn't get encoded
try {
markerStart = helpers.indexOf(newRequest, URLEncoder.encode(new String(Base64.encodeBase64(gzipData(payloads.get(currentKey)))), "UTF-8").getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + URLEncoder.encode(new String(Base64.encodeBase64(gzipData(payloads.get(currentKey)))), "UTF-8").getBytes().length;
issueName = activeScanIssue + currentKey + " (encoded in Base64 and Gzipped)";
}
catch (Exception ex) {
stderr.println(ex.getMessage());
}
} else {
markerStart = helpers.indexOf(newRequest, gzipData(payloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(gzipData(payloads.get(currentKey))).length;
issueName = activeScanIssue + currentKey + " (encoded/compressed with Gzip)";
}
stdout.println(markerStart + " - " + markerEnd);
requestMarkers.add(new int[]{markerStart,markerEnd});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + currentKey + ".",
activeScanRemediationDetail));
}
}
}
if(issues.size() > 0) {
//stdout.println("Reporting " + issues.size() + " active results");
return issues;
} else {
return null;
}
}
#location 136
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
List<IScanIssue> issues = new ArrayList<IScanIssue>();
// Current insertion point
byte[] insertionPointBaseValue = insertionPoint.getBaseValue().getBytes();
int magicPos = helpers.indexOf(insertionPointBaseValue, serializeMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64 = helpers.indexOf(insertionPointBaseValue, base64Magic, false, 0, insertionPointBaseValue.length);
int magicPosAsciiHex = helpers.indexOf(insertionPointBaseValue, asciiHexMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64Gzip = helpers.indexOf(insertionPointBaseValue, base64GzipMagic, false, 0, insertionPointBaseValue.length);
int magicPosGzip = helpers.indexOf(insertionPointBaseValue, gzipMagic, false, 0, insertionPointBaseValue.length);
byte[] request = baseRequestResponse.getRequest();
IRequestInfo requestInfo = helpers.analyzeRequest(baseRequestResponse);
if(magicPos > -1 || magicPosBase64 > -1 || magicPosAsciiHex > -1 || magicPosBase64Gzip > -1 || magicPosGzip > -1) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = new HashMap<String,String>();
// URLDNS
if(enableActiveScanURLDNSChecks.isSelected()) {
String urlDnsCollaboratorUrl = collaboratorContext.generatePayload(true);
byte[] urldnsFinalPayload = createUrlDnsVector(payloadURLDNS,urlDnsCollaboratorUrl);
currentPayloads.put("URLDNS", urldnsFinalPayload);
dnsCollaboratorUrls.put("URLDNS", urlDnsCollaboratorUrl);
}
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
if(enableActiveScanDNSChecks.isSelected()) {
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload, currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newPayload = null;
if(magicPos > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = insertionPoint.buildRequest(newPayload);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
// Adding of marker for the vulnerability report
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStart = 0;
int markerEnd = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStart = helpers.indexOf(newRequest, helpers.urlEncode(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(currentPayloads.get(currentKey)).length;
}else if(magicPosBase64 > -1) {
markerStart = helpers.indexOf(newRequest, Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Base64.encodeBase64URLSafe(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded in Base64)";
} else if(magicPosAsciiHex > -1) {
markerStart = helpers.indexOf(newRequest, Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes()).length;
issueName = issueName + " (encoded in Ascii HEX)";
} else if(magicPosBase64Gzip > -1) {
//Need to use more comprehensive URL encoding as / doesn't get encoded
try {
markerStart = helpers.indexOf(newRequest, URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes().length;
issueName = issueName + " (encoded in Base64 and Gzipped)";
}
catch (Exception ex) {
stderr.println(ex.getMessage());
}
} else {
markerStart = helpers.indexOf(newRequest, gzipData(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(gzipData(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStart,markerEnd});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
else if(!urlBodyAlreadyScanned.contains(requestInfo.getUrl().toExternalForm())){ //Check for full body insertion point if not already tested
// Full body insertion point
int bodyOffset = requestInfo.getBodyOffset();
magicPos = helpers.indexOf(request, serializeMagic, false, 0, request.length);
magicPosBase64 = helpers.indexOf(request, base64Magic, false, 0, request.length);
magicPosAsciiHex = helpers.indexOf(request, asciiHexMagic, false, 0, request.length);
magicPosBase64Gzip = helpers.indexOf(request, base64GzipMagic, false, 0, request.length);
magicPosGzip = helpers.indexOf(request, gzipMagic, false, 0, request.length);
// Add the url to the urlBodyAlreadyScanned arraylist in order to avoid duplicate scanning of the body
urlBodyAlreadyScanned.add(requestInfo.getUrl().toExternalForm());
if((magicPos > -1 && magicPos == bodyOffset) || (magicPosBase64 > -1 && magicPosBase64 == bodyOffset) || (magicPosAsciiHex > -1 && magicPosAsciiHex == bodyOffset) || (magicPosBase64Gzip > -1 && magicPosBase64Gzip == bodyOffset) || (magicPosGzip > -1 && magicPosGzip == bodyOffset)) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = new HashMap<String,String>();
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
// URLDNS
if(enableActiveScanURLDNSChecks.isSelected()) {
String urlDnsCollaboratorUrl = collaboratorContext.generatePayload(true);
byte[] urldnsFinalPayload = createUrlDnsVector(payloadURLDNS,urlDnsCollaboratorUrl);
currentPayloads.put("URLDNS", urldnsFinalPayload);
dnsCollaboratorUrls.put("URLDNS", urlDnsCollaboratorUrl);
}
// DNS
if(enableActiveScanDNSChecks.isSelected()) {
//currentPayloads = new HashMap<String,byte[]>();
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload,currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
List<String> headers = requestInfo.getHeaders();
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newBody = null;
if(magicPos > -1) {
// Put directly the payload
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
// Encode the payload in Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
// Encode the payload in Ascii HEX
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
// Encode/compress the payload in Gzip and Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
// Encode/compress the payload with Gzip
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = helpers.buildHttpMessage(headers, newBody);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = (long)((((float)(endTime - startTime))) / 1000000000L); //divide by 1000000 to get milliseconds.
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStartPos = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStartPos = helpers.indexOf(newRequest, serializeMagic, false, 0, newRequest.length);
} else if(magicPosBase64 > -1) {
markerStartPos = helpers.indexOf(newRequest, base64Magic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64)";
} else if (magicPosAsciiHex > -1) {
markerStartPos = helpers.indexOf(newRequest, asciiHexMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Ascii HEX)";
} else if (magicPosBase64Gzip > -1) {
markerStartPos = helpers.indexOf(newRequest, base64GzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64 and Gzipped)";
} else {
markerStartPos = helpers.indexOf(newRequest, gzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStartPos,newRequest.length});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
}
if(issues.size() > 0) {
//stdout.println("Reporting " + issues.size() + " active results");
return issues;
} else {
return null;
}
} | #vulnerable code
public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
List<IScanIssue> issues = new ArrayList<IScanIssue>();
// Current insertion point
byte[] insertionPointBaseValue = insertionPoint.getBaseValue().getBytes();
int magicPos = helpers.indexOf(insertionPointBaseValue, serializeMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64 = helpers.indexOf(insertionPointBaseValue, base64Magic, false, 0, insertionPointBaseValue.length);
int magicPosAsciiHex = helpers.indexOf(insertionPointBaseValue, asciiHexMagic, false, 0, insertionPointBaseValue.length);
int magicPosBase64Gzip = helpers.indexOf(insertionPointBaseValue, base64GzipMagic, false, 0, insertionPointBaseValue.length);
int magicPosGzip = helpers.indexOf(insertionPointBaseValue, gzipMagic, false, 0, insertionPointBaseValue.length);
byte[] request = baseRequestResponse.getRequest();
IRequestInfo requestInfo = helpers.analyzeRequest(baseRequestResponse);
if(magicPos > -1 || magicPosBase64 > -1 || magicPosAsciiHex > -1 || magicPosBase64Gzip > -1 || magicPosGzip > -1) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = null;
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
if(enableActiveScanDNSChecks.isSelected()) {
//currentPayloads = new HashMap<String,byte[]>();
dnsCollaboratorUrls = new HashMap<String,String>();
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload, currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newPayload = null;
if(magicPos > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
newPayload = ArrayUtils.addAll(Arrays.copyOfRange(insertionPointBaseValue, 0, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = insertionPoint.buildRequest(newPayload);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS);
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
// Adding of marker for the vulnerability report
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStart = 0;
int markerEnd = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStart = helpers.indexOf(newRequest, helpers.urlEncode(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(currentPayloads.get(currentKey)).length;
}else if(magicPosBase64 > -1) {
markerStart = helpers.indexOf(newRequest, Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Base64.encodeBase64URLSafe(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded in Base64)";
} else if(magicPosAsciiHex > -1) {
markerStart = helpers.indexOf(newRequest, Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes()).length;
issueName = issueName + " (encoded in Ascii HEX)";
} else if(magicPosBase64Gzip > -1) {
//Need to use more comprehensive URL encoding as / doesn't get encoded
try {
markerStart = helpers.indexOf(newRequest, URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes(), false, 0, newRequest.length);
markerEnd = markerStart + URLEncoder.encode(new String(Base64.encodeBase64(gzipData(currentPayloads.get(currentKey)))), "UTF-8").getBytes().length;
issueName = issueName + " (encoded in Base64 and Gzipped)";
}
catch (Exception ex) {
stderr.println(ex.getMessage());
}
} else {
markerStart = helpers.indexOf(newRequest, gzipData(currentPayloads.get(currentKey)), false, 0, newRequest.length);
markerEnd = markerStart + helpers.urlEncode(gzipData(currentPayloads.get(currentKey))).length;
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStart,markerEnd});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
else if(!urlBodyAlreadyScanned.contains(requestInfo.getUrl().toExternalForm())){ //Check for full body insertion point if not already tested
// Full body insertion point
int bodyOffset = requestInfo.getBodyOffset();
magicPos = helpers.indexOf(request, serializeMagic, false, 0, request.length);
magicPosBase64 = helpers.indexOf(request, base64Magic, false, 0, request.length);
magicPosAsciiHex = helpers.indexOf(request, asciiHexMagic, false, 0, request.length);
magicPosBase64Gzip = helpers.indexOf(request, base64GzipMagic, false, 0, request.length);
magicPosGzip = helpers.indexOf(request, gzipMagic, false, 0, request.length);
// Add the url to the urlBodyAlreadyScanned arraylist in order to avoid duplicate scanning of the body
urlBodyAlreadyScanned.add(requestInfo.getUrl().toExternalForm());
if((magicPos > -1 && magicPos == bodyOffset) || (magicPosBase64 > -1 && magicPosBase64 == bodyOffset) || (magicPosAsciiHex > -1 && magicPosAsciiHex == bodyOffset) || (magicPosBase64Gzip > -1 && magicPosBase64Gzip == bodyOffset) || (magicPosGzip > -1 && magicPosGzip == bodyOffset)) {
// Collaborator context for DNS payloads
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
HashMap<String,byte[]> currentPayloads = new HashMap<String,byte[]>();
HashMap<String,String> dnsCollaboratorUrls = null;
// Sleep payloads
if(enableActiveScanSleepChecks.isSelected()) {
currentPayloads.putAll(payloadsSleep);
}
if(enableActiveScanDNSChecks.isSelected()) {
//currentPayloads = new HashMap<String,byte[]>();
dnsCollaboratorUrls = new HashMap<String,String>();
Set<String> payloadDnsKeys = payloadsDNS.keySet();
Iterator<String> iter = payloadDnsKeys.iterator();
String currentKey;
byte[] currentValue;
String currentCollaboratorPayload;
byte[] dnsPayloadWithCollaboratorPayload;
while (iter.hasNext()) {
currentKey = iter.next();
currentValue = payloadsDNS.get(currentKey);
currentCollaboratorPayload = collaboratorContext.generatePayload(true);
dnsPayloadWithCollaboratorPayload = createDnsVector(currentValue,currentCollaboratorPayload,currentKey);
currentPayloads.put(currentKey, dnsPayloadWithCollaboratorPayload);
dnsCollaboratorUrls.put(currentKey, currentCollaboratorPayload);
}
}
List<String> headers = requestInfo.getHeaders();
Set<String> payloadKeys = currentPayloads.keySet();
Iterator<String> iter = payloadKeys.iterator();
String currentKey;
while (iter.hasNext()) {
currentKey = iter.next();
byte[] newBody = null;
if(magicPos > -1) {
// Put directly the payload
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPos),currentPayloads.get(currentKey));
} else if(magicPosBase64 > -1) {
// Encode the payload in Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64),Base64.encodeBase64URLSafe(currentPayloads.get(currentKey)));
} else if(magicPosAsciiHex > -1) {
// Encode the payload in Ascii HEX
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosAsciiHex),Hex.encodeHexString(currentPayloads.get(currentKey)).getBytes());
} else if(magicPosBase64Gzip > -1) {
// Encode/compress the payload in Gzip and Base64
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosBase64Gzip),Base64.encodeBase64(gzipData(currentPayloads.get(currentKey))));
} else {
// Encode/compress the payload with Gzip
newBody = ArrayUtils.addAll(Arrays.copyOfRange(request, bodyOffset, magicPosGzip),gzipData(currentPayloads.get(currentKey)));
}
byte[] newRequest = helpers.buildHttpMessage(headers, newBody);
long startTime = System.nanoTime();
IHttpRequestResponse checkRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), newRequest);
long endTime = System.nanoTime();
long duration = (long)((((float)(endTime - startTime))) / 1000000000L); //divide by 1000000 to get milliseconds.
List<IBurpCollaboratorInteraction> collaboratorInteractions = null;
if(currentKey.contains("DNS")) {
collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(dnsCollaboratorUrls.get(currentKey));
}
if( (currentKey.contains("Sleep") && ((int)duration) >= 10 ) || (currentKey.contains("DNS") && collaboratorInteractions.size() > 0 ) ) {
// Vulnerability founded
List<int[]> requestMarkers = new ArrayList<int[]>();
int markerStartPos = 0;
String issueName = activeScanIssue + activeScanIssueVulnerableLibrary + currentKey;
if(magicPos > -1) {
markerStartPos = helpers.indexOf(newRequest, serializeMagic, false, 0, newRequest.length);
} else if(magicPosBase64 > -1) {
markerStartPos = helpers.indexOf(newRequest, base64Magic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64)";
} else if (magicPosAsciiHex > -1) {
markerStartPos = helpers.indexOf(newRequest, asciiHexMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Ascii HEX)";
} else if (magicPosBase64Gzip > -1) {
markerStartPos = helpers.indexOf(newRequest, base64GzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded in Base64 and Gzipped)";
} else {
markerStartPos = helpers.indexOf(newRequest, gzipMagic, false, 0, newRequest.length);
issueName = issueName + " (encoded/compressed with Gzip)";
}
requestMarkers.add(new int[]{markerStartPos,newRequest.length});
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { callbacks.applyMarkers(checkRequestResponse, requestMarkers, new ArrayList<int[]>()) },
issueName,
activeScanSeverity,
activeScanConfidence,
activeScanIssueDetail + activeScanIssueDetailVulnerableLibrary + currentKey + ".",
activeScanRemediationDetail));
}
}
}
}
if(issues.size() > 0) {
//stdout.println("Reporting " + issues.size() + " active results");
return issues;
} else {
return null;
}
}
#location 49
#vulnerability type NULL_DEREFERENCE | 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 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 18
#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 void commit(long zxid) {
lastCommitted = zxid;
QuorumPacket qp = new QuorumPacket(Leader.COMMIT, zxid, null, null);
sendPacket(qp);
} | #vulnerable code
public void commit(long zxid) {
lastCommitted = zxid;
QuorumPacket qp = new QuorumPacket(Leader.COMMIT, zxid, null, null);
sendPacket(qp);
if(pendingSyncs.containsKey(zxid)){
sendSync(syncHandler.get(pendingSyncs.get(zxid).sessionId), pendingSyncs.get(zxid));
syncHandler.remove(pendingSyncs.get(zxid));
pendingSyncs.remove(zxid);
}
}
#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 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 stat(String host, int port) {
Socket s = null;
try {
byte[] reqBytes = new byte[4];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("stat".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 stat(String host, int port) {
try {
byte[] reqBytes = new byte[4];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("stat".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 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 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.ipMap)
{
Set<NIOServerCnxn> s = factory.ipMap.get(sock.socket().getInetAddress());
s.remove(this);
}
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);
}
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);
}
}
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION | 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
public static void main(String[] args) throws IOException {
if(args.length<3 || args.length>4)
printUsage();
int i = 0;
File dataDir=new File(args[0]);
File snapDir=dataDir;
if(args.length==4){
i++;
snapDir=new File(args[i]);
}
i++; i++;
int num = Integer.parseInt(args[i]);
purge(dataDir, snapDir, num);
} | #vulnerable code
public static void main(String[] args) throws IOException {
if(args.length<1 || args.length>2)
printUsage();
File dataDir=new File(args[0]);
File snapDir=dataDir;
if(args.length==2){
snapDir=new File(args[1]);
}
FileTxnSnapLog txnLog = new FileTxnSnapLog(dataDir, snapDir);
// found any valid recent snapshots?
// files to exclude from deletion
Set<File> exc=new HashSet<File>();
File snapShot = txnLog.findMostRecentSnapshot();
exc.add(txnLog.findMostRecentSnapshot());
long zxid = Util.getZxidFromName(snapShot.getName(),"snapshot");
exc.addAll(Arrays.asList(txnLog.getSnapshotLogs(zxid)));
final Set<File> exclude=exc;
class MyFileFilter implements FileFilter{
private final String prefix;
MyFileFilter(String prefix){
this.prefix=prefix;
}
public boolean accept(File f){
if(!f.getName().startsWith(prefix) || exclude.contains(f))
return false;
return true;
}
}
// add all non-excluded log files
List<File> files=new ArrayList<File>(
Arrays.asList(dataDir.listFiles(new MyFileFilter("log."))));
// add all non-excluded snapshot files to the deletion list
files.addAll(Arrays.asList(snapDir.listFiles(new MyFileFilter("snapshot."))));
// remove the old files
for(File f: files)
{
System.out.println("Removing file: "+
DateFormat.getDateTimeInstance().format(f.lastModified())+
"\t"+f.getPath());
if(!f.delete()){
System.err.println("Failed to remove "+f.getPath());
}
}
}
#location 18
#vulnerability type NULL_DEREFERENCE | 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 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 29
#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 commit(long zxid) {
synchronized(this){
lastCommitted = zxid;
}
QuorumPacket qp = new QuorumPacket(Leader.COMMIT, zxid, null, null);
sendPacket(qp);
} | #vulnerable code
public void commit(long zxid) {
lastCommitted = zxid;
QuorumPacket qp = new QuorumPacket(Leader.COMMIT, zxid, null, null);
sendPacket(qp);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | 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 stat(String host, int port) {
Socket s = null;
try {
byte[] reqBytes = new byte[4];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("stat".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 stat(String host, int port) {
try {
byte[] reqBytes = new byte[4];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("stat".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 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 void snapshot() throws InterruptedException {
long lastZxid = dataTree.lastProcessedZxid;
ZooTrace.logTraceMessage(LOG, ZooTrace.getTextTraceLevel(),
"Snapshotting: zxid 0x" + Long.toHexString(lastZxid));
try {
File f = new File(dataDir, "snapshot." + Long.toHexString(lastZxid));
OutputStream sessOS = new BufferedOutputStream(new FileOutputStream(f));
try {
BinaryOutputArchive oa = BinaryOutputArchive.getArchive(sessOS);
snapshot(oa);
sessOS.flush();
} finally {
sessOS.close();
}
ZooTrace.logTraceMessage(LOG, ZooTrace.getTextTraceLevel(),
"Snapshotting finished: zxid 0x" + Long.toHexString(lastZxid));
} catch (IOException e) {
LOG.error("Severe error, exiting",e);
// This is a severe error that we cannot recover from,
// so we need to exit
System.exit(10);
}
} | #vulnerable code
public void snapshot() throws InterruptedException {
long lastZxid = dataTree.lastProcessedZxid;
ZooTrace.logTraceMessage(LOG, ZooTrace.getTextTraceLevel(),
"Snapshotting: zxid 0x" + Long.toHexString(lastZxid));
try {
File f =new File(dataDir, "snapshot." + Long.toHexString(lastZxid));
OutputStream sessOS = new BufferedOutputStream(new FileOutputStream(f));
BinaryOutputArchive oa = BinaryOutputArchive.getArchive(sessOS);
snapshot(oa);
sessOS.flush();
sessOS.close();
ZooTrace.logTraceMessage(LOG, ZooTrace.getTextTraceLevel(),
"Snapshotting finished: zxid 0x" + Long.toHexString(lastZxid));
} catch (IOException e) {
LOG.error("Severe error, exiting",e);
// This is a severe error that we cannot recover from,
// so we need to exit
System.exit(10);
}
}
#location 14
#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
public static void stat(String host, int port) {
Socket s = null;
try {
byte[] reqBytes = new byte[4];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("stat".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 stat(String host, int port) {
try {
byte[] reqBytes = new byte[4];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("stat".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
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 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 25
#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 13
#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 + ")");
}
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)) {
senderWorkerMap.get(sid).finish();
}
if (!queueSendMap.containsKey(sid)) {
queueSendMap.put(sid, new ArrayBlockingQueue<ByteBuffer>(
CAPACITY));
}
senderWorkerMap.put(sid, sw);
sw.start();
rw.start();
return true;
}
return false;
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private long getTopicLogSize(String topic, int pid) {
Option<Object> o = ZkUtils.getLeaderForPartition(zkClient, topic, pid);
if (o.isEmpty() || o.get() == null) {
log.error("No broker for partition %s - %s", topic, pid);
return 0;
}
Integer leaderId = Int.unbox(o.get());
SimpleConsumer consumer = consumerMap.get(leaderId);
if (consumer == null) {
consumer = createSimpleConsumer(leaderId);
}
// createSimpleConsumer may fail.
if (consumer == null) {
return 0;
}
consumerMap.put(leaderId, consumer);
TopicAndPartition topicAndPartition = new TopicAndPartition(topic, pid);
PartitionOffsetRequestInfo requestInfo = new PartitionOffsetRequestInfo(OffsetRequest.LatestTime(), 1);
OffsetRequest request = new OffsetRequest(
new Map1<TopicAndPartition, PartitionOffsetRequestInfo>(topicAndPartition, requestInfo),
0,
Request.OrdinaryConsumerId()
);
OffsetResponse response = consumer.getOffsetsBefore(request);
PartitionOffsetsResponse offsetsResponse = response.partitionErrorAndOffsets().get(topicAndPartition).get();
return scala.Long.unbox(offsetsResponse.offsets().head());
} | #vulnerable code
private long getTopicLogSize(String topic, int pid) {
Option<Object> o = ZkUtils.getLeaderForPartition(zkClient, topic, pid);
if (o.get() == null) {
log.error("No broker for partition %s - %s", topic, pid);
}
Integer leaderId = Int.unbox(o.get());
SimpleConsumer consumer = consumerMap.get(leaderId);
if (consumer == null) {
consumer = createSimpleConsumer(leaderId);
}
// createSimpleConsumer may fail.
if (consumer == null) {
return 0;
}
consumerMap.put(leaderId, consumer);
TopicAndPartition topicAndPartition = new TopicAndPartition(topic, pid);
PartitionOffsetRequestInfo requestInfo = new PartitionOffsetRequestInfo(OffsetRequest.LatestTime(), 1);
OffsetRequest request = new OffsetRequest(
new Map1<TopicAndPartition, PartitionOffsetRequestInfo>(topicAndPartition, requestInfo),
0,
Request.OrdinaryConsumerId()
);
OffsetResponse response = consumer.getOffsetsBefore(request);
PartitionOffsetsResponse offsetsResponse = response.partitionErrorAndOffsets().get(topicAndPartition).get();
return scala.Long.unbox(offsetsResponse.offsets().head());
}
#location 25
#vulnerability type NULL_DEREFERENCE | 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 {
//socket
RedisReplicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting());
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(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, Configuration.defaultSetting());
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 17
#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 {
// //socket
// final RedisReplicator replicator = new RedisReplicator("127.0.0.1",
// 6379,
// Configuration.defaultSetting()
// .setAuthPassword("test")
// .setRetries(0)
// .setVerbose(true));
// replicator.addRdbListener(new RdbListener.Adaptor() {
// @Override
// public void handle(Replicator replicator, KeyValuePair<?> kv) {
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// logger.debug(kv);
// }
// });
// replicator.addCommandListener(new CommandListener() {
// @Override
// public void handle(Replicator replicator, Command command) {
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// logger.debug(command);
// }
// });
// replicator.open();
} | #vulnerable code
@Test
public void testSync() throws Exception {
//socket
final RedisReplicator replicator = new RedisReplicator("127.0.0.1",
6379,
Configuration.defaultSetting()
.setAuthPassword("test")
.setRetries(0)
.setVerbose(true));
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.debug(kv);
}
});
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.debug(command);
}
});
replicator.open();
}
#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 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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applyListZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueList o10 = new KeyStringValueList();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
List<String> list = new ArrayList<>();
List<byte[]> rawList = 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++) {
byte[] e = BaseRdbParser.StringHelper.zipListEntry(stream);
list.add(new String(e, CHARSET));
rawList.add(e);
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o10.setValueRdbType(RDB_TYPE_LIST_ZIPLIST);
o10.setValue(list);
o10.setRawValue(rawList);
o10.setDb(db);
o10.setKey(new String(key, CHARSET));
o10.setRawKey(key);
return o10;
} | #vulnerable code
@Override
public Event applyListZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueList o10 = new KeyStringValueList();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
List<String> 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 expect 255 but " + zlend);
}
o10.setValueRdbType(RDB_TYPE_LIST_ZIPLIST);
o10.setValue(list);
o10.setDb(db);
o10.setKey(key);
return o10;
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void test() throws Exception {
String str = "sdajkl;jlqwjqejqweq89080c中jlxczksaouwq9823djadj";
ByteArray bytes = new ByteArray(str.getBytes().length, 10);
byte[] b1 = str.getBytes();
int i = 0;
for (byte b : b1) {
bytes.set(i, b);
assertEquals(b, bytes.get(i));
i++;
}
ByteArray bytes1 = new ByteArray(str.getBytes().length - 10, 10);
ByteArray.arraycopy(bytes, 10, bytes1, 0, bytes.length - 10);
assertEquals(str.substring(10), getString(bytes1));
str = "sdajk";
ByteArray bytes2 = new ByteArray(str.getBytes().length, 10);
b1 = str.getBytes();
i = 0;
for (byte b : b1) {
bytes2.set(i, b);
assertEquals(b, bytes2.get(i));
i++;
}
assertEquals(getString(bytes2), "sdajk");
ByteArray bytes3 = new ByteArray(bytes2.length() - 1, 10);
ByteArray.arraycopy(bytes2, 1, bytes3, 0, bytes2.length() - 1);
assertEquals(str.substring(1), getString(bytes3));
} | #vulnerable code
@Test
public void test() throws Exception {
String str = "sdajkl;jlqwjqejqweq89080c中jlxczksaouwq9823djadj";
ByteArray bytes = new ByteArray(str.getBytes().length, 10);
byte[] b1 = str.getBytes();
int i = 0;
for (byte b : b1) {
bytes.set(i, b);
assertEquals(b, bytes.get(i));
i++;
}
ByteArray bytes1 = new ByteArray(str.getBytes().length - 10, 10);
ByteArray.arraycopy(bytes, 10, bytes1, 0, bytes.length - 10);
assertEquals(str.substring(10), new String(bytes1.first()));
str = "sdajk";
ByteArray bytes2 = new ByteArray(str.getBytes().length, 10);
b1 = str.getBytes();
i = 0;
for (byte b : b1) {
bytes2.set(i, b);
assertEquals(b, bytes2.get(i));
i++;
}
assertEquals(new String(bytes2.first()), "sdajk");
ByteArray bytes3 = new ByteArray(bytes2.length() - 1, 10);
ByteArray.arraycopy(bytes2, 1, bytes3, 0, bytes2.length() - 1);
assertEquals(str.substring(1), new String(bytes3.first()));
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws IOException, URISyntaxException {
final OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("/path/to/appendonly.aof")));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
try {
out.write(rawBytes);
} catch (IOException ignore) {
}
}
};
//save 1000 records commands
Replicator replicator = new RedisReplicator("redis://127.0.0.1:6379");
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
replicator.addRawByteListener(rawByteListener);
}
});
final AtomicInteger acc = new AtomicInteger(0);
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
if (acc.incrementAndGet() == 1000) {
try {
out.close();
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
replicator.open();
//check aof file
replicator = new RedisReplicator("redis:///path/to/appendonly.aof");
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
System.out.println(command);
}
});
replicator.open();
} | #vulnerable code
public static void main(String[] args) throws IOException {
final FileOutputStream out = new FileOutputStream(new File("./src/test/resources/appendonly.aof"));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
try {
out.write(rawBytes);
} catch (IOException ignore) {
}
}
};
//save 1000 records commands
Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting());
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
replicator.addRawByteListener(rawByteListener);
}
});
final AtomicInteger acc = new AtomicInteger(0);
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
if (acc.incrementAndGet() == 1000) {
try {
out.close();
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
replicator.open();
//check aof file
replicator = new RedisReplicator(new File("./src/test/resources/appendonly.aof"), FileType.AOF, Configuration.defaultSetting());
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
System.out.println(command);
}
});
replicator.open();
}
#location 44
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applyZSetZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueZSet o12 = new KeyStringValueZSet();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<ZSetEntry> zset = new LinkedHashSet<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
byte[] element = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
double score = Double.valueOf(new String(BaseRdbParser.StringHelper.zipListEntry(stream), CHARSET));
zllen--;
zset.add(new ZSetEntry(new String(element, CHARSET), score, element));
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o12.setValueRdbType(RDB_TYPE_ZSET_ZIPLIST);
o12.setValue(zset);
o12.setDb(db);
o12.setKey(new String(key, CHARSET));
o12.setRawKey(key);
return o12;
} | #vulnerable code
@Override
public Event applyZSetZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueZSet o12 = new KeyStringValueZSet();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<ZSetEntry> zset = new LinkedHashSet<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int 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));
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o12.setValueRdbType(RDB_TYPE_ZSET_ZIPLIST);
o12.setValue(zset);
o12.setDb(db);
o12.setKey(key);
return o12;
}
#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 testSync() throws Exception {
//socket
RedisSocketReplicator replicator = new RedisSocketReplicator("127.0.0.1", 6379, Configuration.defaultSetting().setAuthPassword("test"));
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
});
replicator.open();
} | #vulnerable code
@Test
public void testSync() throws Exception {
//socket
RedisReplicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting());
replicator.open();
}
#location 5
#vulnerability type RESOURCE_LEAK | 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 36
#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 20
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applyListZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueList o10 = new KeyStringValueList();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
List<String> list = new ArrayList<>();
List<byte[]> rawList = 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++) {
byte[] e = BaseRdbParser.StringHelper.zipListEntry(stream);
list.add(new String(e, CHARSET));
rawList.add(e);
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o10.setValueRdbType(RDB_TYPE_LIST_ZIPLIST);
o10.setValue(list);
o10.setRawValue(rawList);
o10.setDb(db);
o10.setKey(new String(key, CHARSET));
o10.setRawKey(key);
return o10;
} | #vulnerable code
@Override
public Event applyListZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueList o10 = new KeyStringValueList();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
List<String> 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 expect 255 but " + zlend);
}
o10.setValueRdbType(RDB_TYPE_LIST_ZIPLIST);
o10.setValue(list);
o10.setDb(db);
o10.setKey(key);
return o10;
}
#location 20
#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 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applyHashZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueHash o13 = new KeyStringValueHash();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Map<String, String> map = new LinkedHashMap<>();
Map<byte[], byte[]> rawMap = new LinkedHashMap<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
byte[] field = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
byte[] value = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
map.put(new String(field, CHARSET), new String(value, CHARSET));
rawMap.put(field, value);
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o13.setValueRdbType(RDB_TYPE_HASH_ZIPLIST);
o13.setValue(map);
o13.setRawValue(rawMap);
o13.setDb(db);
o13.setKey(new String(key, CHARSET));
o13.setRawKey(key);
return o13;
} | #vulnerable code
@Override
public Event applyHashZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueHash o13 = new KeyStringValueHash();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Map<String, String> map = new LinkedHashMap<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int 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);
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o13.setValueRdbType(RDB_TYPE_HASH_ZIPLIST);
o13.setValue(map);
o13.setDb(db);
o13.setKey(key);
return o13;
}
#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 testChecksumV7() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV7.rdb"), FileType.RDB,
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
final AtomicLong atomicChecksum = new AtomicLong(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
atomicChecksum.compareAndSet(0, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testChecksumV7");
assertEquals(19, acc.get());
assertEquals(6576517133597126869L, atomicChecksum.get());
}
});
redisReplicator.open();
} | #vulnerable code
@Test
public void testChecksumV7() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV7.rdb"),
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
final AtomicLong atomicChecksum = new AtomicLong(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
atomicChecksum.compareAndSet(0, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testChecksumV7");
assertEquals(19, acc.get());
assertEquals(6576517133597126869L, atomicChecksum.get());
}
});
redisReplicator.open();
}
#location 28
#vulnerability type RESOURCE_LEAK | 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 36
#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 13
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void close() {
if (!connected.compareAndSet(true, false)) return;
synchronized (this) {
if (heartBeat != null) {
heartBeat.cancel();
heartBeat = null;
logger.info("heart beat canceled.");
}
}
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException e) {
//NOP
}
logger.info("channel closed");
} | #vulnerable code
@Override
public void close() {
if (!connected.compareAndSet(true, false)) return;
if (heartBeat != null) {
heartBeat.cancel();
heartBeat = null;
logger.info("heart beat canceled.");
}
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException e) {
//NOP
}
logger.info("channel closed");
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFilter() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV7.rdb"), FileType.RDB,
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void preFullSync(Replicator replicator) {
super.preFullSync(replicator);
assertEquals(0, acc.get());
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
if (kv.getValueRdbType() == 0) {
acc.incrementAndGet();
}
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFilter");
assertEquals(13, acc.get());
}
});
redisReplicator.open();
} | #vulnerable code
@Test
public void testFilter() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV7.rdb"),
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void preFullSync(Replicator replicator) {
super.preFullSync(replicator);
assertEquals(0, acc.get());
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
if (kv.getValueRdbType() == 0) {
acc.incrementAndGet();
}
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFilter");
assertEquals(13, acc.get());
}
});
redisReplicator.open();
}
#location 33
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void notify(byte... bytes) {
if (rawByteListeners == null || rawByteListeners.isEmpty()) return;
for (RawByteListener listener : rawByteListeners) {
listener.handle(bytes);
}
} | #vulnerable code
protected void notify(byte... bytes) {
if (listeners == null || listeners.isEmpty()) return;
for (RawByteListener listener : listeners) {
listener.handle(bytes);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
final Replicator replicator = new RedisReplicator("redis://127.0.0.1:6379");
replicator.addRdbListener(new RdbListener.Adaptor() {
@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
public static void main(String[] args) throws IOException {
final Replicator replicator = new RedisReplicator(
"127.0.0.1", 6379,
Configuration.defaultSetting());
replicator.addRdbListener(new RdbListener.Adaptor() {
@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 20
#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 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFileV8() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV8.rdb"), FileType.RDB,
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV8");
assertEquals(92499, acc.get());
}
});
redisReplicator.open();
} | #vulnerable code
@Test
public void testFileV8() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV8.rdb"),
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV8");
assertEquals(92499, acc.get());
}
});
redisReplicator.open();
}
#location 26
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applyHashZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueHash o13 = new KeyStringValueHash();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Map<String, String> map = new LinkedHashMap<>();
Map<byte[], byte[]> rawMap = new LinkedHashMap<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
byte[] field = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
byte[] value = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
map.put(new String(field, CHARSET), new String(value, CHARSET));
rawMap.put(field, value);
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o13.setValueRdbType(RDB_TYPE_HASH_ZIPLIST);
o13.setValue(map);
o13.setRawValue(rawMap);
o13.setDb(db);
o13.setKey(new String(key, CHARSET));
o13.setRawKey(key);
return o13;
} | #vulnerable code
@Override
public Event applyHashZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueHash o13 = new KeyStringValueHash();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Map<String, String> map = new LinkedHashMap<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int 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);
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o13.setValueRdbType(RDB_TYPE_HASH_ZIPLIST);
o13.setValue(map);
o13.setDb(db);
o13.setKey(key);
return o13;
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
Replicator r = new RedisReplicator("redis:///path/to/dump.rdb");
r.setRdbVisitor(new ValueIterableRdbVisitor(r));
r.addRdbListener(new HugeKVRdbListener(200) {
@Override
public void handleString(boolean last, byte[] key, byte[] value, int type) {
// your business code goes here.
}
@Override
public void handleModule(boolean last, byte[] key, Module value, int type) {
// your business code goes here.
}
@Override
public void handleList(boolean last, byte[] key, List<byte[]> list, int type) {
// your business code goes here.
}
@Override
public void handleZSetEntry(boolean last, byte[] key, List<ZSetEntry> list, int type) {
// your business code goes here.
}
@Override
public void handleMap(boolean last, byte[] key, List<Map.Entry<byte[], byte[]>> list, int type) {
// your business code goes here.
}
});
r.open();
} | #vulnerable code
public static void main(String[] args) throws IOException {
Replicator r = new RedisReplicator(new File("./src/test/resources/dumpV7.rdb"), FileType.RDB, Configuration.defaultSetting());
r.setRdbVisitor(new ValueIterableRdbVisitor(r));
r.addRdbListener(new HugeKVRdbListener(200) {
@Override
public void handleString(boolean last, byte[] key, byte[] value, int type) {
// your business code goes here.
}
@Override
public void handleModule(boolean last, byte[] key, Module value, int type) {
// your business code goes here.
}
@Override
public void handleList(boolean last, byte[] key, List<byte[]> list, int type) {
// your business code goes here.
}
@Override
public void handleZSetEntry(boolean last, byte[] key, List<ZSetEntry> list, int type) {
// your business code goes here.
}
@Override
public void handleMap(boolean last, byte[] key, List<Map.Entry<byte[], byte[]>> list, int type) {
// your business code goes here.
}
});
r.open();
}
#location 30
#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 19
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void template(String filename, final ConcurrentHashMap<String, KeyValuePair> map) {
try {
Replicator replicator = new RedisReplicator(RdbParserTest.class.
getClassLoader().getResourceAsStream(filename)
, FileType.RDB, Configuration.defaultSetting());
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
map.put(kv.getKey(), kv);
}
});
replicator.open();
} catch (Exception e) {
TestCase.fail();
}
} | #vulnerable code
public void template(String filename, final ConcurrentHashMap<String, KeyValuePair> map) {
try {
Replicator replicator = new RedisReplicator(RdbParserTest.class.
getClassLoader().getResourceAsStream(filename)
, Configuration.defaultSetting());
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
map.put(kv.getKey(), kv);
}
});
replicator.open();
} catch (Exception e) {
TestCase.fail();
}
}
#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 testFileV7() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV7.rdb"), FileType.RDB,
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
if (kv.getKey().equals("abcd")) {
KeyStringValueString ksvs = (KeyStringValueString) kv;
assertEquals("abcd", ksvs.getValue());
}
if (kv.getKey().equals("foo")) {
KeyStringValueString ksvs = (KeyStringValueString) kv;
assertEquals("bar", ksvs.getValue());
}
if (kv.getKey().equals("aaa")) {
KeyStringValueString ksvs = (KeyStringValueString) kv;
assertEquals("bbb", ksvs.getValue());
}
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
assertEquals(19, acc.get());
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV7");
assertEquals(19, acc.get());
}
});
redisReplicator.open();
} | #vulnerable code
@Test
public void testFileV7() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV7.rdb"),
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
if (kv.getKey().equals("abcd")) {
KeyStringValueString ksvs = (KeyStringValueString) kv;
assertEquals("abcd", ksvs.getValue());
}
if (kv.getKey().equals("foo")) {
KeyStringValueString ksvs = (KeyStringValueString) kv;
assertEquals("bar", ksvs.getValue());
}
if (kv.getKey().equals("aaa")) {
KeyStringValueString ksvs = (KeyStringValueString) kv;
assertEquals("bbb", ksvs.getValue());
}
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
assertEquals(19, acc.get());
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV7");
assertEquals(19, acc.get());
}
});
redisReplicator.open();
}
#location 38
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applyZSetZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueZSet o12 = new KeyStringValueZSet();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<ZSetEntry> zset = new LinkedHashSet<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
byte[] element = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
double score = Double.valueOf(new String(BaseRdbParser.StringHelper.zipListEntry(stream), CHARSET));
zllen--;
zset.add(new ZSetEntry(new String(element, CHARSET), score, element));
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o12.setValueRdbType(RDB_TYPE_ZSET_ZIPLIST);
o12.setValue(zset);
o12.setDb(db);
o12.setKey(new String(key, CHARSET));
o12.setRawKey(key);
return o12;
} | #vulnerable code
@Override
public Event applyZSetZipList(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueZSet o12 = new KeyStringValueZSet();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<ZSetEntry> zset = new LinkedHashSet<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int 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));
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expect 255 but " + zlend);
}
o12.setValueRdbType(RDB_TYPE_ZSET_ZIPLIST);
o12.setValue(zset);
o12.setDb(db);
o12.setKey(key);
return o12;
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void close() {
if (!connected.compareAndSet(true, false)) return;
synchronized (this) {
if (heartBeat != null) {
heartBeat.cancel();
heartBeat = null;
logger.info("heart beat canceled.");
}
}
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException e) {
//NOP
}
logger.info("channel closed");
} | #vulnerable code
@Override
public void close() {
if (!connected.compareAndSet(true, false)) return;
if (heartBeat != null) {
heartBeat.cancel();
heartBeat = null;
logger.info("heart beat canceled.");
}
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException e) {
//NOP
}
logger.info("channel closed");
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | 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 44
#vulnerability type THREAD_SAFETY_VIOLATION | 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 11
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void close() {
if (!connected.compareAndSet(true, false)) return;
synchronized (this) {
if (heartBeat != null) {
heartBeat.cancel();
heartBeat = null;
logger.info("heart beat canceled.");
}
}
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException e) {
//NOP
}
logger.info("channel closed");
} | #vulnerable code
@Override
public void close() {
if (!connected.compareAndSet(true, false)) return;
if (heartBeat != null) {
heartBeat.cancel();
heartBeat = null;
logger.info("heart beat canceled.");
}
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
//NOP
}
try {
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException e) {
//NOP
}
logger.info("channel closed");
}
#location 10
#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 {
try (FileOutputStream out = new FileOutputStream(new File("./src/test/resources/dump-merged.rdb"))) {
// you know your redis version. so you know your rdb version.
out.write("REDIS0007".getBytes());
for (int i = 0; i < 4; i++) {
Replicator replicator = new RedisReplicator(new File("./src/test/resources/dump-split-" + i + ".rdb"),
FileType.RDB, Configuration.defaultSetting());
final Tuple2<String, ByteBuilder> tuple = new Tuple2<>();
tuple.setT2(ByteBuilder.allocate(128));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
if (tuple.getT1() != null) {
try {
byte[] ary = tuple.getT2().array();
byte[] head = Arrays.copyOfRange(ary, 0, 5);
if (Arrays.equals("REDIS".getBytes(), head)) {
out.write(ary, 9, ary.length - 9);
} else {
out.write(ary);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
tuple.setT1(null);
tuple.setT2(ByteBuilder.allocate(128));
}
for (byte b : rawBytes) tuple.getT2().put(b);
}
};
replicator.addRawByteListener(rawByteListener);
replicator.addAuxFieldListener(new AuxFieldListener() {
@Override
public void handle(Replicator replicator, AuxField auxField) {
// clear aux field
tuple.setT2(ByteBuilder.allocate(128));
}
});
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
tuple.setT1(kv.getKey());
}
public void postFullSync(Replicator replicator, long checksum) {
tuple.setT2(ByteBuilder.allocate(128));
}
});
replicator.open();
}
out.write(Constants.RDB_OPCODE_EOF);
// if you want to load data from split rdb file which we generated.
// You MUST close rdbchecksum in redis.conf.
// Because this checksum is not correct.
out.write(longToByteArray(0L));
}
} | #vulnerable code
public static void main(String[] args) throws IOException {
final FileOutputStream out = new FileOutputStream(new File("./src/test/resources/dump-merged.rdb"));
// you know your redis version. so you know your rdb version.
out.write("REDIS0007".getBytes());
for (int i = 0; i < 4; i++) {
Replicator replicator = new RedisReplicator(new File("./src/test/resources/dump-split-" + i + ".rdb"),
FileType.RDB, Configuration.defaultSetting());
final Tuple2<String, ByteBuilder> tuple = new Tuple2<>();
tuple.setT2(ByteBuilder.allocate(128));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
if (tuple.getT1() != null) {
try {
byte[] ary = tuple.getT2().array();
byte[] head = Arrays.copyOfRange(ary, 0, 5);
if (Arrays.equals("REDIS".getBytes(), head)) {
out.write(ary, 9, ary.length - 9);
} else {
out.write(ary);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
tuple.setT1(null);
tuple.setT2(ByteBuilder.allocate(128));
}
for (byte b : rawBytes) tuple.getT2().put(b);
}
};
replicator.addRawByteListener(rawByteListener);
replicator.addAuxFieldListener(new AuxFieldListener() {
@Override
public void handle(Replicator replicator, AuxField auxField) {
// clear aux field
tuple.setT2(ByteBuilder.allocate(128));
}
});
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
tuple.setT1(kv.getKey());
}
public void postFullSync(Replicator replicator, long checksum) {
tuple.setT2(ByteBuilder.allocate(128));
}
});
replicator.open();
}
out.write(Constants.RDB_OPCODE_EOF);
// if you want to load data from split rdb file which we generated.
// You MUST close rdbchecksum in redis.conf.
// Because this checksum is not correct.
out.write(longToByteArray(0L));
out.close();
}
#location 51
#vulnerability type RESOURCE_LEAK | 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/appendonly.aof")));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
try {
out.write(rawBytes);
} catch (IOException ignore) {
}
}
};
//save 1000 records commands
Replicator replicator = new RedisReplicator("redis://127.0.0.1:6379");
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
replicator.addRawByteListener(rawByteListener);
}
});
final AtomicInteger acc = new AtomicInteger(0);
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
if (acc.incrementAndGet() == 1000) {
try {
out.close();
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
replicator.open();
//check aof file
replicator = new RedisReplicator("redis:///path/to/appendonly.aof");
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
System.out.println(command);
}
});
replicator.open();
} | #vulnerable code
public static void main(String[] args) throws IOException {
final FileOutputStream out = new FileOutputStream(new File("./src/test/resources/appendonly.aof"));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
try {
out.write(rawBytes);
} catch (IOException ignore) {
}
}
};
//save 1000 records commands
Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting());
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
replicator.addRawByteListener(rawByteListener);
}
});
final AtomicInteger acc = new AtomicInteger(0);
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
if (acc.incrementAndGet() == 1000) {
try {
out.close();
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
replicator.open();
//check aof file
replicator = new RedisReplicator(new File("./src/test/resources/appendonly.aof"), FileType.AOF, Configuration.defaultSetting());
replicator.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
System.out.println(command);
}
});
replicator.open();
}
#location 31
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
Replicator r = new RedisReplicator("redis://127.0.0.1:6379");
r.setRdbVisitor(new ValueIterableRdbVisitor(r));
r.addRdbListener(new HugeKVRdbListener(200) {
@Override
public void handleString(boolean last, byte[] key, byte[] value, int type) {
// your business code goes here.
}
@Override
public void handleModule(boolean last, byte[] key, Module value, int type) {
// your business code goes here.
}
@Override
public void handleList(boolean last, byte[] key, List<byte[]> list, int type) {
// your business code goes here.
}
@Override
public void handleZSetEntry(boolean last, byte[] key, List<ZSetEntry> list, int type) {
// your business code goes here.
}
@Override
public void handleMap(boolean last, byte[] key, List<Map.Entry<byte[], byte[]>> list, int type) {
// your business code goes here.
}
});
r.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
System.out.println(command);
}
});
r.open();
} | #vulnerable code
public static void main(String[] args) throws IOException {
Replicator r = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting());
r.setRdbVisitor(new ValueIterableRdbVisitor(r));
r.addRdbListener(new HugeKVRdbListener(200) {
@Override
public void handleString(boolean last, byte[] key, byte[] value, int type) {
// your business code goes here.
}
@Override
public void handleModule(boolean last, byte[] key, Module value, int type) {
// your business code goes here.
}
@Override
public void handleList(boolean last, byte[] key, List<byte[]> list, int type) {
// your business code goes here.
}
@Override
public void handleZSetEntry(boolean last, byte[] key, List<ZSetEntry> list, int type) {
// your business code goes here.
}
@Override
public void handleMap(boolean last, byte[] key, List<Map.Entry<byte[], byte[]>> list, int type) {
// your business code goes here.
}
});
r.addCommandListener(new CommandListener() {
@Override
public void handle(Replicator replicator, Command command) {
System.out.println(command);
}
});
r.open();
}
#location 36
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applySetIntSet(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueSet o11 = new KeyStringValueSet();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<String> set = new LinkedHashSet<>();
Set<byte[]> rawSet = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
long lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (long i = 0; i < lenOfContent; i++) {
switch (encoding) {
case 2:
String element = String.valueOf(stream.readInt(2));
set.add(element);
rawSet.add(element.getBytes());
break;
case 4:
element = String.valueOf(stream.readInt(4));
set.add(element);
rawSet.add(element.getBytes());
break;
case 8:
element = String.valueOf(stream.readLong(8));
set.add(element);
rawSet.add(element.getBytes());
break;
default:
throw new AssertionError("expect encoding [2,4,8] but:" + encoding);
}
}
o11.setValueRdbType(RDB_TYPE_SET_INTSET);
o11.setValue(set);
o11.setRawValue(rawSet);
o11.setDb(db);
o11.setKey(new String(key, CHARSET));
o11.setRawKey(key);
return o11;
} | #vulnerable code
@Override
public Event applySetIntSet(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueSet o11 = new KeyStringValueSet();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<String> set = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
long lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (long 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(RDB_TYPE_SET_INTSET);
o11.setValue(set);
o11.setDb(db);
o11.setKey(key);
return o11;
}
#location 28
#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 22
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testChecksumV6() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"), FileType.RDB,
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
final AtomicLong atomicChecksum = new AtomicLong(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
atomicChecksum.compareAndSet(0, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testChecksumV6");
assertEquals(132, acc.get());
assertEquals(-3409494954737929802L, atomicChecksum.get());
}
});
redisReplicator.open();
} | #vulnerable code
@Test
public void testChecksumV6() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"),
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
final AtomicLong atomicChecksum = new AtomicLong(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
atomicChecksum.compareAndSet(0, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testChecksumV6");
assertEquals(132, acc.get());
assertEquals(-3409494954737929802L, atomicChecksum.get());
}
});
redisReplicator.open();
}
#location 28
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void 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 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFileV6() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"), FileType.RDB,
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV6");
assertEquals(132, acc.get());
}
});
redisReplicator.open();
} | #vulnerable code
@Test
public void testFileV6() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"),
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV6");
assertEquals(132, acc.get());
}
});
redisReplicator.open();
}
#location 26
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Event applySetIntSet(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueSet o11 = new KeyStringValueSet();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<String> set = new LinkedHashSet<>();
Set<byte[]> rawSet = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
long lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (long i = 0; i < lenOfContent; i++) {
switch (encoding) {
case 2:
String element = String.valueOf(stream.readInt(2));
set.add(element);
rawSet.add(element.getBytes());
break;
case 4:
element = String.valueOf(stream.readInt(4));
set.add(element);
rawSet.add(element.getBytes());
break;
case 8:
element = String.valueOf(stream.readLong(8));
set.add(element);
rawSet.add(element.getBytes());
break;
default:
throw new AssertionError("expect encoding [2,4,8] but:" + encoding);
}
}
o11.setValueRdbType(RDB_TYPE_SET_INTSET);
o11.setValue(set);
o11.setRawValue(rawSet);
o11.setDb(db);
o11.setKey(new String(key, CHARSET));
o11.setRawKey(key);
return o11;
} | #vulnerable code
@Override
public Event applySetIntSet(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueSet o11 = new KeyStringValueSet();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<String> set = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
long lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (long 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(RDB_TYPE_SET_INTSET);
o11.setValue(set);
o11.setDb(db);
o11.setKey(key);
return o11;
}
#location 31
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 58
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (hashProgress.isProgressDisplayed())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgress.hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
hashProgress.progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
hashProgress.progressOutputStop();
displayStatistics(start, state);
return state;
} | #vulnerable code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = State.loadFromGZipFile(stateFile);
adjustAccordingToHashMode(state);
return state;
} | #vulnerable code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = new State();
state.loadFromGZipFile(stateFile);
// Replace by 'no_hash' accurately to be able to compare the FileState entry
switch (parameters.getHashMode())
{
case DONT_HASH_FILES:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_FOUR_KILO:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_MEGA:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case COMPUTE_ALL_HASH:
// Nothing to do
break;
}
return state;
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws IOException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new GnuParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
} | #vulnerable code
public static void main(String[] args) throws IOException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new GnuParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State previousState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
previousState = manager.loadPreviousState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(previousState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
previousState = manager.loadPreviousState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(previousState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadPreviousState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
previousState = manager.loadPreviousState();
manager.resetDates(previousState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
#location 106
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public DuplicateResult findDuplicates(State state)
{
DuplicateResult result = new DuplicateResult(parameters);
List<FileState> fileStates = new ArrayList<>(state.getFileStates());
Collections.sort(fileStates, hashComparator);
List<FileState> duplicatedFiles = new ArrayList<>();
FileHash previousFileHash = new FileHash(FileState.NO_HASH, FileState.NO_HASH, FileState.NO_HASH);
for (FileState fileState : fileStates)
{
if (!previousFileHash.equals(fileState.getFileHash()))
{
result.addDuplicatedFiles(duplicatedFiles);
duplicatedFiles.clear();
}
previousFileHash = fileState.getFileHash();
duplicatedFiles.add(fileState);
}
result.addDuplicatedFiles(duplicatedFiles);
return result;
} | #vulnerable code
public DuplicateResult findDuplicates(State state)
{
DuplicateResult result = new DuplicateResult(parameters);
List<FileState> fileStates = new ArrayList<>(state.getFileStates());
Collections.sort(fileStates, fullHashComparator);
FileHash previousHash = new FileHash(FileState.NO_HASH, FileState.NO_HASH, FileState.NO_HASH);
for (FileState fileState : fileStates)
{
if (!previousHash.equals(fileState.getFileHash()))
{
result.addDuplicatedFiles(duplicatedFiles);
duplicatedFiles.clear();
}
previousHash = fileState.getFileHash();
duplicatedFiles.add(fileState);
}
result.addDuplicatedFiles(duplicatedFiles);
return result;
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws IOException, NoSuchAlgorithmException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new DefaultParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
String fimRepositoryDirectory = null;
boolean alwaysYes = false;
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
fimRepositoryDirectory = commandLine.getOptionValue('d');
alwaysYes = commandLine.hasOption('y');
if (command == Command.REMOVE_DUPLICATES && fimRepositoryDirectory == null)
{
System.out.println("The Fim repository directory must be provided");
printUsage();
System.exit(-1);
}
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(-1);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIM_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State state;
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (alwaysYes || confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case REMOVE_DUPLICATES:
fastCompareNotSupported(compareMode);
File repository = new File(fimRepositoryDirectory);
if (!repository.exists())
{
System.out.printf("Directory %s does not exist%n", fimRepositoryDirectory);
System.exit(-1);
}
if (repository.getCanonicalPath().equals(baseDirectory.getCanonicalPath()))
{
System.out.printf("Cannot remove duplicates from the current directory%n");
System.exit(-1);
}
File fimDir = new File(repository, StateGenerator.FIM_DIR);
if (!fimDir.exists())
{
System.out.printf("Directory %s is not a Fim repository%n", fimRepositoryDirectory);
System.exit(-1);
}
System.out.println("Searching for duplicated files using the " + fimRepositoryDirectory + " directory as master");
System.out.println("");
File otherStateDir = new File(fimDir, "states");
StateManager otherManager = new StateManager(otherStateDir, CompareMode.FULL);
State otherState = otherManager.loadLastState();
Map<String, FileState> otherHashes = new HashMap<>();
for (FileState otherFileState : otherState.getFileStates())
{
otherHashes.put(otherFileState.getHash(), otherFileState);
}
State localState = generator.generateState(message, baseDirectory);
for (FileState localFileState : localState.getFileStates())
{
FileState otherFileState = otherHashes.get(localFileState.getHash());
if (otherFileState != null)
{
System.out.printf("%s is a duplicate of %s/%s%n", localFileState.getFileName(), fimRepositoryDirectory, otherFileState.getFileName());
if (alwaysYes || confirmCommand("remove it"))
{
System.out.printf(" %s removed%n", localFileState.getFileName());
File localFile = new File(localFileState.getFileName());
localFile.delete();
}
}
}
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
} | #vulnerable code
public static void main(String[] args) throws IOException, NoSuchAlgorithmException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new DefaultParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
#location 106
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
} | #vulnerable code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf(" (Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 38
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (hashProgress.isProgressDisplayed())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgress.hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
hashProgress.progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
hashProgress.progressOutputStop();
displayStatistics(start, state);
return state;
} | #vulnerable code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void outputInit() {
progressLock.lock();
try {
summedFileLength = 0;
fileCount = 0;
} finally {
progressLock.unlock();
}
} | #vulnerable code
public void outputInit() {
summedFileLength = 0;
fileCount = 0;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 63
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 28
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = State.loadFromGZipFile(stateFile);
adjustAccordingToHashMode(state);
return state;
} | #vulnerable code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = new State();
state.loadFromGZipFile(stateFile);
// Replace by 'no_hash' accurately to be able to compare the FileState entry
switch (parameters.getHashMode())
{
case DONT_HASH_FILES:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_FOUR_KILO:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_MEGA:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case COMPUTE_ALL_HASH:
// Nothing to do
break;
}
return state;
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 53
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean resetDosPermissions(Path file, FileState fileState, DosFileAttributes dosFileAttributes)
{
String permissions = DosFilePermissions.toString(dosFileAttributes);
String previousPermissions = getAttribute(fileState, FileAttribute.DosFilePermissions);
if (previousPermissions != null && !Objects.equals(permissions, previousPermissions))
{
DosFilePermissions.setPermissions(file, previousPermissions);
System.out.printf("Set permissions: %s \t%s -> %s%n", fileState.getFileName(), permissions, previousPermissions);
return true;
}
return false;
} | #vulnerable code
private boolean resetDosPermissions(Path file, FileState fileState, DosFileAttributes dosFileAttributes)
{
String permissions = DosFilePermissions.toString(dosFileAttributes);
String previousPermissions = getAttribute(fileState, FileAttribute.DosFilePermissions);
if (!Objects.equals(permissions, previousPermissions))
{
DosFilePermissions.setPermissions(file, previousPermissions);
System.out.printf("Set permissions: %s \t%s -> %s%n", fileState.getFileName(), permissions, previousPermissions);
return true;
}
return false;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 33
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
} | #vulnerable code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf(" (Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.