input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
|---|---|---|
#vulnerable code
public AsteriskChannel getDialedChannel()
{
return dialedChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public AsteriskChannel getDialedChannel()
{
synchronized(dialedChannels) {
for (AsteriskChannel channel:dialedChannels) {
if (channel != null) return channel;
}
}
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public AsteriskChannel getDialingChannel()
{
return dialingChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public AsteriskChannel getDialingChannel()
{
synchronized(dialingChannels) {
if (dialingChannels.isEmpty()) return null;
return dialingChannels.get(0);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 38
#vulnerability type THREAD_SAFETY_VIOLATION
|
#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");
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
}
}
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 54
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed 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;
}
}
}
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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ResponseEvents sendEventGeneratingAction(
EventGeneratingAction action, long timeout) throws IOException,
EventTimeoutException, IllegalArgumentException,
IllegalStateException
{
final ResponseEventsImpl responseEvents;
final ResponseEventHandler responseEventHandler;
final String internalActionId;
if (action == null)
{
throw new IllegalArgumentException(
"Unable to send action: action is null.");
}
else if (action.getActionCompleteEventClass() == null)
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass for " +
action.getClass().getName() + " is null.");
}
else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClass()))
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass (" +
action.getActionCompleteEventClass().getName() + ") for " +
action.getClass().getName() + " is not a ResponseEvent.");
}
// TODO
if (socket == null)
{
throw new IllegalStateException("Unable to send "
+ action.getAction() + " action: not connected.");
}
responseEvents = new ResponseEventsImpl();
responseEventHandler = new ResponseEventHandler(
responseEvents,
action.getActionCompleteEventClass());
internalActionId = createInternalActionId();
// register response handler...
synchronized (this.responseListeners)
{
this.responseListeners.put(internalActionId, responseEventHandler);
}
// ...and event handler.
synchronized (this.responseEventListeners)
{
this.responseEventListeners.put(internalActionId, responseEventHandler);
}
synchronized (responseEvents)
{
writer.sendAction(action, internalActionId);
// only wait if response has not yet arrived.
if ((responseEvents.getResponse() == null || !responseEvents.isComplete()))
{
try
{
responseEvents.wait(timeout);
}
catch (InterruptedException e)
{
logger.warn("Interrupted while waiting for response events.");
}
}
}
// still no response or not all events received and timed out?
if ((responseEvents.getResponse() == null || !responseEvents.isComplete()))
{
// clean up
synchronized (this.responseEventListeners)
{
this.responseEventListeners.remove(internalActionId);
}
throw new EventTimeoutException(
"Timeout waiting for response or response events to "
+ action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"),
responseEvents);
}
// remove the event handler
// Note: The response handler has already been removed
// when the response was received
synchronized (this.responseEventListeners)
{
this.responseEventListeners.remove(internalActionId);
}
return responseEvents;
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public ResponseEvents sendEventGeneratingAction(
EventGeneratingAction action, long timeout) throws IOException,
EventTimeoutException, IllegalArgumentException,
IllegalStateException
{
final ResponseEventsImpl responseEvents;
final ResponseEventHandler responseEventHandler;
final String internalActionId;
if (action == null)
{
throw new IllegalArgumentException(
"Unable to send action: action is null.");
}
else if (action.getActionCompleteEventClass() == null)
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass for " +
action.getClass().getName() + " is null.");
}
else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClass()))
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass (" +
action.getActionCompleteEventClass().getName() + ") for " +
action.getClass().getName() + " is not a ResponseEvent.");
}
if (state != CONNECTED)
{
throw new IllegalStateException("Actions may only be sent when in state " +
"CONNECTED, but connection is in state " + state);
}
responseEvents = new ResponseEventsImpl();
responseEventHandler = new ResponseEventHandler(
responseEvents,
action.getActionCompleteEventClass());
internalActionId = createInternalActionId();
// register response handler...
synchronized (this.responseListeners)
{
this.responseListeners.put(internalActionId, responseEventHandler);
}
// ...and event handler.
synchronized (this.responseEventListeners)
{
this.responseEventListeners.put(internalActionId, responseEventHandler);
}
synchronized (responseEvents)
{
writer.sendAction(action, internalActionId);
// only wait if response has not yet arrived.
if ((responseEvents.getResponse() == null || !responseEvents.isComplete()))
{
try
{
responseEvents.wait(timeout);
}
catch (InterruptedException e)
{
logger.warn("Interrupted while waiting for response events.");
}
}
}
// still no response or not all events received and timed out?
if ((responseEvents.getResponse() == null || !responseEvents.isComplete()))
{
// clean up
synchronized (this.responseEventListeners)
{
this.responseEventListeners.remove(internalActionId);
}
throw new EventTimeoutException(
"Timeout waiting for response or response events to "
+ action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"),
responseEvents);
}
// remove the event handler
// Note: The response handler has already been removed
// when the response was received
synchronized (this.responseEventListeners)
{
this.responseEventListeners.remove(internalActionId);
}
return responseEvents;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) throws ManagerCommunicationException
{
return originateToApplication(channel, application, data, timeout, null, null);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) throws ManagerCommunicationException, NoSuchChannelException
{
return originateToApplication(channel, application, data, timeout, null, null);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 124
#vulnerability type THREAD_SAFETY_VIOLATION
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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");
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
QueueManager(AsteriskServerImpl server, ChannelManager channelManager)
{
this.server = server;
this.channelManager = channelManager;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ResponseEvents sendEventGeneratingAction(
EventGeneratingAction action, long timeout) throws IOException,
EventTimeoutException, IllegalArgumentException,
IllegalStateException
{
ResponseEventsImpl responseEvents;
ResponseEventHandler responseEventHandler;
String internalActionId;
long start;
long timeSpent;
if (action == null)
{
throw new IllegalArgumentException(
"Unable to send action: action is null.");
}
else if (action.getActionCompleteEventClass() == null)
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is null.");
}
else if (!ResponseEvent.class.isAssignableFrom(action
.getActionCompleteEventClass()))
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is not a ResponseEvent.");
}
if (socket == null)
{
throw new IllegalStateException("Unable to send "
+ action.getAction() + " action: not connected.");
}
responseEvents = new ResponseEventsImpl();
responseEventHandler = new ResponseEventHandler(responseEvents, action
.getActionCompleteEventClass(), Thread.currentThread());
internalActionId = createInternalActionId();
// register response handler...
synchronized (this.responseHandlers)
{
this.responseHandlers.put(internalActionId, responseEventHandler);
}
// ...and event handler.
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.put(internalActionId,
responseEventHandler);
}
writer.sendAction(action, internalActionId);
// let's wait to see what we get
start = System.currentTimeMillis();
timeSpent = 0;
while (responseEvents.getResponse() == null
|| !responseEvents.isComplete())
{
try
{
Thread.sleep(timeout - timeSpent);
}
catch (InterruptedException ex)
{
}
// still no response or not all events received and timed out?
timeSpent = System.currentTimeMillis() - start;
if ((responseEvents.getResponse() == null || !responseEvents
.isComplete())
&& timeSpent > timeout)
{
// clean up
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
throw new EventTimeoutException(
"Timeout waiting for response or response events to "
+ action.getAction(), responseEvents);
}
}
// remove the event handler (note: the response handler is removed
// automatically when the response is received)
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
return responseEvents;
}
#location 54
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public ResponseEvents sendEventGeneratingAction(
EventGeneratingAction action, long timeout) throws IOException,
EventTimeoutException, IllegalArgumentException,
IllegalStateException
{
ResponseEventsImpl responseEvents;
ResponseEventHandler responseEventHandler;
String internalActionId;
if (action == null)
{
throw new IllegalArgumentException(
"Unable to send action: action is null.");
}
else if (action.getActionCompleteEventClass() == null)
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is null.");
}
else if (!ResponseEvent.class.isAssignableFrom(action
.getActionCompleteEventClass()))
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is not a ResponseEvent.");
}
if (socket == null)
{
throw new IllegalStateException("Unable to send "
+ action.getAction() + " action: not connected.");
}
responseEvents = new ResponseEventsImpl();
responseEventHandler = new ResponseEventHandler(responseEvents, action
.getActionCompleteEventClass());
internalActionId = createInternalActionId();
// register response handler...
synchronized (this.responseHandlers)
{
this.responseHandlers.put(internalActionId, responseEventHandler);
}
// ...and event handler.
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.put(internalActionId,
responseEventHandler);
}
synchronized (responseEvents)
{
writer.sendAction(action, internalActionId);
try
{
responseEvents.wait(timeout);
}
catch (InterruptedException ex)
{
//TODO fix logging
System.err.println("Interrupted");
}
}
// still no response or not all events received and timed out?
if ((responseEvents.getResponse() == null || !responseEvents
.isComplete()))
{
// clean up
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
throw new EventTimeoutException(
"Timeout waiting for response or response events to "
+ action.getAction(), responseEvents);
}
// remove the event handler (note: the response handler is removed
// automatically when the response is received)
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
return responseEvents;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void disconnected()
{
if (traceScheduledExecutorService != null)
{
traceScheduledExecutorService.shutdown();
}
synchronized (channels)
{
channels.clear();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private boolean isZipFile(final File file) throws IOException {
final DataInputStream in = new DataInputStream(new FileInputStream(file));
final int n = in.readInt();
in.close();
return n == 0x504b0304;
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
private boolean isZipFile(final File file) {
DataInputStream in = null;
try {
in = new DataInputStream(new FileInputStream(file));
final int n = in.readInt();
return n == 0x504b0304;
} catch (IOException ex) {
// silently ignore read exceptions
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
// ignore
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testTaskCreate() {
setupContextForTaskExecutionListener();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener =
context.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null);
verifyListenerResults(true, false, false, taskExecution,taskExecutionListener);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testTaskCreate() {
setupContextForTaskExecutionListener();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener =
context.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null, null);
verifyListenerResults(true, false, false, taskExecution,taskExecutionListener);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
Search(String question) {
this.question = question;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private Long searchAndOpen(String question) throws IOException {
String path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=20";
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path);
return new Search(question).search(question);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
#fixed code
private Long searchAndOpen(String question) throws IOException {
String path = null;
try {
path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=20";
//获取操作系统的名字
String osName = System.getProperty("os.name", "");
if (osName.startsWith("Mac OS")) {
//苹果的打开方式
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class});
openURL.invoke(null, new Object[]{path});
} else if (osName.startsWith("Windows")) {
//windows的打开方式。
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path);
return new Search(question).search(question);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
Search(String question) {
this.question = question;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请选择您要使用的文字识别方式\n1.TessOCR\n2.百度OCR");
System.out.println("默认使用TessOCR,选择后回车");
OCR ocr = OCR_FACTORY.getOcr(Integer.valueOf(bf.readLine()));
System.out.println("请选择您要进入的游戏\n1.百万英雄\n2.冲顶大会");
System.out.println("默认为百万英雄,选择后回车");
Pattern pattern = PATTERN_FACTORY.getPattern(Integer.valueOf(bf.readLine()), ocr, UTILS);
while (true) {
String str = bf.readLine();
if ("exit".equals(str)) {
System.out.println("ヾ( ̄▽ ̄)Bye~Bye~");
break;
} else {
if (str.length() == 0) {
System.out.print("开始答题");
pattern.run();
}
}
}
}
#location 18
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请选择您要使用的文字识别方式\n1.TessOCR\n2.百度OCR");
System.out.println("默认使用TessOCR,选择后回车,不能为空");
String selection=bf.readLine();
OCR ocr = OCR_FACTORY.getOcr(Integer.valueOf((selection.length()==0)?"1":selection));
System.out.println("请选择您要进入的游戏\n1.百万英雄\n2.冲顶大会");
System.out.println("默认为百万英雄,选择后回车");
selection=bf.readLine();
Pattern pattern = PATTERN_FACTORY.getPattern(Integer.valueOf((selection.length()==0)?"1":selection), ocr, UTILS);
while (true) {
String str = bf.readLine();
if ("exit".equals(str)) {
System.out.println("ヾ( ̄▽ ̄)Bye~Bye~");
break;
} else {
if (str.length() == 0) {
System.out.print("开始答题");
pattern.run();
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 34
#vulnerability type NULL_DEREFERENCE
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void run() {
try {
LOGGER.info(I18n.UPDATE_LOADING);
URLConnection con = new URL("http://jsql-injection.googlecode.com/git/.version").openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line, pageSource = "";
while ((line = reader.readLine()) != null) {
pageSource += line + "\n";
}
reader.close();
Float gitVersion = Float.parseFloat(pageSource);
MediatorGUI.model();
if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) {
LOGGER.debug(I18n.UPDATE_UPTODATE);
} else {
LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE);
}
} catch (NumberFormatException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
} catch (IOException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void run() {
try {
LOGGER.info(I18n.UPDATE_LOADING);
URLConnection con = new URL("https://raw.githubusercontent.com/ron190/jsql-injection/master/.version").openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line, pageSource = "";
while ((line = reader.readLine()) != null) {
pageSource += line + "\n";
}
reader.close();
Float gitVersion = Float.parseFloat(pageSource);
MediatorGUI.model();
if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) {
LOGGER.debug(I18n.UPDATE_UPTODATE);
} else {
LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE);
}
} catch (NumberFormatException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
} catch (IOException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 58
#vulnerability type NULL_DEREFERENCE
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 73
#vulnerability type NULL_DEREFERENCE
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 54
#vulnerability type NULL_DEREFERENCE
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 39
#vulnerability type NULL_DEREFERENCE
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 50
#vulnerability type NULL_DEREFERENCE
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void run() {
try {
LOGGER.info(I18n.UPDATE_LOADING);
URLConnection con = new URL("http://jsql-injection.googlecode.com/git/.version").openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line, pageSource = "";
while ((line = reader.readLine()) != null) {
pageSource += line + "\n";
}
reader.close();
Float gitVersion = Float.parseFloat(pageSource);
MediatorGUI.model();
if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) {
LOGGER.debug(I18n.UPDATE_UPTODATE);
} else {
LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE);
}
} catch (NumberFormatException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
} catch (IOException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
}
}
#location 23
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void run() {
try {
LOGGER.info(I18n.UPDATE_LOADING);
URLConnection con = new URL("https://raw.githubusercontent.com/ron190/jsql-injection/master/.version").openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line, pageSource = "";
while ((line = reader.readLine()) != null) {
pageSource += line + "\n";
}
reader.close();
Float gitVersion = Float.parseFloat(pageSource);
MediatorGUI.model();
if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) {
LOGGER.debug(I18n.UPDATE_UPTODATE);
} else {
LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE);
}
} catch (NumberFormatException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
} catch (IOException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void start(Class<?> clazz,String path) throws Exception {
long start = System.currentTimeMillis();
//init application
AppConfig.getInstance().setRootPackageName(clazz.getPackage().getName());
AppConfig.getInstance().setRootPath(path);
InputStream resourceAsStream = CicadaServer.class.getClassLoader().getResourceAsStream("application.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
int port = Integer.parseInt(prop.get(CicadaConstant.CICADA_PORT).toString());
AppConfig.getInstance().setPort(port);
List<Class<?>> configuration = ClassScanner.getConfiguration(AppConfig.getInstance().getRootPackageName());
for (Class<?> aClass : configuration) {
AbstractCicadaConfiguration conf = (AbstractCicadaConfiguration) aClass.newInstance() ;
InputStream stream = CicadaServer.class.getClassLoader().getResourceAsStream(conf.getPropertiesName());
Properties properties = new Properties();
properties.load(stream);
conf.setProperties(properties) ;
ConfigurationHolder.addConfiguration(aClass.getName(),conf) ;
}
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(boss, work)
.channel(NioServerSocketChannel.class)
.childHandler(new CicadaInitializer());
ChannelFuture future = bootstrap.bind(port).sync();
if (future.isSuccess()) {
long end = System.currentTimeMillis();
LOGGER.info("Cicada started on port: {}.cost {}ms", port ,end-start);
}
Channel channel = future.channel();
channel.closeFuture().sync();
} finally {
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void start(Class<?> clazz,String path) throws Exception {
InitSetting.setting(clazz,path) ;
NettyBootStrap.startServer();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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_NAME.matcher(channelName).matches()) {
throw new IllegalArgumentException(String.format(ERROR_ILLEGAL_CHANNEL_NAME, channelName));
}
String scopeId = getReference(SocketScope.class).register(channelName, Scope.of(getString(context, scope)));
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 17
#vulnerability type NULL_DEREFERENCE
|
#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));
}
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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings("unchecked")
@Produces
@Param
public <V> ParamValue<V> produce(InjectionPoint injectionPoint) {
Param requestParameter = getQualifier(injectionPoint, Param.class);
FacesContext context = getContext();
UIComponent component = getViewRoot();
// Get raw submitted value from the request
String submittedValue = getRequestParameter(getName(requestParameter, injectionPoint));
Object convertedValue = null;
boolean valid = true;
try {
// Convert the submitted value
Converter converter = getConverter(requestParameter, getTargetType(injectionPoint));
if (converter != null) {
convertedValue = converter.getAsObject(context, component, submittedValue);
} else {
convertedValue = submittedValue;
}
// Validate the converted value
for (Validator validator : getValidators(requestParameter)) {
try {
validator.validate(context, component, convertedValue);
} catch (ValidatorException ve) {
valid = false;
String clientId = component.getClientId(context);
for (FacesMessage facesMessage : getFacesMessages(ve)) {
context.addMessage(clientId, facesMessage);
}
}
}
} catch (ConverterException ce) {
valid = false;
addConverterMessage(context, component, submittedValue, ce, requestParameter.converterMessage());
}
if (!valid) {
context.validationFailed();
convertedValue = null;
}
return (ParamValue<V>) new ParamValue<Object>(convertedValue);
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings("unchecked")
@Produces
@Param
public <V> ParamValue<V> produce(InjectionPoint injectionPoint) {
// @Param is the annotation on the injection point that holds all data for this request parameter
Param requestParameter = getQualifier(injectionPoint, Param.class);
FacesContext context = getContext();
UIComponent component = getViewRoot();
// TODO: Save/restore existing potentially existing label?
component.getAttributes().put("label", getLabel(requestParameter, injectionPoint));
// Get raw submitted value from the request
String submittedValue = getRequestParameter(getName(requestParameter, injectionPoint));
Object convertedValue = null;
boolean valid = true;
try {
// Convert the submitted value
Converter converter = getConverter(requestParameter, getTargetType(injectionPoint));
if (converter != null) {
convertedValue = converter.getAsObject(context, component, submittedValue);
} else {
convertedValue = submittedValue;
}
// Validate the converted value
for (Validator validator : getValidators(requestParameter)) {
try {
validator.validate(context, component, convertedValue);
} catch (ValidatorException ve) {
valid = false;
addValidatorMessages(context, component, submittedValue, ve, requestParameter.validatorMessage());
}
}
} catch (ConverterException ce) {
valid = false;
addConverterMessage(context, component, submittedValue, ce, requestParameter.converterMessage());
}
if (!valid) {
context.validationFailed();
convertedValue = null;
}
return (ParamValue<V>) new ParamValue<Object>(convertedValue);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass) {
return getInstance(beanManager, resolve(beanManager, beanClass), true);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass) {
Bean<T> bean = resolve(beanManager, beanClass);
return (bean != null) ? getInstance(beanManager, bean, true) : null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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()));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@OnClose
public void close(Session session) {
BeanManager.INSTANCE.getReference(PushContextImpl.class).remove(session); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld.
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@OnClose
public void close(Session session) {
BeanManager.INSTANCE.getReference(SocketPushContext.class).remove(session); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld.
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static <T> T getReference(BeanManager beanManager, Class<T> beanClass) {
return getReference(beanManager, resolve(beanManager, beanClass));
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static <T> T getReference(BeanManager beanManager, Class<T> beanClass) {
Bean<T> bean = resolve(beanManager, beanClass);
return (bean != null) ? getReference(beanManager, bean) : null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@OnOpen
public void open(Session session, @PathParam("channel") String channel) {
BeanManager.INSTANCE.getReference(PushContextImpl.class).add(session, channel); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld.
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@OnOpen
public void open(Session session, @PathParam("channel") String channel) {
BeanManager.INSTANCE.getReference(SocketPushContext.class).add(session, channel); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld.
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public <S extends Serializable> Map<S, Set<Future<Void>>> send(Object message, Collection<S> users) {
SocketSessionManager manager = SocketSessionManager.getInstance();
Map<S, Set<Future<Void>>> resultsByUser = new HashMap<>(users.size());
for (S user : users) {
Set<String> userChannelIds = getUserChannelIds(user, channel);
Set<Future<Void>> results = new HashSet<>(userChannelIds.size());
for (String channelId : userChannelIds) {
results.addAll(manager.send(channelId, message));
}
resultsByUser.put(user, results);
}
return resultsByUser;
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public <S extends Serializable> Map<S, Set<Future<Void>>> send(Object message, Collection<S> users) {
Map<S, Set<Future<Void>>> resultsByUser = new HashMap<>(users.size());
for (S user : users) {
Set<String> userChannelIds = userManager.getUserChannelIds(user, channel);
Set<Future<Void>> results = new HashSet<>(userChannelIds.size());
for (String channelId : userChannelIds) {
results.addAll(sessionManager.send(channelId, message));
}
resultsByUser.put(user, results);
}
return resultsByUser;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
if (event instanceof PreDestroyViewMapEvent) {
getReference(ViewScopeManager.class).preDestroyView();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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), "") : "";
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 12
#vulnerability type NULL_DEREFERENCE
|
#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[] uriAndQueryString = actionURL.split("\\?", 2);
String uri = stripWelcomeFilePrefix(servletContext, removeExtensionIfNecessary(servletContext, uriAndQueryString[0], viewId));
String queryString = uriAndQueryString.length > 1 ? ("?" + uriAndQueryString[1]) : "";
String pathInfo = context.getViewRoot().getViewId().equals(viewId) ? coalesce(getRequestPathInfo(context), "") : "";
return (pathInfo.isEmpty() ? uri : (stripTrailingSlash(uri) + pathInfo)) + queryString;
}
// Not a resource we mapped or not a forwarded one, take the version from the parent view handler.
return actionURL;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public UIViewRoot restoreView(FacesContext context, String viewId) {
if (isUnloadRequest(context)) {
UIViewRoot createdView = createView(context, viewId);
createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId));
getReference(ViewScopeManager.class).preDestroyView();
responseComplete();
return createdView;
}
UIViewRoot restoredView = super.restoreView(context, viewId);
if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) {
return restoredView;
}
try {
UIViewRoot createdView = buildView(viewId);
return isRestorableView(createdView) ? createdView : null;
}
catch (IOException e) {
throw new FacesException(e);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public UIViewRoot restoreView(FacesContext context, String viewId) {
if (isUnloadRequest(context)) {
UIViewRoot createdView = createView(context, viewId);
createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId));
context.setProcessingEvents(true);
context.getApplication().publishEvent(context, PreDestroyViewMapEvent.class, UIViewRoot.class, createdView);
responseComplete();
return createdView;
}
UIViewRoot restoredView = super.restoreView(context, viewId);
if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) {
return restoredView;
}
try {
UIViewRoot createdView = buildView(viewId);
return isRestorableView(createdView) ? createdView : null;
}
catch (IOException e) {
throw new FacesException(e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void contextInitialized(ServletContextEvent event) {
checkCDIAvailable();
BeanManager.INSTANCE.getReference(EagerBeansRepository.class).instantiateApplicationScoped();
FacesViews.addMappings(event.getServletContext());
CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext());
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void contextInitialized(ServletContextEvent event) {
checkCDIAvailable();
EagerBeansRepository.getInstance().instantiateApplicationScoped();
FacesViews.addMappings(event.getServletContext());
CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void handlePreValidate(UIInput component) {
final BeanValidator beanValidator = getBeanValidator(component);
final String newValidationGroups = disabled ? NoValidationGroup.class.getName() : validationGroups;
final String originalValidationGroups = beanValidator.getValidationGroups();
if (originalValidationGroups != null) {
component.getAttributes().put(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS, originalValidationGroups);
}
beanValidator.setValidationGroups(newValidationGroups);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(String.format(LOG_VALIDATION_GROUPS_OVERRIDDEN,
component.getClientId(), originalValidationGroups, newValidationGroups));
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void handlePreValidate(UIInput component) {
BeanValidator beanValidator = getBeanValidator(component);
if (beanValidator == null) {
return;
}
String newValidationGroups = disabled ? NoValidationGroup.class.getName() : validationGroups;
String originalValidationGroups = beanValidator.getValidationGroups();
if (originalValidationGroups != null) {
component.getAttributes().put(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS, originalValidationGroups);
}
beanValidator.setValidationGroups(newValidationGroups);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(String.format(LOG_VALIDATION_GROUPS_OVERRIDDEN,
component.getClientId(), originalValidationGroups, newValidationGroups));
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public UIViewRoot restoreView(FacesContext context, String viewId) {
if (isUnloadRequest(context)) {
UIViewRoot createdView = createView(context, viewId);
createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId));
BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView();
responseComplete();
return createdView;
}
UIViewRoot restoredView = super.restoreView(context, viewId);
if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) {
return restoredView;
}
try {
UIViewRoot createdView = buildView(viewId);
return isRestorableView(createdView) ? createdView : null;
}
catch (IOException e) {
throw new FacesException(e);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public UIViewRoot restoreView(FacesContext context, String viewId) {
if (isUnloadRequest(context)) {
UIViewRoot createdView = createView(context, viewId);
createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId));
getReference(ViewScopeManager.class).preDestroyView();
responseComplete();
return createdView;
}
UIViewRoot restoredView = super.restoreView(context, viewId);
if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) {
return restoredView;
}
try {
UIViewRoot createdView = buildView(viewId);
return isRestorableView(createdView) ? createdView : null;
}
catch (IOException e) {
throw new FacesException(e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
if (SocketFacesListener.register(context, this)) {
String channel = getChannel();
if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) {
throw new IllegalArgumentException(format(ERROR_INVALID_CHANNEL, channel));
}
Integer port = getPort();
String host = (port != null ? ":" + port : "") + getRequestContextPath(context);
String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser());
String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose();
String behaviors = getBehaviorScripts();
boolean connected = isConnected();
String script = format(SCRIPT_INIT, host, channelId, functions, behaviors, connected);
context.getResponseWriter().write(script);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#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);
}
if (SocketFacesListener.register(context, this)) {
String channel = getChannel();
if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) {
throw new IllegalArgumentException(format(ERROR_INVALID_CHANNEL, channel));
}
Integer port = getPort();
String host = (port != null ? ":" + port : "") + getRequestContextPath(context);
String channelId = SocketChannelManager.getInstance().register(channel, getScope(), getUser());
String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose();
String behaviors = getBehaviorScripts();
boolean connected = isConnected();
String script = format(SCRIPT_INIT, host, channelId, functions, behaviors, connected);
context.getResponseWriter().write(script);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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.isLiteral() ? channel.getValue(context) : null;
if (channelName == null || !PATTERN_CHANNEL.matcher(channelName).matches()) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channelName));
}
Object userObject = getObject(context, user);
if (userObject != null && !(userObject instanceof Serializable)) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_USER, userObject));
}
SocketChannelManager channelManager = getReference(SocketChannelManager.class);
String scopeName = (scope == null) ? null : scope.isLiteral() ? getString(context, scope) : "";
String channelId;
try {
channelId = channelManager.register(channelName, scopeName, (Serializable) userObject);
}
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 onopenFunction = getString(context, onopen);
String onmessageFunction = onmessage.getValue(context);
String oncloseFunction = getString(context, onclose);
String functions = onopenFunction + "," + onmessageFunction + "," + oncloseFunction;
ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class);
SystemEventListener listener = new SocketFacesListener(portNumber, channelName, channelId, functions, connectedExpression);
subscribeToViewEvent(PostAddToViewEvent.class, listener);
subscribeToViewEvent(PreRenderViewEvent.class, listener);
}
#location 28
#vulnerability type NULL_DEREFERENCE
|
#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);
}
Integer portNumber = getObject(context, port, Integer.class);
String channelName = getChannelName(context, channel);
String channelId = getChannelId(context, channelName, scope, user);
String functions = getString(context, onopen) + "," + onmessage.getValue(context) + "," + getString(context, onclose);
ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class);
SystemEventListener listener = new SocketFacesListener(portNumber, channelName, channelId, functions, connectedExpression);
subscribeToViewEvent(PostAddToViewEvent.class, listener);
subscribeToViewEvent(PreRenderViewEvent.class, listener);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void contextInitialized(ServletContextEvent event) {
checkCDIAvailable();
try {
EagerBeansRepository.getInstance().instantiateApplicationScoped();
FacesViews.addMappings(event.getServletContext());
CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext());
}
catch (Throwable e) {
logger.log(Level.SEVERE, "OmniFaces failed to initialize! Report an issue to OmniFaces.", e);
throw e;
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void contextInitialized(ServletContextEvent event) {
checkCDIAvailable();
try {
ServletContext servletContext = event.getServletContext();
EagerBeansRepository.instantiateApplicationScopedAndRegisterListener(servletContext);
FacesViews.addMappings(servletContext);
CacheInitializer.loadProviderAndRegisterFilter(servletContext);
}
catch (Throwable e) {
logger.log(Level.SEVERE, "OmniFaces failed to initialize! Report an issue to OmniFaces.", e);
throw e;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass, boolean create) {
return getInstance(beanManager, resolve(beanManager, beanClass), create);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass, boolean create) {
Bean<T> bean = resolve(beanManager, beanClass);
return (bean != null) ? getInstance(beanManager, bean, create) : null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#fixed code
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
if (event instanceof PreDestroyViewMapEvent) {
processPreDestroyView();
}
else if (event instanceof PostRestoreStateEvent && "unload".equals(getRequestParameter("omnifaces.event"))) {
processPreDestroyView();
responseComplete();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Set<Future<Void>> send(Object message) {
return SocketSessionManager.getInstance().send(getChannelId(channel, sessionScopeIds, viewScopeIds), message);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public Set<Future<Void>> send(Object message) {
return sessionManager.send(getChannelId(channel, sessionScopeIds, viewScopeIds), message);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private TreeModel<T> getPreviousSibling(TreeModel<T> parent, int index) {
if (isRoot()) {
return null;
}
else if (index >= 0) {
return parent.getChildren().get(index);
}
else {
TreeModel<T> previousParent = parent.getPreviousSibling();
return getPreviousSibling(previousParent, (previousParent != null ? previousParent.getChildCount() : 0) - 1);
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private TreeModel<T> getPreviousSibling(TreeModel<T> parent, int index) {
if (parent == null) {
return null;
}
else if (index >= 0) {
return parent.getChildren().get(index);
}
else {
TreeModel<T> previousParent = parent.getPreviousSibling();
return getPreviousSibling(previousParent, (previousParent != null ? previousParent.getChildCount() : 0) - 1);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void shouldBeAbleToConvertNumbers(){
assertThat(((Character) converter.convert("r", char.class, errors, bundle)).charValue(), is(equalTo('r')));
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void shouldBeAbleToConvertNumbers(){
assertThat(((Character) converter.convert("r", char.class, bundle)).charValue(), is(equalTo('r')));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void readerWriterTest() throws URISyntaxException, IOException, TransformationException, SAXException {
File file = new File(HTMLDocContentStructureConvertersTest.class.getResource(modelFilePath).toURI());
String expectedHTML = FileUtils.readFileToString(file, "UTF-8");
InputStream is = HTMLDocContentStructureConvertersTest.class.getResourceAsStream(modelFilePath);
InputStreamReader isr = new InputStreamReader(is);
ContentStructure structure = reader.read(isr);
String structureHTML = writer.write(structure);
XMLUnit.setIgnoreWhitespace(true);
Diff diff = new Diff(expectedHTML, structureHTML);
assertTrue(diff.similar());
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void readerWriterTest() throws URISyntaxException, IOException, TransformationException, SAXException {
File file = new File(HTMLDocContentStructureConvertersTest.class.getResource(modelFilePath).toURI());
String expectedHTML = FileUtils.readFileToString(file, "UTF-8");
InputStream is = HTMLDocContentStructureConvertersTest.class.getResourceAsStream(modelFilePath);
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
ContentStructure structure = reader.read(isr);
String structureHTML = writer.write(structure);
XMLUnit.setIgnoreWhitespace(true);
Diff diff = new Diff(expectedHTML, structureHTML);
assertTrue(diff.similar());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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();
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable 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");
}
#location 38
#vulnerability type NULL_DEREFERENCE
|
#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) {
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");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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.");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static BxDocument getDocument(File file) throws IOException, TransformationException {
TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
BxDocument newDoc = new BxDocument();
InputStream is = new FileInputStream(file);
try {
List<BxPage> pages = tvReader.read(new InputStreamReader(is));
for (BxPage page : pages) {
page.setParent(newDoc);
}
newDoc.setFilename(file.getName());
newDoc.setPages(pages);
return newDoc;
} finally {
is.close();
}
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static BxDocument getDocument(File file) throws IOException, TransformationException {
TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
BxDocument newDoc = new BxDocument();
InputStream is = new FileInputStream(file);
try {
List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8"));
for (BxPage page : pages) {
page.setParent(newDoc);
}
newDoc.setFilename(file.getName());
newDoc.setPages(pages);
return newDoc;
} finally {
is.close();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 DocstrumSegmenter();
BxDocument outDoc = pageSegmenter.segmentDocument(inDoc);
// Check whether zones are correctly detected
assertEquals(1, outDoc.childrenCount());
// Check whether lines are correctly detected
assertEquals(3, outDoc.getFirstChild().childrenCount());
assertEquals(3, outDoc.getFirstChild().getChild(0).childrenCount());
assertEquals(16, outDoc.getFirstChild().getChild(1).childrenCount());
assertEquals(16, outDoc.getFirstChild().getChild(2).childrenCount());
assertEquals(24, outDoc.getFirstChild().getChild(1).getFirstChild().childrenCount());
assertEquals("A", outDoc.getFirstChild().getChild(1).getFirstChild().getFirstChild().toText());
for (BxZone zone : outDoc.getFirstChild()) {
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
|
#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 DocstrumSegmenter();
BxDocument outDoc = pageSegmenter.segmentDocument(inDoc);
// Check whether zones are correctly detected
assertEquals(1, outDoc.childrenCount());
// Check whether lines are correctly detected
assertEquals(3, outDoc.getFirstChild().childrenCount());
assertEquals(3, outDoc.getFirstChild().getChild(0).childrenCount());
assertEquals(16, outDoc.getFirstChild().getChild(1).childrenCount());
assertEquals(16, outDoc.getFirstChild().getChild(2).childrenCount());
assertEquals(24, outDoc.getFirstChild().getChild(1).getFirstChild().childrenCount());
assertEquals("A", outDoc.getFirstChild().getChild(1).getFirstChild().getFirstChild().toText());
for (BxZone zone : outDoc.getFirstChild()) {
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());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
|
#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);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public String getErrorMessage() {
String res = "";
if (error != null) {
res = error.getMessage();
if(res==null || res.isEmpty()) {
res = "Exception is: "+res.getClass().toString();
}
} else {
res = "Unknown error";
log.warn("Unexpected question for error message while no exception. Wazzup?");
}
return res;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public String getErrorMessage() {
String res;
if (error != null) {
res = error.getMessage();
if(res==null || res.isEmpty()) {
res = "Exception is: "+error.getClass().toString();
}
} else {
res = "Unknown error";
log.warn("Unexpected question for error message while no exception. Wazzup?");
}
return res;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testImporter() throws IOException, ParserConfigurationException, SAXException,
TransformationException {
BxPage page = new TrueVizToBxDocumentReader().read(new InputStreamReader(TrueVizToBxDocumentReaderTest.class.getResourceAsStream("/pl/edu/icm/cermine/structure/imports/MargImporterTest1.xml"))).get(0);
boolean contains = false;
boolean rightText = false;
boolean rightSize = false;
for (BxZone zone : page) {
if (zone.getLabel() != null) {
if (zone.getLabel().equals(BxZoneLabel.MET_AUTHOR)) {
contains = true;
if (zone.toText().trim().equalsIgnoreCase("Howard M Schachter Ba Pham Jim King tt\nStephanie Langford David Moher".trim())) {
rightText = true;
}
if (zone.getBounds().getX() == 72 && zone.getBounds().getY() == 778 && zone.getBounds().getWidth() == 989 && zone.getBounds().getHeight() == 122) {
rightSize = true;
}
}
}
}
assertTrue(contains);
assertTrue(rightText);
assertTrue(rightSize);
BxWord word = page.getChild(0).getChild(0).getChild(0);
assertEquals("font-1", word.getChild(0).getFontName());
assertEquals("font-2", word.getChild(1).getFontName());
}
#location 4
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testImporter() throws IOException, ParserConfigurationException, SAXException,
TransformationException {
BxPage page = new TrueVizToBxDocumentReader().read(new InputStreamReader(TrueVizToBxDocumentReaderTest.class.getResourceAsStream("/pl/edu/icm/cermine/structure/imports/MargImporterTest1.xml"), "UTF-8")).get(0);
boolean contains = false;
boolean rightText = false;
boolean rightSize = false;
for (BxZone zone : page) {
if (zone.getLabel() != null) {
if (zone.getLabel().equals(BxZoneLabel.MET_AUTHOR)) {
contains = true;
if (zone.toText().trim().equalsIgnoreCase("Howard M Schachter Ba Pham Jim King tt\nStephanie Langford David Moher".trim())) {
rightText = true;
}
if (zone.getBounds().getX() == 72 && zone.getBounds().getY() == 778 && zone.getBounds().getWidth() == 989 && zone.getBounds().getHeight() == 122) {
rightSize = true;
}
}
}
}
assertTrue(contains);
assertTrue(rightText);
assertTrue(rightSize);
BxWord word = page.getChild(0).getChild(0).getChild(0);
assertEquals("font-1", word.getChild(0).getFontName());
assertEquals("font-2", word.getChild(1).getFontName());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void metadataExtractionTest() throws AnalysisException, JDOMException, IOException, SAXException, TransformationException, URISyntaxException {
InputStream expStream = AbstractBibReferenceExtractorTest.class.getResourceAsStream(EXP_FILE);
BufferedReader expReader = new BufferedReader(new InputStreamReader(expStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = expReader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
expStream.close();
expReader.close();
URL url = AbstractBibReferenceExtractorTest.class.getResource(TEST_FILE);
ZipFile zipFile = new ZipFile(new File(url.toURI()));
InputStream inputStream = zipFile.getInputStream(zipFile.getEntry("out.xml"));
BxDocument expDocument = new BxDocument().setPages(bxReader.read(new InputStreamReader(inputStream)));
String[] references = getExtractor().extractBibReferences(expDocument);
assertEquals(StringUtils.join(references, "\n"), sb.toString().trim());
}
#location 11
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void metadataExtractionTest() throws AnalysisException, JDOMException, IOException, SAXException, TransformationException, URISyntaxException {
InputStream expStream = AbstractBibReferenceExtractorTest.class.getResourceAsStream(EXP_FILE);
BufferedReader expReader = new BufferedReader(new InputStreamReader(expStream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = expReader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
expStream.close();
expReader.close();
URL url = AbstractBibReferenceExtractorTest.class.getResource(TEST_FILE);
ZipFile zipFile = new ZipFile(new File(url.toURI()));
InputStream inputStream = zipFile.getInputStream(zipFile.getEntry("out.xml"));
BxDocument expDocument = new BxDocument().setPages(bxReader.read(new InputStreamReader(inputStream, "UTF-8")));
String[] references = getExtractor().extractBibReferences(expDocument);
assertEquals(StringUtils.join(references, "\n"), sb.toString().trim());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.