instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
|
#vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getUniqueID());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457", document.getUniqueID());
Assert.assertEquals(1567278978000l, document.getItemValueDate("$created").getTime());
}
#location 42
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
// test conditional sequence flow...
if (bSequenceFlow && bconditionExpression && qName.equalsIgnoreCase("bpmn2:conditionExpression")) {
String svalue = characterStream.toString();
logger.fine("conditional SequenceFlow:" + bpmnID + "=" + svalue);
bconditionExpression = false;
conditionCache.put(bpmnID, svalue);
}
}
|
#vulnerable code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
}
#location 66
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
// Nashorn: check for importClass function and then load if missing
// See: issue #124
String jsNashorn = " if (typeof importClass != 'function') { load('nashorn:mozilla_compat.js');}";
String jsCode = "importPackage(java.util);" + "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsNashorn + jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine.get("_evaluateScriptParam");
if (resultList==null) {
return null;
}
if ("[undefined]".equals(resultList.toString())) {
return null;
}
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - " + se.getMessage());
return null;
}
}
|
#vulnerable code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
String jsCode = "importPackage(java.util);"
+ "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine
.get("_evaluateScriptParam");
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - "
+ se.getMessage());
return null;
}
}
#location 38
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testMinusWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testMinusWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFileData(new FileData( "test1.txt", empty,"application/xml",null));
ItemCollection itemColTarget = new ItemCollection();
itemColTarget.addFileData(itemColSource.getFileData("test1.txt"));
FileData filedata = itemColTarget.getFileData("test1.txt");
Assert.assertNotNull(filedata);
Assert.assertEquals("test1.txt", filedata.getName());
Assert.assertEquals("application/xml", filedata.getContentType());
// test the byte content of itemColSource
byte[] file1Data1 =itemColSource.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
file1Data1 = itemColTarget.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
}
|
#vulnerable code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFile(empty, "test1.txt", "application/xml");
ItemCollection itemColTarget = new ItemCollection();
itemColTarget.addFileData(itemColSource.getFileData("test1.txt"));
FileData filedata = itemColTarget.getFileData("test1.txt");
Assert.assertNotNull(filedata);
Assert.assertEquals("test1.txt", filedata.getName());
Assert.assertEquals("application/xml", filedata.getContentType());
// test the byte content of itemColSource
Map<String, List<Object>> conedFiles1 = itemColSource.getFiles();
List<Object> fileContent1 = conedFiles1.get("test1.txt");
byte[] file1Data1 = (byte[]) fileContent1.get(1);
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
conedFiles1 = itemColTarget.getFiles();
fileContent1 = conedFiles1.get("test1.txt");
file1Data1 = (byte[]) fileContent1.get(1);
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
}
#location 28
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings({ "rawtypes" })
public int run(ItemCollection documentContext,
ItemCollection documentActivity) throws PluginException {
mailMessage = null;
// check if mail is active?
if ("1".equals(documentActivity.getItemValueString("keyMailInactive")))
return Plugin.PLUGIN_OK;
List vectorRecipients = getRecipients(documentContext, documentActivity);
if (vectorRecipients.isEmpty()) {
logger.fine("[MailPlugin] No Receipients defined for this Activity...");
return Plugin.PLUGIN_OK;
}
try {
// first initialize mail message object
initMailMessage();
if (mailMessage == null) {
logger.warning("[MailPlugin] mailMessage = null");
return Plugin.PLUGIN_WARNING;
}
// set FROM
mailMessage.setFrom(getInternetAddress(getFrom(documentContext,
documentActivity)));
// set Recipient
mailMessage.setRecipients(Message.RecipientType.TO,
getInternetAddressArray(vectorRecipients));
// build CC
mailMessage.setRecipients(
Message.RecipientType.CC,
getInternetAddressArray(getRecipientsCC(documentContext,
documentActivity)));
// replay to?
String sReplyTo = getReplyTo(documentContext, documentActivity);
if ((sReplyTo != null) && (!sReplyTo.isEmpty())) {
InternetAddress[] resplysAdrs = new InternetAddress[1];
resplysAdrs[0] = getInternetAddress(sReplyTo);
mailMessage.setReplyTo(resplysAdrs);
}
// set Subject
mailMessage.setSubject(
getSubject(documentContext, documentActivity),
this.getCharSet());
// set Body
String aBodyText = getBody(documentContext, documentActivity);
if (aBodyText == null) {
aBodyText = "";
}
// set mailbody
MimeBodyPart messagePart = new MimeBodyPart();
logger.fine("[MailPlugin] ContentType: '" + getContentType() + "'");
messagePart.setContent(aBodyText, getContentType());
// append message part
mimeMultipart.addBodyPart(messagePart);
// mimeMulitPart object can be extended from subclases
} catch (Exception e) {
logger.warning("[MailPlugin] run - Warning:" + e.toString());
e.printStackTrace();
return Plugin.PLUGIN_WARNING;
}
return Plugin.PLUGIN_OK;
}
|
#vulnerable code
@SuppressWarnings({ "rawtypes" })
public int run(ItemCollection documentContext,
ItemCollection documentActivity) throws PluginException {
mailMessage = null;
// check if mail is active?
if ("1".equals(documentActivity.getItemValueString("keyMailInactive")))
return Plugin.PLUGIN_OK;
List vectorRecipients = getRecipients(documentContext, documentActivity);
if (vectorRecipients.isEmpty()) {
logger.fine("[MailPlugin] No Receipients defined for this Activity...");
return Plugin.PLUGIN_OK;
}
try {
// first initialize mail message object
initMailMessage();
// set FROM
mailMessage.setFrom(getInternetAddress(getFrom(documentContext,
documentActivity)));
// set Recipient
mailMessage.setRecipients(Message.RecipientType.TO,
getInternetAddressArray(vectorRecipients));
// build CC
mailMessage.setRecipients(
Message.RecipientType.CC,
getInternetAddressArray(getRecipientsCC(documentContext,
documentActivity)));
// replay to?
String sReplyTo = getReplyTo(documentContext, documentActivity);
if ((sReplyTo != null) && (!sReplyTo.isEmpty())) {
InternetAddress[] resplysAdrs = new InternetAddress[1];
resplysAdrs[0] = getInternetAddress(sReplyTo);
mailMessage.setReplyTo(resplysAdrs);
}
// set Subject
mailMessage.setSubject(
getSubject(documentContext, documentActivity),
this.getCharSet());
// set Body
String aBodyText = getBody(documentContext, documentActivity);
if (aBodyText == null) {
aBodyText = "";
}
// set mailbody
MimeBodyPart messagePart = new MimeBodyPart();
logger.fine("[MailPlugin] ContentType: '" + getContentType() + "'");
messagePart.setContent(aBodyText, getContentType());
// append message part
mimeMultipart.addBodyPart(messagePart);
// mimeMulitPart object can be extended from subclases
} catch (Exception e) {
logger.warning("[MailPlugin] run - Warning:" + e.toString());
e.printStackTrace();
return Plugin.PLUGIN_WARNING;
}
return Plugin.PLUGIN_OK;
}
#location 23
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putDocuments(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
}
|
#vulnerable code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putCollection(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// test orign ref
Assert.assertEquals(orignUniqueID,subprocess.getItemValueString(SplitAndJoinPlugin.ORIGIN_REF));
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
}
#location 48
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
// Nashorn: check for importClass function and then load if missing
// See: issue #124
String jsNashorn = " if (typeof importClass != 'function') { load('nashorn:mozilla_compat.js');}";
String jsCode = "importPackage(java.util);" + "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsNashorn + jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine.get("_evaluateScriptParam");
if (resultList==null) {
return null;
}
if ("[undefined]".equals(resultList.toString())) {
return null;
}
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - " + se.getMessage());
return null;
}
}
|
#vulnerable code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
String jsCode = "importPackage(java.util);"
+ "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine
.get("_evaluateScriptParam");
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - "
+ se.getMessage());
return null;
}
}
#location 33
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
|
#vulnerable code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
#vulnerable code
void handleNewChannelEvent(NewChannelEvent event)
{
final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
if (event.getChannel() == null)
{
logger.info("Ignored NewChannelEvent with empty channel name (uniqueId=" + event.getUniqueId() + ")");
}
else
{
addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), event.getAccountCode());
}
}
else
{
// channel had already been created probably by a NewCallerIdEvent
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#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 onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
Thread reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
|
#vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
#location 78
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.info("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.info("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.info("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
|
#vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.warn("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.warn("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.warn("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.warn("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
logger.warn("Manager Events seen " + managerEventsSeen.get());
return this.result;
}
#location 127
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException
{
ResponseHandlerResult result = new ResponseHandlerResult();
SendActionCallback callbackHandler = new DefaultSendActionCallback(result);
sendAction(action, callbackHandler);
// definitely return null for the response of user events
if (action instanceof UserEventAction)
{
return null;
}
// only wait if we did not yet receive the response.
// Responses may be returned really fast.
if (result.getResponse() == null)
{
try
{
result.await(timeout);
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for result");
Thread.currentThread().interrupt();
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to " + action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"));
}
return result.getResponse();
}
|
#vulnerable code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException
{
ResponseHandlerResult result;
SendActionCallback callbackHandler;
result = new ResponseHandlerResult();
callbackHandler = new DefaultSendActionCallback(result);
synchronized (result)
{
sendAction(action, callbackHandler);
// definitely return null for the response of user events
if (action instanceof UserEventAction)
{
return null;
}
// only wait if we did not yet receive the response.
// Responses may be returned really fast.
if (result.getResponse() == null)
{
try
{
result.wait(timeout);
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for result");
Thread.currentThread().interrupt();
}
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to " + action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"));
}
return result.getResponse();
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to readerThread
// After sending the DisconnectThread that thread will die anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
|
#vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
}
#location 66
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
Thread reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
|
#vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
#location 68
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private synchronized Map<String, String[]> parseParameters(String s)
{
Map<String, List<String>> parameterMap;
Map<String, String[]> result;
StringTokenizer st;
parameterMap = new HashMap<String, List<String>>();
result = new HashMap<String, String[]>();
if (s == null)
{
return result;
}
st = new StringTokenizer(s, "&");
while (st.hasMoreTokens())
{
String parameter;
Matcher parameterMatcher;
String name;
String value;
List<String> values;
parameter = st.nextToken();
parameterMatcher = PARAMETER_PATTERN.matcher(parameter);
if (parameterMatcher.matches())
{
try
{
name = URLDecoder.decode(parameterMatcher.group(1), "UTF-8");
value = URLDecoder.decode(parameterMatcher.group(2), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
else
{
try
{
name = URLDecoder.decode(parameter, "UTF-8");
value = "";
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
if (parameterMap.get(name) == null)
{
values = new ArrayList<String>();
values.add(value);
parameterMap.put(name, values);
}
else
{
values = parameterMap.get(name);
values.add(value);
}
}
for (Map.Entry<String, List<String>> entry : parameterMap.entrySet())
{
String[] valueArray;
valueArray = new String[entry.getValue().size()];
result.put(entry.getKey(), entry.getValue().toArray(valueArray));
}
return result;
}
|
#vulnerable code
private synchronized Map<String, String[]> parseParameters(String s)
{
Map<String, List<String>> parameterMap;
Map<String, String[]> result;
StringTokenizer st;
parameterMap = new HashMap<String, List<String>>();
result = new HashMap<String, String[]>();
if (s == null)
{
return result;
}
st = new StringTokenizer(s, "&");
while (st.hasMoreTokens())
{
String parameter;
Matcher parameterMatcher;
String name;
String value;
List<String> values;
parameter = st.nextToken();
parameterMatcher = PARAMETER_PATTERN.matcher(parameter);
if (parameterMatcher.matches())
{
try
{
name = URLDecoder.decode(parameterMatcher.group(1), "UTF-8");
value = URLDecoder.decode(parameterMatcher.group(2), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
else
{
try
{
name = URLDecoder.decode(parameter, "UTF-8");
value = "";
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
if (parameterMap.get(name) == null)
{
values = new ArrayList<String>();
values.add(value);
parameterMap.put(name, values);
}
else
{
values = parameterMap.get(name);
values.add(value);
}
}
for (String name : parameterMap.keySet())
{
List<String> values;
String[] valueArray;
values = parameterMap.get(name);
valueArray = new String[values.size()];
result.put(name, values.toArray(valueArray));
}
return result;
}
#location 72
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getProtocolIdentifier()
{
return protocolIdentifier.getValue();
}
|
#vulnerable code
public String getProtocolIdentifier()
{
return protocolIdentifier.value;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#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 onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) throws ManagerCommunicationException, NoSuchChannelException
{
return originateToExtension(channel, context, exten, priority, timeout, null, null);
}
|
#vulnerable code
public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) throws ManagerCommunicationException
{
return originateToExtension(channel, context, exten, priority, timeout, null, null);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
}
|
#vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public AsteriskChannel getDialedChannel()
{
synchronized(dialedChannels) {
for (AsteriskChannel channel:dialedChannels) {
if (channel != null) return channel;
}
}
return null;
}
|
#vulnerable code
public AsteriskChannel getDialedChannel()
{
return dialedChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected AsteriskVersion determineVersion() throws IOException, TimeoutException
{
int attempts = 0;
logger.info("Got asterisk protocol identifier version " + protocolIdentifier.getValue());
while (attempts++ < MAX_VERSION_ATTEMPTS)
{
try {
AsteriskVersion version = determineVersionByCoreSettings();
if (version != null) return version;
} catch (Exception e) {
}
try {
AsteriskVersion version = determineVersionByCoreShowVersion();
if (version != null) return version;
} catch (Exception e) {
}
try
{
Thread.sleep(RECONNECTION_VERSION_INTERVAL);
}
catch (Exception ex)
{
// ignore
} // NOPMD
}
logger.error("Unable to determine asterisk version, assuming " + DEFAULT_ASTERISK_VERSION + "... you should expect problems to follow.");
return DEFAULT_ASTERISK_VERSION;
}
|
#vulnerable code
protected AsteriskVersion determineVersion() throws IOException, TimeoutException
{
int attempts = 0;
// if ("Asterisk Call Manager/1.1".equals(protocolIdentifier.value))
// {
// return AsteriskVersion.ASTERISK_1_6;
// }
while (attempts++ < MAX_VERSION_ATTEMPTS)
{
final ManagerResponse showVersionFilesResponse;
final List<String> showVersionFilesResult;
boolean Asterisk14outputPresent = false;
// increase timeout as output is quite large
showVersionFilesResponse = sendAction(new CommandAction("show version files pbx.c"), defaultResponseTimeout * 2);
if (!(showVersionFilesResponse instanceof CommandResponse))
{
// return early in case of permission problems
// org.asteriskjava.manager.response.ManagerError:
// actionId='null'; message='Permission denied';
// response='Error';
// uniqueId='null'; systemHashcode=15231583
if (showVersionFilesResponse.getOutput() != null)
{
Asterisk14outputPresent = true;
}
else
{
break;
}
}
if (Asterisk14outputPresent)
{
List<String> outputList = Arrays
.asList(showVersionFilesResponse.getOutput().split(SocketConnectionFacadeImpl.NL_PATTERN.pattern()));
showVersionFilesResult = outputList;
}
else
{
showVersionFilesResult = ((CommandResponse) showVersionFilesResponse).getResult();
}
if (showVersionFilesResult != null && !showVersionFilesResult.isEmpty())
{
final String line1 = showVersionFilesResult.get(0);
if (line1 != null && line1.startsWith("File"))
{
final String rawVersion;
rawVersion = getRawVersion();
if (rawVersion != null && rawVersion.startsWith("Asterisk 1.4"))
{
return AsteriskVersion.ASTERISK_1_4;
}
return AsteriskVersion.ASTERISK_1_2;
}
else if (line1 != null && line1.contains("No such command"))
{
final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction("core show version"),
defaultResponseTimeout * 2);
if (coreShowVersionResponse != null && coreShowVersionResponse instanceof CommandResponse)
{
final List<String> coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult();
if (coreShowVersionResult != null && !coreShowVersionResult.isEmpty())
{
final String coreLine = coreShowVersionResult.get(0);
if (VERSION_PATTERN_1_6.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_1_6;
}
else if (VERSION_PATTERN_1_8.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_1_8;
}
else if (VERSION_PATTERN_10.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_10;
}
else if (VERSION_PATTERN_11.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_11;
}
else if (VERSION_PATTERN_CERTIFIED_11.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_11;
}
else if (VERSION_PATTERN_12.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_12;
}
else if (VERSION_PATTERN_13.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_13;
}
else if (VERSION_PATTERN_CERTIFIED_13.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_13;
}
else if (VERSION_PATTERN_14.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_14;
}
else if (VERSION_PATTERN_15.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_15;
}
}
}
try
{
Thread.sleep(RECONNECTION_VERSION_INTERVAL);
}
catch (Exception ex)
{
// ingnore
} // NOPMD
}
else
{
// if it isn't the "no such command", break and return the
// lowest version immediately
break;
}
}
}
// TODO: add retry logic; in a reconnect scenario the version fails to
// be identified leading to errors
// as a fallback assume 1.6
logger.error("Unable to determine asterisk version, assuming 1.6... you should expect problems to follow.");
return AsteriskVersion.ASTERISK_1_6;
}
#location 51
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.info("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.info("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.info("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
|
#vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.warn("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.warn("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.warn("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.warn("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
logger.warn("Manager Events seen " + managerEventsSeen.get());
return this.result;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String toString()
{
final StringBuffer sb;
sb = new StringBuffer("AsteriskAgent[");
sb.append("agentId='").append(getAgentId()).append("',");
sb.append("name='").append(getName()).append("',");
sb.append("state=").append(getState()).append(",");
sb.append("systemHashcode=").append(System.identityHashCode(this));
sb.append("]");
return sb.toString();
}
|
#vulnerable code
@Override
public String toString()
{
final StringBuffer sb;
sb = new StringBuffer("AsteriskAgent[");
sb.append("agentId='").append(getAgentId()).append("',");
sb.append("name='").append(getName()).append("',");
sb.append("state=").append(getStatus()).append(",");
sb.append("systemHashcode=").append(System.identityHashCode(this));
sb.append("]");
return sb.toString();
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public AsteriskChannel getDialingChannel()
{
synchronized(dialingChannels) {
if (dialingChannels.isEmpty()) return null;
return dialingChannels.get(0);
}
}
|
#vulnerable code
public AsteriskChannel getDialingChannel()
{
return dialingChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
#vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
}
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
|
#vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup == true)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess == true)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void fastScannerSpeedTest(Pattern pattern) throws Exception
{
try
{
for (int i = 10; i-- > 0;)
{
Socket echoSocket = new Socket("127.0.0.1", FastScannerTestSocketSource.portNumber);
InputStreamReader reader = getReader(echoSocket);
System.out.print("Fast " + i + ":\t");
FastScanner scanner = FastScannerFactory.getReader(reader, pattern);
long start = System.currentTimeMillis();
try
{
int ctr = 0;
@SuppressWarnings("unused")
String t;
while ((t = scanner.next()) != null)
{
// System.out.println(t);
ctr++;
}
System.out.print(ctr + "\t");
}
catch (NoSuchElementException e)
{
}
System.out.println((System.currentTimeMillis() - start) + " ms");
}
}
catch (Exception e)
{
System.out.println(
"If you want to run FastScannerSpeedTestOnSocket, you'll need to run FastScannerTestSocketSource first");
}
}
|
#vulnerable code
private void fastScannerSpeedTest(Pattern pattern) throws Exception
{
try
{
for (int i = 10; i-- > 0;)
{
InputStreamReader reader = getReader();
System.out.print("Fast " + i + ":\t");
FastScanner scanner = FastScannerFactory.getReader(reader, pattern);
long start = System.currentTimeMillis();
try
{
int ctr = 0;
@SuppressWarnings("unused")
String t;
while ((t = scanner.next()) != null)
{
// System.out.println(t);
ctr++;
}
System.out.print(ctr + "\t");
}
catch (NoSuchElementException e)
{
}
System.out.println((System.currentTimeMillis() - start) + " ms");
}
}
catch (Exception e)
{
System.out.println(
"If you want to run FastScannerSpeedTestOnSocket, you'll need to run FastScannerTestSocketSource first");
}
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
QueueManager(AsteriskServerImpl server, ChannelManager channelManager)
{
this.server = server;
this.channelManager = channelManager;
}
|
#vulnerable code
void handleQueueMemberStatusEvent(QueueMemberStatusEvent event)
{
AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue());
if (queue == null)
{
logger.error("Ignored QueueMemberStatusEvent for unknown queue " + event.getQueue());
return;
}
AsteriskQueueMemberImpl member = queue.getMemberByLocation(event.getLocation());
if (member == null)
{
logger.error("Ignored QueueMemberStatusEvent for unknown member " + event.getLocation());
return;
}
updateQueue(queue.getName());
member.stateChanged(QueueMemberState.valueOf(event.getStatus()));
member.penaltyChanged(event.getPenalty());
member.lastCallChanged(event.getLastCall());
member.callsTakenChanged(event.getCallsTaken());
queue.fireMemberStateChanged(member);
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
|
#vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup == true)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess == true)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
#vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
#vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public ReadablePeriod deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException
{
JsonToken t = p.currentToken();
if (t == JsonToken.VALUE_STRING) {
return _fromString(p, ctxt, p.getText());
}
if (t == JsonToken.VALUE_NUMBER_INT) {
return new Period(p.getLongValue());
}
if (t != JsonToken.START_OBJECT && t != JsonToken.FIELD_NAME) {
return (ReadablePeriod) ctxt.handleUnexpectedToken(handledType(), t, p,
"expected JSON Number, String or Object");
}
return _fromObject(p, ctxt);
}
|
#vulnerable code
@Override
public ReadablePeriod deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException
{
JsonToken t = p.currentToken();
if (t == JsonToken.VALUE_STRING) {
String str = p.getText().trim();
if (str.isEmpty()) {
return null;
}
return _format.parsePeriod(ctxt, str);
}
if (t == JsonToken.VALUE_NUMBER_INT) {
return new Period(p.getLongValue());
}
if (t != JsonToken.START_OBJECT && t != JsonToken.FIELD_NAME) {
return (ReadablePeriod) ctxt.handleUnexpectedToken(handledType(), t, p,
"expected JSON Number, String or Object");
}
JsonNode treeNode = p.readValueAsTree();
String periodType = treeNode.path("fieldType").path("name").asText();
String periodName = treeNode.path("periodType").path("name").asText();
// any "weird" numbers we should worry about?
int periodValue = treeNode.path(periodType).asInt();
ReadablePeriod rp;
if (periodName.equals( "Seconds" )) {
rp = Seconds.seconds( periodValue );
}
else if (periodName.equals( "Minutes" )) {
rp = Minutes.minutes( periodValue );
}
else if (periodName.equals( "Hours" )) {
rp = Hours.hours( periodValue );
}
else if (periodName.equals( "Days" )) {
rp = Days.days( periodValue );
}
else if (periodName.equals( "Weeks" )) {
rp = Weeks.weeks( periodValue );
}
else if (periodName.equals( "Months" )) {
rp = Months.months( periodValue );
}
else if (periodName.equals( "Years" )) {
rp = Years.years( periodValue );
} else {
ctxt.reportInputMismatch(handledType(),
"Don't know how to deserialize %s using periodName '%s'",
handledType().getName(), periodName);
rp = null; // never gets here
}
if (_requireFullPeriod && !(rp instanceof Period)) {
rp = rp.toPeriod();
}
return rp;
}
#location 57
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void updateTranslationProgressMap(String langCode, int value) {
if (getDefaultLanguageCode().equals(langCode)) {
return;
}
double defsize = getDefaultLanguage().size();
double approved = value;
Map<String, Integer> progress = getTranslationProgressMap();
Integer percent = progress.get(langCode);
if (value == PLUS) {
approved = Math.round(percent * (defsize / 100) + 1);
} else if (value == MINUS) {
approved = Math.round(percent * (defsize / 100) - 1);
}
// allow 3 identical words per language (i.e. Email, etc)
if (approved >= defsize - 5) {
approved = defsize;
}
if (((int) defsize) == 0) {
progress.put(langCode, 0);
} else {
progress.put(langCode, (int) ((approved / defsize) * 100));
}
Sysprop updatedProgress = new Sysprop(progressKey);
for (Map.Entry<String, Integer> entry : progress.entrySet()) {
updatedProgress.addProperty(entry.getKey(), entry.getValue());
}
langProgressCache = updatedProgress;
if (percent < 100 && !percent.equals(progress.get(langCode))) {
pc.create(updatedProgress);
}
}
|
#vulnerable code
private void updateTranslationProgressMap(String langCode, int value) {
if (getDefaultLanguageCode().equals(langCode)) {
return;
}
double defsize = getDefaultLanguage().size();
double approved = value;
Map<String, Integer> progress = getTranslationProgressMap();
Integer percent = progress.get(langCode);
if (value == PLUS) {
approved = Math.round(percent * (defsize / 100) + 1);
} else if (value == MINUS) {
approved = Math.round(percent * (defsize / 100) - 1);
}
// allow 3 identical words per language (i.e. Email, etc)
if (approved >= defsize - 5) {
approved = defsize;
}
if (((int) defsize) == 0) {
progress.put(langCode, 0);
} else {
progress.put(langCode, (int) ((approved / defsize) * 100));
}
if (percent < 100 && !percent.equals(progress.get(langCode))) {
Sysprop s = new Sysprop(progressKey);
for (Map.Entry<String, Integer> entry : progress.entrySet()) {
s.addProperty(entry.getKey(), entry.getValue());
}
pc.create(s);
}
}
#location 27
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAnnotationCreate() throws Exception {
setupContextForAnnotatedListener();
DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener =
context.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null, null);
verifyListenerResults(true, false, false, taskExecution,annotatedListener);
}
|
#vulnerable code
@Test
public void testAnnotationCreate() throws Exception {
setupContextForAnnotatedListener();
DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener =
context.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null);
verifyListenerResults(true, false, false, taskExecution,annotatedListener);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String authentication = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
String method = request.getMethodValue();
String url = request.getPath().value();
log.debug("url:{},method:{},headers:{}", url, method, request.getHeaders());
//不需要网关签权的url
if (authService.ignoreAuthentication(url)) {
return chain.filter(exchange);
}
//调用签权服务看用户是否有权限,若有权限进入下一个filter
if (permissionService.permission(authentication, url, method)) {
ServerHttpRequest.Builder builder = request.mutate();
//TODO 转发的请求都加上服务间认证token
builder.header(X_CLIENT_TOKEN, "TODO zhoutaoo添加服务间简单认证");
//将jwt token中的用户信息传给服务
builder.header(X_CLIENT_TOKEN_USER, getUserToken(authentication));
return chain.filter(exchange.mutate().request(builder.build()).build());
}
return unauthorized(exchange);
}
|
#vulnerable code
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String authentication = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
String method = request.getMethodValue();
String url = request.getPath().value();
log.debug("url:{},method:{},headers:{}", url, method, request.getHeaders());
//不需要网关签权的url
if (authService.ignoreAuthentication(url)) {
return chain.filter(exchange);
}
// 如果请求未携带token信息, 直接跳出
if (StringUtils.isBlank(authentication) || !authentication.startsWith(BEARER)) {
log.debug("url:{},method:{},headers:{}, 请求未携带token信息", url, method, request.getHeaders());
return unauthorized(exchange);
}
//调用签权服务看用户是否有权限,若有权限进入下一个filter
if (authService.hasPermission(authentication, url, method)) {
ServerHttpRequest.Builder builder = request.mutate();
//TODO 转发的请求都加上服务间认证token
builder.header(X_CLIENT_TOKEN, "TODO zhoutaoo添加服务间简单认证");
//将jwt token中的用户信息传给服务
builder.header(X_CLIENT_TOKEN_USER, authService.getJwt(authentication).getClaims());
return chain.filter(exchange.mutate().request(builder.build()).build());
}
return unauthorized(exchange);
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
File getImage() {
//获取当前时间作为名字
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = df.format(current);
File curPhoto = new File(HERO_PATH, curDate + ".png");
//截屏存到手机本地
try {
while(!curPhoto.exists()) {
Process process = Runtime.getRuntime().exec(ADB_PATH
+ " shell /system/bin/screencap -p /sdcard/screenshot.png");
process.waitFor();
//将截图放在电脑本地
process = Runtime.getRuntime().exec(ADB_PATH
+ " pull /sdcard/screenshot.png " + curPhoto.getAbsolutePath());
process.waitFor();
}
//返回当前图片名字
return curPhoto;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("获取图片失败");
return null;
}
|
#vulnerable code
File getImage() {
//获取当前时间作为名字
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = df.format(current);
File curPhoto = new File(HERO_PATH, curDate + ".png");
//截屏存到手机本地
try {
while(!curPhoto.exists()) {
Runtime.getRuntime().exec(ADB_PATH
+ " shell /system/bin/screencap -p /sdcard/screenshot.png");
Thread.sleep(700);
//将截图放在电脑本地
Runtime.getRuntime().exec(ADB_PATH
+ " pull /sdcard/screenshot.png " + curPhoto.getAbsolutePath());
Thread.sleep(200);
}
//返回当前图片名字
return curPhoto;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("获取图片失败");
return null;
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
Search(String question) {
this.question = question;
}
|
#vulnerable code
Long search(String question) throws IOException {
String path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=1";
boolean findIt = false;
String line = null;
while (!findIt) {
URL url = new URL(path);
BufferedReader breaded = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = breaded.readLine()) != null) {
if (line.contains("百度为您找到相关结果约")) {
findIt = true;
int start = line.indexOf("百度为您找到相关结果约") + 11;
line = line.substring(start);
int end = line.indexOf("个");
line = line.substring(0, end);
break;
}
}
}
line = line.replace(",", "");
return Long.valueOf(line);
}
#location 23
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
Search(String question) {
this.question = question;
}
|
#vulnerable code
Long search(String question) throws IOException {
String path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=1";
boolean findIt = false;
String line = null;
while (!findIt) {
URL url = new URL(path);
BufferedReader breaded = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = breaded.readLine()) != null) {
if (line.contains("百度为您找到相关结果约")) {
findIt = true;
int start = line.indexOf("百度为您找到相关结果约") + 11;
line = line.substring(start);
int end = line.indexOf("个");
line = line.substring(0, end);
break;
}
}
}
line = line.replace(",", "");
return Long.valueOf(line);
}
#location 11
#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 {
// Setting the width and height of frame
frame.setSize(500, 800);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
try{
loadConfig();
}catch (Exception e){
initConfig();
}
loadConfig();
// 创建面板
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
addAdbPath(panel);
addImagePath(panel);
addOCRSelection(panel);
addSearchSelection(panel);
addSetFinishButton(panel);
addRunButton(panel);
addResultTextArea(panel);
addPatternSelection(panel);
// 设置界面可见
frame.setVisible(true);
}
|
#vulnerable code
public static void main(String[] args) throws IOException {
// Setting the width and height of frame
frame.setSize(500, 800);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
String path=MainGUI.class.getProtectionDomain().getCodeSource().getLocation().getFile();
path=path.substring(0,path.lastIndexOf("/"));
System.out.println(path);
File config = new File(path, "hero.config");
System.out.println(config.getAbsolutePath());
if(config.createNewFile()){
FileOutputStream fileOutputStream=new FileOutputStream(config);
fileOutputStream.write("测试".getBytes());
}else{
System.out.println("nothing");
}
System.out.println(config.getAbsolutePath());
// 创建面板
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
addAdbPath(panel);
addImagePath(panel);
addOCRSelection(panel);
addSearchSelection(panel);
addSetFinishButton(panel);
addRunButton(panel);
addResultTextArea(panel);
addPatternSelection(panel);
// 设置界面可见
frame.setVisible(true);
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
// Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql]
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
// Transform all query, SQL and HTTP
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
return sqlQuery;
}
|
#vulnerable code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
// Problme si le tag contient des caractres spciaux
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
return sqlQuery;
}
#location 68
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
// Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql]
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
// Transform all query, SQL and HTTP
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
return sqlQuery;
}
|
#vulnerable code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
// Problme si le tag contient des caractres spciaux
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
return sqlQuery;
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
// Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql]
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
// Transform all query, SQL and HTTP
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
return sqlQuery;
}
|
#vulnerable code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
// Problme si le tag contient des caractres spciaux
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
return sqlQuery;
}
#location 63
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
// Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql]
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
// Transform all query, SQL and HTTP
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
return sqlQuery;
}
|
#vulnerable code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
// Problme si le tag contient des caractres spciaux
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
return sqlQuery;
}
#location 29
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
// Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql]
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
// Transform all query, SQL and HTTP
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
return sqlQuery;
}
|
#vulnerable code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
// Problme si le tag contient des caractres spciaux
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
return sqlQuery;
}
#location 44
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void handlePostValidate(UIInput component) {
BeanValidator beanValidator = getBeanValidator(component);
if (beanValidator != null) {
String originalValidationGroups = (String) component.getAttributes().remove(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS);
beanValidator.setValidationGroups(originalValidationGroups);
}
}
|
#vulnerable code
private void handlePostValidate(UIInput component) {
final BeanValidator beanValidator = getBeanValidator(component);
final String originalValidationGroups = (String) component.getAttributes().remove(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS);
beanValidator.setValidationGroups(originalValidationGroups);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void encodeBegin(FacesContext context) throws IOException {
Components.validateHasNoChildren(this);
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
BufferedHttpServletResponse bufferedResponse = new BufferedHttpServletResponse(response);
try {
request.getRequestDispatcher((String) getAttributes().get("path")).include(request, bufferedResponse);
}
catch (ServletException e) {
throw new FacesException(e);
}
context.getResponseWriter().write(new String(bufferedResponse.getBuffer(), response.getCharacterEncoding()));
}
|
#vulnerable code
@Override
public void encodeBegin(FacesContext context) throws IOException {
Components.validateHasNoChildren(this);
try {
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// Create dispatcher for the resource given by the component's page attribute.
RequestDispatcher requestDispatcher = request.getRequestDispatcher((String) getAttributes().get("path"));
// Catch the resource's output.
CharResponseWrapper responseWrapper = new CharResponseWrapper(response);
requestDispatcher.include(request, responseWrapper);
// Write the output from the resource to the JSF response writer.
context.getResponseWriter().write(responseWrapper.toString());
}
catch (ServletException e) {
throw new IOException();
}
}
#location 18
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
if (event instanceof PreDestroyViewMapEvent) {
getReference(ViewScopeManager.class).preDestroyView();
}
}
|
#vulnerable code
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
if (event instanceof PreDestroyViewMapEvent) {
BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView();
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
public static <T> void destroy(BeanManager beanManager, T instance) {
if (instance instanceof Class) { // Java prefers T over Class<T> when varargs is not specified :(
destroy(beanManager, (Class<T>) instance, new Annotation[0]);
}
else {
Bean<T> bean = (Bean<T>) resolve(beanManager, instance.getClass());
if (bean != null) {
destroy(beanManager, bean, instance);
}
}
}
|
#vulnerable code
@SuppressWarnings("unchecked")
public static <T> void destroy(BeanManager beanManager, T instance) {
if (instance instanceof Class) {
destroy(beanManager, (Class<T>) instance, new Annotation[0]);
}
else if (instance instanceof Bean) {
destroy(beanManager, (Bean<T>) instance);
}
else {
Bean<T> bean = (Bean<T>) resolve(beanManager, instance.getClass());
bean.destroy(instance, beanManager.createCreationalContext(bean));
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
String string = submittedValue;
if (!isEmpty(string)) {
DecimalFormat formatter = getFormatter();
if (formatter != null) {
String symbol = getSymbol(formatter);
if (!string.contains(symbol)) {
string = PATTERN_NUMBER.matcher(formatter.format(0)).replaceAll(submittedValue);
}
}
}
return super.getAsObject(context, component, string);
}
|
#vulnerable code
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
String string = submittedValue;
if (!isEmpty(string)) {
DecimalFormat formatter = getFormatter();
String symbol = getSymbol(formatter);
if (!string.contains(symbol)) {
string = PATTERN_NUMBER.matcher(formatter.format(0)).replaceAll(submittedValue);
}
}
return super.getAsObject(context, component, string);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private synchronized void loadResources() {
if (!isEmpty(resources)) {
return;
}
FacesContext context = FacesContext.getCurrentInstance();
resources = new LinkedHashSet<>();
contentLength = 0;
lastModified = 0;
for (ResourceIdentifier resourceIdentifier : resourceIdentifiers) {
Resource resource = createResource(context, resourceIdentifier.getLibrary(), resourceIdentifier.getName());
if (resource == null) {
if (logger.isLoggable(WARNING)) {
logger.log(WARNING, format(LOG_RESOURCE_NOT_FOUND, resourceIdentifier, id));
}
resources.clear();
return;
}
resources.add(resource);
URLConnection connection = openConnection(context, resource);
if (connection == null) {
return;
}
contentLength += connection.getContentLength();
long resourceLastModified = connection.getLastModified();
if (resourceLastModified > lastModified) {
lastModified = resourceLastModified;
}
}
}
|
#vulnerable code
private synchronized void loadResources() {
if (!isEmpty(resources)) {
return;
}
FacesContext context = FacesContext.getCurrentInstance();
ResourceHandler handler = context.getApplication().getResourceHandler();
resources = new LinkedHashSet<>();
contentLength = 0;
lastModified = 0;
for (ResourceIdentifier resourceIdentifier : resourceIdentifiers) {
Resource resource = handler.createResource(resourceIdentifier.getName(), resourceIdentifier.getLibrary());
if (resource == null) {
if (logger.isLoggable(WARNING)) {
logger.log(WARNING, format(LOG_RESOURCE_NOT_FOUND, resourceIdentifier, id));
}
resources.clear();
return;
}
resources.add(resource);
URLConnection connection;
try {
connection = resource.getURL().openConnection();
}
catch (Exception richFacesDoesNotSupportThis) {
logger.log(FINEST, "Ignoring thrown exception; this can only be caused by a buggy component library.", richFacesDoesNotSupportThis);
try {
connection = new URL(getRequestDomainURL(context) + resource.getRequestPath()).openConnection();
}
catch (IOException ignore) {
logger.log(FINEST, "Ignoring thrown exception; cannot handle it at this point, it would be thrown during getInputStream() anyway.", ignore);
return;
}
}
contentLength += connection.getContentLength();
long resourceLastModified = connection.getLastModified();
if (resourceLastModified > lastModified) {
lastModified = resourceLastModified;
}
}
}
#location 43
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String getActionURL(FacesContext context, String viewId) {
String actionURL = super.getActionURL(context, viewId);
ServletContext servletContext = getServletContext(context);
Map<String, String> mappedResources = getMappedResources(servletContext);
if (mappedResources.containsKey(viewId) && (extensionless || isOriginalViewExtensionless(context))) {
// User has requested to always render extensionless, or the requested viewId was mapped and the current
// request is extensionless; render the action URL extensionless as well.
String pathInfo = context.getViewRoot().getViewId().equals(viewId) ? coalesce(getRequestPathInfo(context), "") : "";
String queryString = getQueryString(actionURL);
if (mode == BUILD_WITH_PARENT_QUERY_PARAMETERS) {
return getRequestContextPath(context) + stripExtension(viewId) + pathInfo + queryString;
}
else {
actionURL = removeExtension(servletContext, actionURL, viewId);
return (pathInfo.isEmpty() ? actionURL : (stripTrailingSlash(actionURL) + pathInfo)) + queryString;
}
}
// Not a resource we mapped or not a forwarded one, take the version from the parent view handler.
return actionURL;
}
|
#vulnerable code
@Override
public String getActionURL(FacesContext context, String viewId) {
String actionURL = super.getActionURL(context, viewId);
ServletContext servletContext = getServletContext(context);
Map<String, String> mappedResources = getMappedResources(servletContext);
if (mappedResources.containsKey(viewId) && (extensionless || isOriginalViewExtensionless(context))) {
// User has requested to always render extensionless, or the requested viewId was mapped and the current
// request is extensionless; render the action URL extensionless as well.
String pathInfo = context.getViewRoot().getViewId().equals(viewId) ? coalesce(getRequestPathInfo(context), "") : "";
if (mode == BUILD_WITH_PARENT_QUERY_PARAMETERS) {
return getRequestContextPath(context) + stripExtension(viewId) + pathInfo + getQueryString(actionURL);
}
else {
actionURL = removeExtension(servletContext, actionURL, viewId);
return pathInfo.isEmpty() ? actionURL : (stripTrailingSlash(actionURL) + pathInfo + getQueryString(actionURL));
}
}
// Not a resource we mapped or not a forwarded one, take the version from the parent view handler.
return actionURL;
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void encodeChildren(FacesContext context) throws IOException {
if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) {
throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED);
}
String channel = getChannel();
if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channel));
}
boolean connected = isConnected();
Boolean switched = hasSwitched(context, channel, connected);
String script = null;
if (switched == null) {
Integer port = getPort();
String host = (port != null ? ":" + port : "") + getRequestContextPath(context);
String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser());
String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose();
script = String.format(SCRIPT_INIT, host, channelId, functions, getBehaviorScripts(), connected);
}
else if (switched) {
script = String.format(connected ? SCRIPT_OPEN : SCRIPT_CLOSE, channel);
}
if (script != null) {
context.getResponseWriter().write(script);
}
rendered = super.isRendered();
}
|
#vulnerable code
@Override
public void encodeChildren(FacesContext context) throws IOException {
if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) {
throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED);
}
String channel = getChannel();
if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channel));
}
boolean connected = isConnected();
Boolean switched = hasSwitched(context, channel, connected);
String script = null;
if (switched == null) {
Integer port = getPort();
String host = (port != null ? ":" + port : "") + getRequestContextPath(context);
String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser());
String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose();
script = String.format(SCRIPT_INIT, host, channelId, functions, getBehaviorScripts(), connected);
}
else if (switched) {
script = String.format(connected ? SCRIPT_OPEN : SCRIPT_CLOSE, channel);
}
if (script != null) {
context.getResponseWriter().write(script);
}
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void apply(FaceletContext context, UIComponent parent) throws IOException {
if (!ComponentHandler.isNew(parent)) {
return;
}
if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) {
throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED);
}
String channelName = channel.getValue(context);
if (!PATTERN_CHANNEL.matcher(channelName).matches()) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channelName));
}
SocketChannelManager channelManager = getReference(SocketChannelManager.class);
String scopeName = getString(context, scope);
String channelId;
try {
channelId = channelManager.register(channelName, scopeName);
}
catch (IllegalArgumentException ignore) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_SCOPE, scopeName));
}
if (channelId == null) {
throw new IllegalArgumentException(String.format(ERROR_DUPLICATE_CHANNEL, channelName));
}
Integer portNumber = getObject(context, port, Integer.class);
String onmessageFunction = onmessage.getValue(context);
String oncloseFunction = getString(context, onclose);
String functions = onmessageFunction + "," + oncloseFunction;
ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class);
SystemEventListener listener = new SocketEventListener(portNumber, channelName, channelId, functions, connectedExpression);
subscribeToViewEvent(PostAddToViewEvent.class, listener);
subscribeToViewEvent(PreRenderViewEvent.class, listener);
}
|
#vulnerable code
@Override
public void apply(FaceletContext context, UIComponent parent) throws IOException {
if (!ComponentHandler.isNew(parent)) {
return;
}
if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) {
throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED);
}
String channelName = channel.getValue(context);
if (!PATTERN_CHANNEL.matcher(channelName).matches()) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channelName));
}
SocketScopeManager scopeManager = getReference(SocketScopeManager.class);
String scopeName = getString(context, scope);
String scopeId;
try {
scopeId = scopeManager.register(channelName, scopeName);
}
catch (IllegalArgumentException ignore) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_SCOPE, scopeName));
}
if (scopeId == null) {
throw new IllegalArgumentException(String.format(ERROR_DUPLICATE_CHANNEL, channelName));
}
Integer portNumber = getObject(context, port, Integer.class);
String onmessageFunction = onmessage.getValue(context);
String oncloseFunction = getString(context, onclose);
String functions = onmessageFunction + "," + oncloseFunction;
ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class);
SystemEventListener listener = new SocketEventListener(portNumber, channelName, scopeId, functions, connectedExpression);
subscribeToViewEvent(PostAddToViewEvent.class, listener);
subscribeToViewEvent(PreRenderViewEvent.class, listener);
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static InjectionPoint getCurrentInjectionPoint(BeanManager beanManager, CreationalContext<?> creationalContext) {
Bean<InjectionPointGenerator> bean = resolve(beanManager, InjectionPointGenerator.class);
return (bean != null) ? (InjectionPoint) beanManager.getInjectableReference(bean.getInjectionPoints().iterator().next(), creationalContext) : null;
}
|
#vulnerable code
public static InjectionPoint getCurrentInjectionPoint(BeanManager beanManager, CreationalContext<?> creationalContext) {
return (InjectionPoint) beanManager.getInjectableReference(
resolve(beanManager, InjectionPointGenerator.class).getInjectionPoints().iterator().next(), creationalContext
);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void processAction(ActionEvent event) throws AbortProcessingException {
FacesContext context = FacesContext.getCurrentInstance();
PartialViewContext partialViewContext = context.getPartialViewContext();
if (partialViewContext.isAjaxRequest()) {
Collection<String> renderIds = getRenderIds(partialViewContext);
Collection<String> executeIds = partialViewContext.getExecuteIds();
if (!renderIds.isEmpty() && !renderIds.containsAll(executeIds)) {
resetEditableValueHolders(VisitContext.createVisitContext(
context, renderIds, VISIT_HINTS), context.getViewRoot(), executeIds);
}
}
if (wrapped != null && event != null) {
wrapped.processAction(event);
}
}
|
#vulnerable code
@Override
public void processAction(ActionEvent event) throws AbortProcessingException {
FacesContext context = FacesContext.getCurrentInstance();
PartialViewContext partialViewContext = context.getPartialViewContext();
if (partialViewContext.isAjaxRequest()) {
Collection<String> renderIds = getRenderIds(partialViewContext);
Collection<String> executeIds = partialViewContext.getExecuteIds();
if (!renderIds.isEmpty() && !renderIds.containsAll(executeIds)) {
final Set<EditableValueHolder> inputs = new HashSet<EditableValueHolder>();
// First find all to be rendered inputs in the current view and add them to the set.
findAndAddEditableValueHolders(VisitContext.createVisitContext(
context, renderIds, VISIT_HINTS), context.getViewRoot(), inputs);
// Then find all executed inputs in the current form and remove them from the set.
findAndRemoveEditableValueHolders(VisitContext.createVisitContext(
context, executeIds, VISIT_HINTS), Components.getCurrentForm(), inputs);
// The set now contains inputs which are to be rendered, but which are not been executed. Reset them.
for (EditableValueHolder input : inputs) {
input.resetValue();
}
}
}
if (wrapped != null && event != null) {
wrapped.processAction(event);
}
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void prepareRemotingContainer() throws IOException, InterruptedException {
// if remoting container already exists, we reuse it
if (context.getRemotingContainer() != null) {
if (driver.hasContainer(localLauncher, context.getRemotingContainer().getId())) {
return;
}
}
final ContainerInstance remotingContainer = driver.createRemotingContainer(localLauncher, remotingImage);
context.setRemotingContainer(remotingContainer);
}
|
#vulnerable code
public void prepareRemotingContainer() throws IOException, InterruptedException {
// if remoting container already exists, we reuse it
if (context.getRemotingContainer() != null) {
if (driver.hasContainer(localLauncher, context.getRemotingContainer())) {
return;
}
}
driver.createRemotingContainer(localLauncher, context.getRemotingContainer());
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public BxDocument getDocument() throws TransformationException {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(inputStream, "UTF-8");
TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader();
return new BxDocument().setPages(reader.read(isr));
} catch (UnsupportedEncodingException ex) {
throw new TransformationException("Unsupported encoding!", ex);
} finally {
try {
if (isr != null) {
isr.close();
}
} catch (IOException ex) {
Logger.getLogger(FileExtractor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
#vulnerable code
public BxDocument getDocument() throws TransformationException {
InputStreamReader isr = new InputStreamReader(inputStream);
TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader();
return new BxDocument().setPages(reader.read(isr));
}
#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 AnalysisException, TransformationException, IOException {
// args[0] path to xml directory
if(args.length != 1) {
System.err.println("Source directory needed!");
System.exit(1);
}
SVMInitialZoneClassifier classifier = new SVMInitialZoneClassifier("/pl/edu/icm/cermine/structure/svm_initial_classifier",
"/pl/edu/icm/cermine/structure/svm_initial_classifier.range");
ReadingOrderResolver ror = new HierarchicalReadingOrderResolver();
BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter();
List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]);
for(BxDocument doc: docs) {
System.out.println(">> " + doc.getFilename());
ror.resolve(doc);
classifier.classifyZones(doc);
BufferedWriter out = null;
try {
// Create file
FileWriter fstream = new FileWriter(doc.getFilename());
out = new BufferedWriter(fstream);
out.write(tvw.write(doc.getPages()));
out.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
} finally {
if(out != null) {
out.close();
}
}
}
}
|
#vulnerable code
public static void main(String[] args) throws AnalysisException, TransformationException, IOException {
// args[0] path to xml directory
if(args.length != 1) {
System.err.println("Source directory needed!");
System.exit(1);
}
InputStreamReader modelISR = new InputStreamReader(Thread.currentThread().getClass()
.getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier"));
BufferedReader modelFile = new BufferedReader(modelISR);
InputStreamReader rangeISR = new InputStreamReader(Thread.currentThread().getClass()
.getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier.range"));
BufferedReader rangeFile = new BufferedReader(rangeISR);
SVMZoneClassifier classifier = new SVMInitialZoneClassifier(modelFile, rangeFile);
ReadingOrderResolver ror = new HierarchicalReadingOrderResolver();
BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter();
List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]);
for(BxDocument doc: docs) {
System.out.println(">> " + doc.getFilename());
ror.resolve(doc);
classifier.classifyZones(doc);
BufferedWriter out = null;
try {
// Create file
FileWriter fstream = new FileWriter(doc.getFilename());
out = new BufferedWriter(fstream);
out.write(tvw.write(doc.getPages()));
out.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
} finally {
if(out != null) {
out.close();
}
}
}
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) throws IOException {
BufferedWriter svmDataFile = null;
try {
FileWriter fstream = new FileWriter(filePath);
svmDataFile = new BufferedWriter(fstream);
for (TrainingElement<BxZoneLabel> elem : trainingElements) {
svmDataFile.write(String.valueOf(elem.getLabel().ordinal()));
svmDataFile.write(" ");
Integer featureCounter = 1;
for (Double value : elem.getObservation().getFeatures()) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%d:%.5f", featureCounter++, value);
svmDataFile.write(sb.toString());
svmDataFile.write(" ");
}
svmDataFile.write("\n");
}
svmDataFile.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return;
} finally {
if(svmDataFile != null) {
svmDataFile.close();
}
}
System.out.println("Done.");
}
|
#vulnerable code
public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) {
try {
FileWriter fstream = new FileWriter(filePath);
BufferedWriter svmDataFile = new BufferedWriter(fstream);
for (TrainingElement<BxZoneLabel> elem : trainingElements) {
svmDataFile.write(String.valueOf(elem.getLabel().ordinal()));
svmDataFile.write(" ");
Integer featureCounter = 1;
for (Double value : elem.getObservation().getFeatures()) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%d:%.5f", featureCounter++, value);
svmDataFile.write(sb.toString());
svmDataFile.write(" ");
}
svmDataFile.write("\n");
}
svmDataFile.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return;
}
System.out.println("Done.");
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<BxDocument> getDocuments() throws TransformationException {
String dirPath = directory.getPath();
TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
List<BxDocument> documents = new ArrayList<BxDocument>();
if (!dirPath.endsWith(File.separator)) {
dirPath += File.separator;
}
for (String filename : directory.list()) {
if (!new File(dirPath + filename).isFile()) {
continue;
}
if (filename.endsWith("xml")) {
InputStream is = null;
try {
is = new FileInputStream(dirPath + filename);
List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8"));
BxDocument newDoc = new BxDocument();
for (BxPage page : pages) {
page.setParent(newDoc);
}
newDoc.setFilename(filename);
newDoc.setPages(pages);
documents.add(newDoc);
} catch (IllegalStateException ex) {
System.err.println(ex.getMessage());
System.err.println(dirPath + filename);
throw ex;
} catch (FileNotFoundException ex) {
throw new TransformationException("File not found!", ex);
} catch (UnsupportedEncodingException ex) {
throw new TransformationException("Unsupported encoding!", ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
throw new TransformationException("Cannot close stream!", ex);
}
}
}
}
}
return documents;
}
|
#vulnerable code
@Override
public List<BxDocument> getDocuments() throws TransformationException {
String dirPath = directory.getPath();
TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
List<BxDocument> documents = new ArrayList<BxDocument>();
if (!dirPath.endsWith(File.separator)) {
dirPath += File.separator;
}
for (String filename : directory.list()) {
if (!new File(dirPath + filename).isFile()) {
continue;
}
if (filename.endsWith("xml")) {
InputStream is = null;
try {
is = new FileInputStream(dirPath + filename);
List<BxPage> pages = tvReader.read(new InputStreamReader(is));
BxDocument newDoc = new BxDocument();
for (BxPage page : pages) {
page.setParent(newDoc);
}
newDoc.setFilename(filename);
newDoc.setPages(pages);
documents.add(newDoc);
} catch (IllegalStateException ex) {
System.err.println(ex.getMessage());
System.err.println(dirPath + filename);
throw ex;
} catch (FileNotFoundException ex) {
throw new TransformationException("File not found!", ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
throw new TransformationException("Cannot close stream!", ex);
}
}
}
}
}
return documents;
}
#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 main(String[] args) throws ParseException, IOException, TransformationException, AnalysisException, CloneNotSupportedException {
Options options = new Options();
options.addOption("under", false, "use undersampling for data selection");
options.addOption("over", false, "use oversampling for data selection");
options.addOption("normal", false, "don't use any special strategy for data selection");
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(options, args);
if (args.length != 2 || !(line.hasOption("under") ^ line.hasOption("over") ^ line.hasOption("normal"))) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(" [-options] input-directory", options);
System.exit(1);
}
String inputDirPath = line.getArgs()[0];
File inputDirFile = new File(inputDirPath);
SampleSelector<BxZoneLabel> sampler = null;
if (line.hasOption("over")) {
sampler = new OversamplingSelector<BxZoneLabel>(1.0);
} else if (line.hasOption("under")) {
sampler = new UndersamplingSelector<BxZoneLabel>(1.0);
} else if (line.hasOption("normal")) {
sampler = new NormalSelector<BxZoneLabel>();
} else {
System.err.println("Sampling pattern is not specified!");
System.exit(1);
}
List<TrainingSample<BxZoneLabel>> initialTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>();
List<TrainingSample<BxZoneLabel>> metaTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>();
HierarchicalReadingOrderResolver ror = new HierarchicalReadingOrderResolver();
EvaluationUtils.DocumentsIterator iter = new DocumentsIterator(inputDirPath);
FeatureVectorBuilder<BxZone, BxPage> vectorBuilder;
Integer docIdx = 0;
for(BxDocument doc: iter) {
doc = ror.resolve(doc);
System.out.println(docIdx + ": " + doc.getFilename());
String filename = doc.getFilename();
doc = ror.resolve(doc);
doc.setFilename(filename);
////
for (BxZone zone : doc.asZones()) {
if (zone.getLabel() != null) {
if (zone.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) {
zone.setLabel(zone.getLabel().getGeneralLabel());
}
}
else {
zone.setLabel(BxZoneLabel.OTH_UNKNOWN);
}
}
vectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder();
List<TrainingSample<BxZoneLabel>> newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getIdentityMap());
for(TrainingSample<BxZoneLabel> sample: newSamples) {
if(sample.getLabel().getCategory() == BxZoneLabelCategory.CAT_METADATA) {
metaTrainingElements.add(sample);
}
}
////
vectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder();
newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getLabelToGeneralMap());
initialTrainingElements.addAll(newSamples);
////
++docIdx;
}
initialTrainingElements = sampler.pickElements(initialTrainingElements);
metaTrainingElements = sampler.pickElements(metaTrainingElements);
toLibSVM(initialTrainingElements, "initial_" + inputDirFile.getName() + ".dat");
toLibSVM(metaTrainingElements, "meta_" + inputDirFile.getName() + ".dat");
}
|
#vulnerable code
public static void main(String[] args) throws ParseException, IOException, TransformationException, AnalysisException {
Options options = new Options();
options.addOption("under", false, "use undersampling for data selection");
options.addOption("over", false, "use oversampling for data selection");
options.addOption("normal", false, "don't use any special strategy for data selection");
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(options, args);
if (args.length != 2 || !(line.hasOption("under") ^ line.hasOption("over") ^ line.hasOption("normal"))) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(" [-options] input-directory", options);
System.exit(1);
}
String inputDirPath = line.getArgs()[0];
File inputDirFile = new File(inputDirPath);
SampleSelector<BxZoneLabel> sampler = null;
if (line.hasOption("over")) {
sampler = new OversamplingSelector<BxZoneLabel>(1.0);
} else if (line.hasOption("under")) {
sampler = new UndersamplingSelector<BxZoneLabel>(2.0);
} else if (line.hasOption("normal")) {
sampler = new NormalSelector<BxZoneLabel>();
} else {
System.err.println("Sampling pattern is not specified!");
System.exit(1);
}
List<TrainingSample<BxZoneLabel>> initialTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>();
List<TrainingSample<BxZoneLabel>> metaTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>();
EvaluationUtils.DocumentsIterator iter = new DocumentsIterator(inputDirPath);
FeatureVectorBuilder<BxZone, BxPage> vectorBuilder;
Integer docIdx = 0;
for(BxDocument doc: iter) {
System.out.println(docIdx + ": " + doc.getFilename());
////
for (BxZone zone : doc.asZones()) {
if (zone.getLabel() != null) {
if (zone.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) {
zone.setLabel(zone.getLabel().getGeneralLabel());
}
}
else {
zone.setLabel(BxZoneLabel.OTH_UNKNOWN);
}
}
vectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder();
List<TrainingSample<BxZoneLabel>> newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getIdentityMap());
for(TrainingSample<BxZoneLabel> sample: newSamples) {
if(sample.getLabel().getCategory() == BxZoneLabelCategory.CAT_METADATA) {
metaTrainingElements.add(sample);
}
}
////
vectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder();
newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getLabelToGeneralMap());
initialTrainingElements.addAll(newSamples);
////
++docIdx;
}
initialTrainingElements = sampler.pickElements(initialTrainingElements);
metaTrainingElements = sampler.pickElements(metaTrainingElements);
toLibSVM(initialTrainingElements, "initial_" + inputDirFile.getName() + ".dat");
toLibSVM(metaTrainingElements, "meta_" + inputDirFile.getName() + ".dat");
}
#location 37
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException {
BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath), "UTF-8"));
BufferedReader rangeFile = null;
if (rangeFilePath != null) {
rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath), "UTF-8"));
}
loadModelFromFile(modelFile, rangeFile);
}
|
#vulnerable code
public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException {
BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath)));
BufferedReader rangeFile = null;
if (rangeFilePath != null) {
rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath)));
}
loadModelFromFile(modelFile, rangeFile);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<BxDocument> getDocuments() throws TransformationException {
TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
List<BxDocument> documents = new ArrayList<BxDocument>();
for (File file : FileUtils.listFiles(directory, new String[]{"xml"}, true)) {
InputStream is = null;
try {
is = new FileInputStream(file);
List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8"));
BxDocument doc = new BxDocument();
doc.setFilename(file.getName());
doc.setPages(pages);
documents.add(doc);
} catch (FileNotFoundException ex) {
throw new TransformationException(ex);
} catch (UnsupportedEncodingException ex) {
throw new TransformationException(ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
throw new TransformationException("Cannot close stream!", ex);
}
}
}
}
return documents;
}
|
#vulnerable code
@Override
public List<BxDocument> getDocuments() throws TransformationException {
TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
List<BxDocument> documents = new ArrayList<BxDocument>();
for (File file : FileUtils.listFiles(directory, new String[]{"xml"}, true)) {
InputStream is = null;
try {
is = new FileInputStream(file);
List<BxPage> pages = tvReader.read(new InputStreamReader(is));
BxDocument doc = new BxDocument();
doc.setFilename(file.getName());
doc.setPages(pages);
documents.add(doc);
} catch (FileNotFoundException ex) {
throw new TransformationException(ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
throw new TransformationException("Cannot close stream!", ex);
}
}
}
}
return documents;
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testSegmentPages() throws TransformationException, AnalysisException, UnsupportedEncodingException {
Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml"), "UTF-8");
BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader));
new UnsegmentedPagesFlattener().process(inDoc);
DocstrumSegmenter pageSegmenter = new ParallelDocstrumSegmenter();
BxDocument outDoc = pageSegmenter.segmentDocument(inDoc);
// Check whether zones are correctly detected
assertEquals(1, outDoc.childrenCount());
// Check whether lines are correctly detected
List<BxZone> outZones = Lists.newArrayList(outDoc.getFirstChild());
assertEquals(3, outZones.size());
assertEquals(3, outZones.get(0).childrenCount());
assertEquals(16, outZones.get(1).childrenCount());
assertEquals(16, outZones.get(2).childrenCount());
assertEquals(24, outZones.get(1).getFirstChild().childrenCount());
assertEquals("A", outZones.get(1).getFirstChild().getFirstChild().toText());
for (BxZone zone : outZones) {
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
assertContains(zone.getBounds(), chunk.getBounds());
}
assertContains(zone.getBounds(), word.getBounds());
}
assertContains(zone.getBounds(), line.getBounds());
}
}
assertNotNull(outDoc.getFirstChild().getBounds());
}
|
#vulnerable code
@Test
public void testSegmentPages() throws TransformationException, AnalysisException {
Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml"));
BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader));
new UnsegmentedPagesFlattener().process(inDoc);
DocstrumSegmenter pageSegmenter = new ParallelDocstrumSegmenter();
BxDocument outDoc = pageSegmenter.segmentDocument(inDoc);
// Check whether zones are correctly detected
assertEquals(1, outDoc.childrenCount());
// Check whether lines are correctly detected
List<BxZone> outZones = Lists.newArrayList(outDoc.getFirstChild());
assertEquals(3, outZones.size());
assertEquals(3, outZones.get(0).childrenCount());
assertEquals(16, outZones.get(1).childrenCount());
assertEquals(16, outZones.get(2).childrenCount());
assertEquals(24, outZones.get(1).getFirstChild().childrenCount());
assertEquals("A", outZones.get(1).getFirstChild().getFirstChild().toText());
for (BxZone zone : outZones) {
for (BxLine line : zone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
assertContains(zone.getBounds(), chunk.getBounds());
}
assertContains(zone.getBounds(), word.getBounds());
}
assertContains(zone.getBounds(), line.getBounds());
}
}
assertNotNull(outDoc.getFirstChild().getBounds());
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException {
InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath), "UTF-8");
BufferedReader modelFile = new BufferedReader(modelISR);
InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath), "UTF-8");
BufferedReader rangeFile = new BufferedReader(rangeISR);
loadModelFromFile(modelFile, rangeFile);
}
|
#vulnerable code
public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException {
InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath));
BufferedReader modelFile = new BufferedReader(modelISR);
InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath));
BufferedReader rangeFile = new BufferedReader(rangeISR);
loadModelFromFile(modelFile, rangeFile);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException {
BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath), "UTF-8"));
BufferedReader rangeFile = null;
if (rangeFilePath != null) {
rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath), "UTF-8"));
}
loadModelFromFile(modelFile, rangeFile);
}
|
#vulnerable code
public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException {
BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath)));
BufferedReader rangeFile = null;
if (rangeFilePath != null) {
rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath)));
}
loadModelFromFile(modelFile, rangeFile);
}
#location 7
#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 JDOMException, IOException, AnalysisException {
if (args.length != 3) {
System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>");
System.exit(1);
}
int foldness = Integer.parseInt(args[0]);
String modelPathSuffix = args[1];
String testPathSuffix = args[2];
Map<String, List<Result>> results = new HashMap<String, List<Result>>();
for (int i = 0; i < foldness; i++) {
System.out.println("Fold "+i);
String modelPath = modelPathSuffix + i;
CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath);
String testPath = testPathSuffix + i;
File testFile = new File(testPath);
List<Citation> testCitations;
InputStream testIS = null;
try {
testIS = new FileInputStream(testFile);
InputSource testSource = new InputSource(testIS);
testCitations = NlmCitationExtractor.extractCitations(testSource);
} finally {
if (testIS != null) {
testIS.close();
}
}
System.out.println(testCitations.size());
List<BibEntry> testEntries = new ArrayList<BibEntry>();
for (Citation c : testCitations) {
BibEntry entry = CitationUtils.citationToBibref(c);
testEntries.add(entry);
for (String key : entry.getFieldKeys()) {
if (results.get(key) == null) {
results.put(key, new ArrayList<Result>());
}
}
}
int j = 0;
for (BibEntry orig : testEntries) {
BibEntry test = parser.parseBibReference(orig.getText());
System.out.println();
System.out.println();
System.out.println(orig.toBibTeX());
System.out.println(test.toBibTeX());
Map<String, Result> map = new HashMap<String, Result>();
for (String s : orig.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addOrig(orig.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addExtr(test.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
List<String> origVals = orig.getAllFieldValues(s);
for (String testVal : test.getAllFieldValues(s)) {
boolean found = false;
if (origVals.contains(testVal)) {
map.get(s).addSuccess();
origVals.remove(testVal);
found = true;
}
if (!found) {
System.out.println("WRONG "+s);
}
}
}
for (Map.Entry<String, Result> s : map.entrySet()) {
System.out.println("");
System.out.println(s.getKey());
System.out.println(s.getValue());
System.out.println(s.getValue().getPrecision());
System.out.println(s.getValue().getRecall());
results.get(s.getKey()).add(s.getValue());
}
j++;
System.out.println("Tested "+j+" out of "+testEntries.size());
}
}
for (Map.Entry<String, List<Result>> e : results.entrySet()) {
System.out.println("");
System.out.println(e.getKey());
System.out.println(e.getValue().size());
double precision = 0;
int precisionCount = 0;
double recall = 0;
int recallCount = 0;
for (Result r : e.getValue()) {
if (r.getPrecision() != null) {
precision += r.getPrecision();
precisionCount++;
}
if (r.getRecall() != null) {
recall += r.getRecall();
recallCount++;
}
}
System.out.println("Precision count "+precisionCount);
System.out.println("Mean precision "+(precision / precisionCount));
System.out.println("Recall count "+recallCount);
System.out.println("Mean recall "+(recall / recallCount));
}
}
|
#vulnerable code
public static void main(String[] args) throws JDOMException, IOException, AnalysisException {
if (args.length != 3) {
System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>");
System.exit(1);
}
int foldness = Integer.parseInt(args[0]);
String modelPathSuffix = args[1];
String testPathSuffix = args[2];
Map<String, List<Result>> results = new HashMap<String, List<Result>>();
for (int i = 0; i < foldness; i++) {
System.out.println("Fold "+i);
String modelPath = modelPathSuffix + i;
CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath);
String testPath = testPathSuffix + i;
File testFile = new File(testPath);
List<Citation> testCitations;
InputStream testIS = null;
try {
testIS = new FileInputStream(testFile);
InputSource testSource = new InputSource(testIS);
testCitations = NlmCitationExtractor.extractCitations(testSource);
} finally {
if (testIS != null) {
testIS.close();
}
}
System.out.println(testCitations.size());
List<BibEntry> testEntries = new ArrayList<BibEntry>();
for (Citation c : testCitations) {
BibEntry entry = CitationUtils.citationToBibref(c);
testEntries.add(entry);
for (String key : entry.getFieldKeys()) {
if (results.get(key) == null) {
results.put(key, new ArrayList<Result>());
}
}
}
int j = 0;
for (BibEntry orig : testEntries) {
BibEntry test = parser.parseBibReference(orig.getText());
System.out.println();
System.out.println();
System.out.println(orig.toBibTeX());
System.out.println(test.toBibTeX());
Map<String, Result> map = new HashMap<String, Result>();
for (String s : orig.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addOrig(orig.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addExtr(test.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
List<String> origVals = orig.getAllFieldValues(s);
for (String testVal : test.getAllFieldValues(s)) {
boolean found = false;
if (origVals.contains(testVal)) {
map.get(s).addSuccess();
origVals.remove(testVal);
found = true;
}
if (!found) {
System.out.println("WRONG "+s);
}
}
}
for (Map.Entry<String, Result> s : map.entrySet()) {
System.out.println("");
System.out.println(s.getKey());
System.out.println(s.getValue());
System.out.println(s.getValue().getPrecision());
System.out.println(s.getValue().getRecall());
results.get(s.getKey()).add(s.getValue());
}
j++;
System.out.println("Tested "+j+" out of "+testEntries.size());
}
}
for (String s : results.keySet()) {
System.out.println("");
System.out.println(s);
System.out.println(results.get(s).size());
double precision = 0;
int precisionCount = 0;
double recall = 0;
int recallCount = 0;
for (Result r : results.get(s)) {
if (r.getPrecision() != null) {
precision += r.getPrecision();
precisionCount++;
}
if (r.getRecall() != null) {
recall += r.getRecall();
recallCount++;
}
}
System.out.println("Precision count "+precisionCount);
System.out.println("Mean precision "+(precision / precisionCount));
System.out.println("Recall count "+recallCount);
System.out.println("Mean recall "+(recall / recallCount));
}
}
#location 103
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException
{
InputStreamReader modelISR = new InputStreamReader(this.getClass().getResourceAsStream(modelFilePath));
BufferedReader modelFile = new BufferedReader(modelISR);
InputStreamReader rangeISR = new InputStreamReader(this.getClass().getResourceAsStream(rangeFilePath));
BufferedReader rangeFile = new BufferedReader(rangeISR);
loadModelFromFile(modelFile, rangeFile);
}
|
#vulnerable code
public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException
{
InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class
.getResourceAsStream(modelFilePath));
BufferedReader modelFile = new BufferedReader(modelISR);
BufferedReader rangeFile = null;
if (rangeFilePath != null) {
InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class
.getResourceAsStream(rangeFilePath));
rangeFile = new BufferedReader(rangeISR);
}
loadModelFromFile(modelFile, rangeFile);
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException {
InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath), "UTF-8");
BufferedReader modelFile = new BufferedReader(modelISR);
InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath), "UTF-8");
BufferedReader rangeFile = new BufferedReader(rangeISR);
loadModelFromFile(modelFile, rangeFile);
}
|
#vulnerable code
public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException {
InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath));
BufferedReader modelFile = new BufferedReader(modelISR);
InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath));
BufferedReader rangeFile = new BufferedReader(rangeISR);
loadModelFromFile(modelFile, rangeFile);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void writeToXml() throws Exception {
// 排版缩进的格式
OutputFormat format = OutputFormat.createPrettyPrint();
// 设置编码
format.setEncoding("UTF-8");
// 创建XMLWriter对象,指定了写出文件及编码格式
XMLWriter writer = null;
writer = new XMLWriter(
new OutputStreamWriter(new FileOutputStream(new File(ConstantsTools.PATH_CONFIG)), StandardCharsets.UTF_8), format);
// 写入
writer.write(document);
writer.flush();
writer.close();
}
|
#vulnerable code
public void writeToXml() throws Exception {
// 排版缩进的格式
OutputFormat format = OutputFormat.createPrettyPrint();
// 设置编码
format.setEncoding("UTF-8");
// 创建XMLWriter对象,指定了写出文件及编码格式
XMLWriter writer = null;
writer = new XMLWriter(
new OutputStreamWriter(new FileOutputStream(new File(ConstantsTools.PATH_CONFIG)), "UTF-8"), format);
// 写入
writer.write(document);
writer.flush();
writer.close();
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void clearDirectiory(String dir) {
File dirFile = new File(dir);
for (File file : Objects.requireNonNull(dirFile.listFiles())) {
file.delete();
}
}
|
#vulnerable code
public static void clearDirectiory(String dir) {
File dirFile = new File(dir);
for (File file : dirFile.listFiles()) {
file.delete();
}
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte[] buffer = new byte[8192];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
#vulnerable code
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[8192];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
GitHub(String apiUrl, String login, String oauthAccessToken, String jwtToken, String password,
HttpConnector connector, RateLimitHandler rateLimitHandler, AbuseLimitHandler abuseLimitHandler)
throws IOException {
if (apiUrl.endsWith("/"))
apiUrl = apiUrl.substring(0, apiUrl.length() - 1); // normalize
this.apiUrl = apiUrl;
if (null != connector)
this.connector = connector;
if (oauthAccessToken != null) {
encodedAuthorization = "token " + oauthAccessToken;
} else {
if (jwtToken != null) {
encodedAuthorization = "Bearer " + jwtToken;
} else if (password != null) {
String authorization = (login + ':' + password);
String charsetName = Charsets.UTF_8.name();
encodedAuthorization = "Basic "
+ new String(Base64.encodeBase64(authorization.getBytes(charsetName)), charsetName);
} else {// anonymous access
encodedAuthorization = null;
}
}
users = new ConcurrentHashMap<String, GHUser>();
orgs = new ConcurrentHashMap<String, GHOrganization>();
this.rateLimitHandler = rateLimitHandler;
this.abuseLimitHandler = abuseLimitHandler;
if (login == null && encodedAuthorization != null && jwtToken == null)
login = getMyself().getLogin();
this.login = login;
}
|
#vulnerable code
<T extends GHMetaExamples.GHMetaExample> GHMetaExamples.GHMetaExample getMetaExample(Class<T> clazz)
throws IOException {
return retrieve().to("/meta", clazz);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public <T> T to(URL url, Class<T> type) throws IOException {
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-type","application/x-www-form-urlencoded");
uc.setRequestMethod("POST");
StringBuilder body = new StringBuilder();
for (Entry<String, String> e : args.entrySet()) {
if (body.length()>0) body.append('&');
body.append(URLEncoder.encode(e.getKey(),"UTF-8"));
body.append('=');
body.append(URLEncoder.encode(e.getValue(),"UTF-8"));
}
OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8");
o.write(body.toString());
o.close();
try {
InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8");
if (type==null) {
String data = IOUtils.toString(r);
return null;
}
return MAPPER.readValue(r,type);
} catch (IOException e) {
throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e);
}
}
|
#vulnerable code
public <T> T to(URL url, Class<T> type) throws IOException {
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-type","application/x-www-form-urlencoded");
uc.setRequestMethod("POST");
StringBuilder body = new StringBuilder();
for (Entry<String, String> e : args.entrySet()) {
if (body.length()>0) body.append('&');
body.append(URLEncoder.encode(e.getKey(),"UTF-8"));
body.append('=');
body.append(URLEncoder.encode(e.getValue(),"UTF-8"));
}
OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8");
o.write(body.toString());
o.close();
try {
InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8");
if (type==null) return null;
return MAPPER.readValue(r,type);
} catch (IOException e) {
throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e);
}
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static PagedIterable<GHDiscussion> readAll(GHTeam team) throws IOException {
return team.root.createRequest()
.setRawUrlPath(getRawUrlPath(team, null))
.toIterable(GHDiscussion[].class, item -> item.wrapUp(team));
}
|
#vulnerable code
static PagedIterable<GHDiscussion> readAll(GHTeam team) throws IOException {
return team.root.createRequest()
.setRawUrlPath(team.getUrl().toString() + "/discussions")
.toIterable(GHDiscussion[].class, item -> item.wrapUp(team));
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static GHDiscussion read(GHTeam team, long discussionNumber) throws IOException {
return team.root.createRequest()
.setRawUrlPath(getRawUrlPath(team, discussionNumber))
.fetch(GHDiscussion.class)
.wrapUp(team);
}
|
#vulnerable code
static GHDiscussion read(GHTeam team, long discussionNumber) throws IOException {
return team.root.createRequest()
.setRawUrlPath(team.getUrl().toString() + "/discussions/" + discussionNumber)
.fetch(GHDiscussion.class)
.wrapUp(team);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void delete() throws IOException {
team.root.createRequest().method("DELETE").setRawUrlPath(getRawUrlPath(team, number)).send();
}
|
#vulnerable code
public void delete() throws IOException {
team.root.createRequest()
.method("DELETE")
.setRawUrlPath(team.getUrl().toString() + "/discussions/" + number)
.send();
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testWindowPeer() throws Exception {
if (Platform.isMacOSX() ||
System.getProperty("java.version").matches("1\\.6\\..*")) {
// Oracle Java and jawt: it's complicated.
// See http://forum.lwjgl.org/index.php?topic=4326.0
// OpenJDK 6 + Linux seem problematic too.
return;
}
assertEquals(6 * Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurface.class));
assertEquals(4 * 4, BridJ.sizeOf(JAWT_Rectangle.class));
//assertEquals(4 + 5 * Pointer.SIZE, BridJ.sizeOf(JAWT.class));
//assertEquals(2 * 4 * 4 + 4 + Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurfaceInfo.class));
Frame f = new Frame();
f.pack();
f.setVisible(true);
Thread.sleep(500);
long p = JAWTUtils.getNativePeerHandle(f);
assertTrue(p != 0);
f.setVisible(false);
}
|
#vulnerable code
@Test
public void testWindowPeer() throws Exception {
if (Platform.isMacOSX() ||
System.getProperty("java.version)").matches("1\\.6\\..*")) {
// Oracle Java and jawt: it's complicated.
// See http://forum.lwjgl.org/index.php?topic=4326.0
// OpenJDK 6 + Linux seem problematic too.
return;
}
assertEquals(6 * Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurface.class));
assertEquals(4 * 4, BridJ.sizeOf(JAWT_Rectangle.class));
//assertEquals(4 + 5 * Pointer.SIZE, BridJ.sizeOf(JAWT.class));
//assertEquals(2 * 4 * 4 + 4 + Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurfaceInfo.class));
Frame f = new Frame();
f.pack();
f.setVisible(true);
Thread.sleep(500);
long p = JAWTUtils.getNativePeerHandle(f);
assertTrue(p != 0);
f.setVisible(false);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private HttpClient getHttpClient(PrintStream logger) throws Exception {
boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
String stashServer = stashServerBaseUrl;
DescriptorImpl descriptor = getDescriptor();
if ("".equals(stashServer) || stashServer == null) {
stashServer = descriptor.getStashRootUrl();
}
if (!ignoreUnverifiedSSL) {
ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
}
URL url = new URL(stashServer);
HttpClientBuilder builder = HttpClientBuilder.create();
if (url.getProtocol().equals("https")
&& ignoreUnverifiedSSL) {
// add unsafe trust manager to avoid thrown
// SSLPeerUnverifiedException
try {
TrustStrategy easyStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, easyStrategy)
.useTLS().build();
SSLConnectionSocketFactory sslConnSocketFactory
= new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslConnSocketFactory);
Registry<ConnectionSocketFactory> registry
= RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnSocketFactory)
.build();
HttpClientConnectionManager ccm
= new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
} catch (NoSuchAlgorithmException nsae) {
logger.println("Couldn't establish SSL context:");
nsae.printStackTrace(logger);
} catch (KeyManagementException kme) {
logger.println("Couldn't initialize SSL context:");
kme.printStackTrace(logger);
} catch (KeyStoreException kse) {
logger.println("Couldn't initialize SSL context:");
kse.printStackTrace(logger);
}
}
// Configure the proxy, if needed
// Using the Jenkins methods handles the noProxyHost settings
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
if (proxyConfig != null) {
Proxy proxy = proxyConfig.createProxy(url.getHost());
if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
SocketAddress addr = proxy.address();
if (addr != null && addr instanceof InetSocketAddress) {
InetSocketAddress proxyAddr = (InetSocketAddress) addr;
HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
builder = builder.setProxy(proxyHost);
String proxyUser = proxyConfig.getUserName();
if (proxyUser != null) {
String proxyPass = proxyConfig.getPassword();
CredentialsProvider cred = new BasicCredentialsProvider();
cred.setCredentials(new AuthScope(proxyHost),
new UsernamePasswordCredentials(proxyUser, proxyPass));
builder = builder
.setDefaultCredentialsProvider(cred)
.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
}
}
}
}
return builder.build();
}
|
#vulnerable code
private HttpClient getHttpClient(PrintStream logger) {
HttpClient client = null;
boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
String url = stashServerBaseUrl;
DescriptorImpl descriptor = getDescriptor();
if ("".equals(url) || url == null) {
url = descriptor.getStashRootUrl();
}
if (!ignoreUnverifiedSSL) {
ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
}
if (url.startsWith("https")
&& ignoreUnverifiedSSL) {
// add unsafe trust manager to avoid thrown
// SSLPeerUnverifiedException
try {
HttpClientBuilder builder = HttpClientBuilder.create();
TrustStrategy easyStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, easyStrategy)
.useTLS().build();
SSLConnectionSocketFactory sslConnSocketFactory
= new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslConnSocketFactory);
Registry<ConnectionSocketFactory> registry
= RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnSocketFactory)
.build();
HttpClientConnectionManager ccm
= new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
client = builder.build();
} catch (NoSuchAlgorithmException nsae) {
logger.println("Couldn't establish SSL context:");
nsae.printStackTrace(logger);
} catch (KeyManagementException kme) {
logger.println("Couldn't initialize SSL context:");
kme.printStackTrace(logger);
} catch (KeyStoreException kse) {
logger.println("Couldn't initialize SSL context:");
kse.printStackTrace(logger);
} finally {
if (client == null) {
logger.println("Trying with safe trust manager, instead!");
client = HttpClientBuilder.create().build();
}
}
} else {
client = HttpClientBuilder.create().build();
}
ProxyConfiguration proxy = Jenkins.getInstance().proxy;
if(proxy != null && !proxy.name.isEmpty() && !proxy.name.startsWith("http") && !isHostOnNoProxyList(proxy)){
SchemeRegistry schemeRegistry = client.getConnectionManager().getSchemeRegistry();
schemeRegistry.register(new Scheme("http", proxy.port, new PlainSocketFactory()));
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy.name, proxy.port));
}
return client;
}
#location 12
#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) {
AppUtil appUtil = new AppUtil();
AService service = (AService) appUtil.getComponentInstance("aService");
AggregateRootA aggregateRootA = service.getAggregateRootA("11");
DomainMessage res = service.commandA("11", aggregateRootA, 100);
long start = System.currentTimeMillis();
int result = 0;
DomainMessage res1 = (DomainMessage) res.getBlockEventResult();
if (res1 != null && res1.getBlockEventResult() != null)
result = (Integer) res1.getBlockEventResult();
long stop = System.currentTimeMillis();
Assert.assertEquals(result, 400);
System.out.print("\n ok \n" + result + " time:" + (stop - start));
}
|
#vulnerable code
public static void main(String[] args) {
AppUtil appUtil = new AppUtil();
AService service = (AService) appUtil.getComponentInstance("aService");
AggregateRootA aggregateRootA = service.getAggregateRootA("11");
DomainMessage res = service.commandA("11", aggregateRootA, 100);
long start = System.currentTimeMillis();
int result = 0;
DomainMessage res1 = (DomainMessage) res.getBlockEventResult();
if (res1.getBlockEventResult() != null)
result = (Integer) res1.getBlockEventResult();
long stop = System.currentTimeMillis();
Assert.assertEquals(result, 400);
System.out.print("\n ok \n" + result + (stop - start));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean doExists(String name, Locale locale, String path) throws Exception {
if (file != null && file.exists()) {
ZipFile zipFile = new ZipFile(file);
try {
return zipFile.getEntry(name) != null;
} finally {
zipFile.close();
}
}
return false;
}
|
#vulnerable code
public boolean doExists(String name, Locale locale, String path) throws Exception {
return file != null && file.exists() && new ZipFile(file).getEntry(name) != null;
}
#location 2
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public long getLastModified() {
try {
JarFile jarFile = new JarFile(file);
return jarFile.getEntry(getName()).getTime();
} catch (Throwable e) {
return super.getLastModified();
}
}
|
#vulnerable code
public long getLastModified() {
try {
JarFile zipFile = new JarFile(file);
return zipFile.getEntry(getName()).getTime();
} catch (Throwable e) {
return super.getLastModified();
}
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Template include(String name, Locale locale, String encoding) throws IOException, ParseException {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("include template name == null");
}
String macro = null;
int i = name.indexOf('#');
if (i > 0) {
macro = name.substring(i + 1);
name = name.substring(0, i);
}
Template template = Context.getContext().getTemplate();
if (template != null) {
if (encoding == null || encoding.length() == 0) {
encoding = template.getEncoding();
}
name = UrlUtils.relativeUrl(name, template.getName());
if (locale == null) {
locale = template.getLocale();
}
}
Template include = engine.getTemplate(name, locale, encoding);
if (macro != null && macro.length() > 0) {
include = include.getMacros().get(macro);
}
if (template != null && template == include) {
throw new IllegalStateException("The template " + template.getName() + " can not be recursive including the self template.");
}
return include;
}
|
#vulnerable code
public Template include(String name, Locale locale, String encoding) throws IOException, ParseException {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("include template name == null");
}
String macro = null;
int i = name.indexOf('#');
if (i > 0) {
macro = name.substring(i + 1);
name = name.substring(0, i);
}
Template template = Context.getContext().getTemplate();
if (template != null) {
if (encoding == null || encoding.length() == 0) {
encoding = template.getEncoding();
}
name = UrlUtils.relativeUrl(name, template.getName());
if (locale == null) {
locale = template.getLocale();
}
}
Template include = engine.getTemplate(name, locale, encoding);
if (macro != null && macro.length() > 0) {
include = include.getMacros().get(macro);
}
if (include == template) {
throw new IllegalStateException("The template " + template.getName() + " can not be recursive including the self template.");
}
return include;
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static Object decodeToObject(
String encodedObject, int options, final ClassLoader loader )
throws java.io.IOException, java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject, options );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
// If no custom class loader is provided, use Java's builtin OIS.
if( loader == null ){
ois = new java.io.ObjectInputStream( bais );
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais){
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class<?> c = Class.forName(streamClass.getName(), false, loader);
if( c == null ){
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch( java.lang.ClassNotFoundException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try {
if (bais != null) bais.close();
} finally {
if (ois != null) ois.close();
}
} // end finally
return obj;
}
|
#vulnerable code
public static Object decodeToObject(
String encodedObject, int options, final ClassLoader loader )
throws java.io.IOException, java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject, options );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
// If no custom class loader is provided, use Java's builtin OIS.
if( loader == null ){
ois = new java.io.ObjectInputStream( bais );
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais){
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class<?> c = Class.forName(streamClass.getName(), false, loader);
if( c == null ){
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch( java.lang.ClassNotFoundException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
}
#location 47
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testException() throws Exception {
boolean profile = "true".equals(System.getProperty("profile"));
Engine engine = Engine.getEngine("httl-exception.properties");
String dir = engine.getProperty("template.directory", "");
if (dir.length() > 0 && dir.startsWith("/")) {
dir = dir.substring(1);
}
if (dir.length() > 0 && ! dir.endsWith("/")) {
dir += "/";
}
URL url = this.getClass().getClassLoader().getResource(dir + "results/" + templateName + ".txt");
if (url == null) {
throw new FileNotFoundException("Not found file: " + dir + "results/" + templateName + ".txt");
}
File result = new File(url.getFile());
if (! result.exists()) {
throw new FileNotFoundException("Not found file: " + result.getAbsolutePath());
}
try {
engine.getTemplate("/templates/" + templateName);
fail(templateName);
} catch (ParseException e) {
if (! profile) {
String message = e.getMessage();
assertTrue(StringUtils.isNotEmpty(message));
List<String> expected = IOUtils.readLines(new FileReader(result));
assertTrue(expected != null && expected.size() > 0);
for (String part : expected) {
assertTrue(StringUtils.isNotEmpty(part));
part = StringUtils.unescapeString(part).trim();
assertTrue(templateName + ", exception message: \"" + message + "\" not contains: \"" + part + "\"", message.contains(part));
}
}
}
}
|
#vulnerable code
@Test
public void testException() throws Exception {
boolean profile = "true".equals(System.getProperty("profile"));
if (! profile)
System.out.println("========httl-exception.properties========");
Engine engine = Engine.getEngine("httl-exception.properties");
String dir = engine.getProperty("template.directory", "");
if (dir.length() > 0 && dir.startsWith("/")) {
dir = dir.substring(1);
}
if (dir.length() > 0 && ! dir.endsWith("/")) {
dir += "/";
}
File directory = new File(this.getClass().getClassLoader().getResource(dir + "templates/").getFile());
assertTrue(directory.isDirectory());
File[] files = directory.listFiles();
for (int i = 0, n = files.length; i < n; i ++) {
File file = files[i];
System.out.println(file.getName());
URL url = this.getClass().getClassLoader().getResource(dir + "results/" + file.getName() + ".txt");
if (url == null) {
throw new FileNotFoundException("Not found file: " + dir + "results/" + file.getName() + ".txt");
}
File result = new File(url.getFile());
if (! result.exists()) {
throw new FileNotFoundException("Not found file: " + result.getAbsolutePath());
}
try {
engine.getTemplate("/templates/" + file.getName());
fail(file.getName());
} catch (ParseException e) {
if (! profile) {
String message = e.getMessage();
assertTrue(StringUtils.isNotEmpty(message));
List<String> expected = IOUtils.readLines(new FileReader(result));
assertTrue(expected != null && expected.size() > 0);
for (String part : expected) {
assertTrue(StringUtils.isNotEmpty(part));
part = StringUtils.unescapeString(part).trim();
assertTrue(file.getName() + ", exception message: \"" + message + "\" not contains: \"" + part + "\"", message.contains(part));
}
}
}
}
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.