output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
private void handleResponse(CloseableHttpResponse httpResponse) throws IOException, SaturnJobException {
int status = httpResponse.getStatusLine().getStatusCode();
if (status == 201) {
logger.info("raise alarm successfully.");
return;
}
if (status >= 400 && status <= 500) {
String responseBody = EntityUtils.toString(httpResponse.getEntity());
if (StringUtils.isNotBlank(responseBody)) {
String errMsg = JSONObject.parseObject(responseBody).getString("message");
throw constructSaturnJobException(status, errMsg);
} else {
throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, "internal server error");
}
} else {
// if have unexpected status, then throw RuntimeException directly.
String errMsg = "unexpected status returned from Saturn Server.";
throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, errMsg);
}
} | #vulnerable code
private void handleResponse(CloseableHttpResponse httpResponse) throws IOException, SaturnJobException {
int status = httpResponse.getStatusLine().getStatusCode();
if (status == 201) {
logger.info("raise alarm successfully.");
return;
}
if (status >= 400 && status <= 500) {
HttpEntity entity = httpResponse.getEntity();
StringBuffer buffer = new StringBuffer();
if (entity != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
String temp = null;
while ((temp = in.readLine()) != null) {
buffer.append(temp);
}
}
if (buffer.toString().length() > 0) {
String errMsg = JSONObject.parseObject(buffer.toString()).getString("message");
throw constructSaturnJobException(status, errMsg);
}
} else {
// if have unexpected status, then throw RuntimeException directly.
String errMsg = "unexpected status returned from Saturn Server.";
throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, errMsg);
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void init() {
if (zkConfig.isUseNestedZookeeper()) {
NestedZookeeperServers.getInstance().startServerIfNotStarted(zkConfig.getNestedPort(), zkConfig.getNestedDataDir());
}
log.info("msg=Saturn job: zookeeper registry center init, server lists is: {}.", zkConfig.getServerLists());
Builder builder = CuratorFrameworkFactory.builder()
.connectString(zkConfig.getServerLists())
.sessionTimeoutMs(SESSION_TIMEOUT)
.connectionTimeoutMs(CONNECTION_TIMEOUT)
.retryPolicy(new ExponentialBackoffRetry(zkConfig.getBaseSleepTimeMilliseconds(), zkConfig.getMaxRetries(), zkConfig.getMaxSleepTimeMilliseconds()))
.namespace(zkConfig.getNamespace());
if (0 != zkConfig.getSessionTimeoutMilliseconds()) {
builder.sessionTimeoutMs(zkConfig.getSessionTimeoutMilliseconds());
sessionTimeout = zkConfig.getSessionTimeoutMilliseconds();
}
if (0 != zkConfig.getConnectionTimeoutMilliseconds()) {
builder.connectionTimeoutMs(zkConfig.getConnectionTimeoutMilliseconds());
}
if (!Strings.isNullOrEmpty(zkConfig.getDigest())) {
builder.authorization("digest", zkConfig.getDigest().getBytes(Charset.forName("UTF-8")))
.aclProvider(new ACLProvider() {
@Override
public List<ACL> getDefaultAcl() {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
@Override
public List<ACL> getAclForPath(final String path) {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
});
}
client = builder.build();
client.start();
try {
client.getZookeeperClient().blockUntilConnectedOrTimedOut();
if (!client.getZookeeperClient().isConnected()) {
throw new Exception("the zk client is not connected");
}
client.checkExists().forPath(SLASH_CONSTNAT + zkConfig.getNamespace()); // check namespace node by using client, for UnknownHostException of connection string.
//CHECKSTYLE:OFF
} catch (final Exception ex) {
throw new RuntimeException("zk connect fail, zkList is " + zkConfig.getServerLists(),ex);
}
// start monitor.
if (zkConfig.getMonitorPort() > 0) {
monitorService = new MonitorService(this, zkConfig.getMonitorPort());
monitorService.listen();
log.info("msg=zk monitor port starts at {}. usage: telnet {jobServerIP} {} and execute dump {jobName}", zkConfig.getMonitorPort(), zkConfig.getMonitorPort());
}
} | #vulnerable code
@Override
public void init() {
if (zkConfig.isUseNestedZookeeper()) {
NestedZookeeperServers.getInstance().startServerIfNotStarted(zkConfig.getNestedPort(), zkConfig.getNestedDataDir());
}
log.info("msg=Saturn job: zookeeper registry center init, server lists is: {}.", zkConfig.getServerLists());
Builder builder = CuratorFrameworkFactory.builder()
.connectString(zkConfig.getServerLists())
.sessionTimeoutMs(SESSION_TIMEOUT)
.connectionTimeoutMs(CONNECTION_TIMEOUT)
.retryPolicy(new ExponentialBackoffRetry(zkConfig.getBaseSleepTimeMilliseconds(), zkConfig.getMaxRetries(), zkConfig.getMaxSleepTimeMilliseconds()))
.namespace(zkConfig.getNamespace());
if (0 != zkConfig.getSessionTimeoutMilliseconds()) {
builder.sessionTimeoutMs(zkConfig.getSessionTimeoutMilliseconds());
sessionTimeout = zkConfig.getSessionTimeoutMilliseconds();
}
if (0 != zkConfig.getConnectionTimeoutMilliseconds()) {
builder.connectionTimeoutMs(zkConfig.getConnectionTimeoutMilliseconds());
}
if (!Strings.isNullOrEmpty(zkConfig.getDigest())) {
builder.authorization("digest", zkConfig.getDigest().getBytes(Charset.forName("UTF-8")))
.aclProvider(new ACLProvider() {
@Override
public List<ACL> getDefaultAcl() {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
@Override
public List<ACL> getAclForPath(final String path) {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
});
}
client = builder.build();
client.start();
try {
client.getZookeeperClient().blockUntilConnectedOrTimedOut();
if (!client.getZookeeperClient().isConnected()) {
throw new Exception("the zk client is not connected");
}
client.checkExists().forPath(SLASH_CONSTNAT + zkConfig.getNamespace()); // check namespace node by using client, for UnknownHostException of connection string.
//CHECKSTYLE:OFF
} catch (final Exception ex) {
throw new RuntimeException("zk connect fail, zkList is " + zkConfig.getServerLists(),ex);
}
// start monitor.
if (zkConfig.getMonitorPort() > 0) {
MonitorService monitorService = new MonitorService(this, zkConfig.getMonitorPort());
monitorService.listen();
log.info("msg=zk monitor port starts at {}. usage: telnet {jobServerIP} {} and execute dump {jobName}", zkConfig.getMonitorPort(), zkConfig.getMonitorPort());
}
}
#location 51
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static List<Long> getPidsFromFile(String executorName, String jobName, String jobItem) {
List<Long> pids = new ArrayList<Long>();
//兼容旧版PID目录
Long pid = _getPidFromFile(executorName, jobName, jobItem);
if(pid > 0){
pids.add(pid);
}
String path = String.format(JOBITEMPIDSPATH, executorName, jobName, jobItem);
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory()) {
return pids;
}
File[] files = dir.listFiles();
if(files == null || files.length == 0){
return pids;
}
for(File file:files){
try {
pids.add(Long.parseLong(file.getName()));
} catch (Exception e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, "Parsing the pid file error"), e);
}
}
return pids;
} | #vulnerable code
public static List<Long> getPidsFromFile(String executorName, String jobName, String jobItem) {
List<Long> pids = new ArrayList<Long>();
//兼容旧版PID目录
Long pid = _getPidFromFile(executorName, jobName, jobItem);
if(pid > 0){
pids.add(pid);
}
String path = String.format(JOBITEMPIDSPATH, executorName, jobName, jobItem);
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory()) {
return pids;
}
File[] files = dir.listFiles();
if(files.length == 0){
return pids;
}
for(File file:files){
try {
pids.add(Long.parseLong(file.getName()));
} catch (Exception e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, "Parsing the pid file error"), e);
}
}
return pids;
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void startNamespaceShardingManagerList(int count) throws Exception {
assertThat(nestedZkUtils.isStarted());
for (int i = 0; i < count; i++) {
ZookeeperRegistryCenter shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration(-1, nestedZkUtils.getZkString(), NAMESPACE, 1000, 3000, 3));
shardingRegCenter.init();
NamespaceShardingManager namespaceShardingManager = new NamespaceShardingManager((CuratorFramework) shardingRegCenter.getRawClient(),NAMESPACE, "127.0.0.1-" + i);
namespaceShardingManager.start();
namespaceShardingManagerList.add(namespaceShardingManager);
}
} | #vulnerable code
public static void startNamespaceShardingManagerList(int count) throws Exception {
assertThat(nestedZkUtils.isStarted());
for (int i = 0; i < count; i++) {
shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration(-1, nestedZkUtils.getZkString(), NAMESPACE, 1000, 3000, 3));
shardingRegCenter.init();
NamespaceShardingManager namespaceShardingManager = new NamespaceShardingManager((CuratorFramework) shardingRegCenter.getRawClient(),NAMESPACE, "127.0.0.1-" + i);
namespaceShardingManager.start();
namespaceShardingManagerList.add(namespaceShardingManager);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void refreshNamespaceShardingListenerManagerMap() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: zkCluster.getRegCenterConfList()) {
String nns = conf.getNameAndNamespace();
if(!namespaceShardingListenerManagerMap.containsKey(nns)) {
// client 从缓存取,不再新建也就不需要关闭
try {
CuratorFramework client = connect(conf.getNameAndNamespace()).getCuratorClient();
NamespaceShardingManager newObj = new NamespaceShardingManager(client, conf.getNamespace(), generateShardingLeadershipHostValue());
if (namespaceShardingListenerManagerMap.putIfAbsent(nns, newObj) == null) {
log.info("start NamespaceShardingManager {}", nns);
newObj.start();
log.info("done starting NamespaceShardingManager {}", nns);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
// 关闭无用的
Iterator<Entry<String, NamespaceShardingManager>> iterator = namespaceShardingListenerManagerMap.entrySet().iterator();
while(iterator.hasNext()) {
Entry<String, NamespaceShardingManager> next = iterator.next();
String nns = next.getKey();
NamespaceShardingManager namespaceShardingManager = next.getValue();
boolean find = false;
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: zkCluster.getRegCenterConfList()) {
if(conf.getNameAndNamespace().equals(nns)) {
find = true;
break;
}
}
if(find) {
break;
}
}
if(!find) {
namespaceShardingManager.stop();
iterator.remove();
// clear NNS_CURATOR_CLIENT_MAP
RegistryCenterClient registryCenterClient = NNS_CURATOR_CLIENT_MAP.remove(nns);
if (registryCenterClient != null) {
log.info("close zk client in NNS_CURATOR_CLIENT_MAP, nns: {}");
CloseableUtils.closeQuietly(registryCenterClient.getCuratorClient());
}
}
}
} | #vulnerable code
private void refreshNamespaceShardingListenerManagerMap() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
String namespace = conf.getNamespace();
if(!namespaceShardingListenerManagerMap.containsKey(namespace)) {
// client 从缓存取,不再新建也就不需要关闭
try {
CuratorFramework client = connect(conf.getNameAndNamespace()).getCuratorClient();
NamespaceShardingManager newObj = new NamespaceShardingManager(client, namespace, generateShardingLeadershipHostValue());
if (namespaceShardingListenerManagerMap.putIfAbsent(namespace, newObj) == null) {
log.info("start NamespaceShardingManager {}", namespace);
newObj.start();
log.info("done starting NamespaceShardingManager {}", namespace);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
// 关闭无用的
Iterator<Entry<String, NamespaceShardingManager>> iterator = namespaceShardingListenerManagerMap.entrySet().iterator();
while(iterator.hasNext()) {
Entry<String, NamespaceShardingManager> next = iterator.next();
String namespace = next.getKey();
NamespaceShardingManager namespaceShardingManager = next.getValue();
boolean find = false;
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
if(conf.getNamespace().equals(namespace)) {
find = true;
break;
}
}
}
if(!find) {
namespaceShardingManager.stop();
iterator.remove();
}
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> Cursor<T> queryForCursor(Query query, final Class<T> clazz) {
return new DelegatingCursor<T>(queryParsers.getForClass(query.getClass()).constructSolrQuery(query)) {
@Override
protected org.springframework.data.solr.core.query.result.DelegatingCursor.PartialResult<T> doLoad(
SolrQuery nativeQuery) {
QueryResponse response = executeSolrQuery(nativeQuery, getSolrRequestMethod(getDefaultRequestMethod()));
if (response == null) {
return new PartialResult<T>("", Collections.<T> emptyList());
}
return new PartialResult<T>(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz));
}
}.open();
} | #vulnerable code
public <T> Cursor<T> queryForCursor(Query query, final Class<T> clazz) {
return new DelegatingCursor<T>(queryParsers.getForClass(query.getClass()).constructSolrQuery(query)) {
@Override
protected org.springframework.data.solr.core.query.result.DelegatingCursor.PartialResult<T> doLoad(
SolrQuery nativeQuery) {
QueryResponse response = executeSolrQuery(nativeQuery);
if (response == null) {
return new PartialResult<T>("", Collections.<T> emptyList());
}
return new PartialResult<T>(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz));
}
}.open();
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(this);
actor.lifeCycle.nextDispersing();
} else {
internalDeliver(this);
}
} | #vulnerable code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
} | #vulnerable code
@Override
public void deliver() {
if (actor.__internal__IsResumed()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.__internal__Environment().suspended.swapWith(this));
}
actor.__internal__NextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.__internal__Environment().stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(this);
actor.lifeCycle.nextDispersing();
} else {
internalDeliver(this);
}
} | #vulnerable code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void addChild(final Actor child) {
children.add(child);
} | #vulnerable code
void stop() {
if (stopped.compareAndSet(false, true)) {
stopChildren();
// suspended.reset();
// stowage.reset();
mailbox.close();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void addChild(final Actor child) {
children.add(child);
} | #vulnerable code
void addChild(final Actor child) {
children = children.plus(child);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
} | #vulnerable code
@Override
public void deliver() {
if (actor.__internal__IsResumed()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.__internal__Environment().suspended.swapWith(this));
}
actor.__internal__NextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.__internal__Environment().stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
try (ZMQ.Context zctx = new ZMQ.Context(1);
ZMQ.Socket s = zctx.socket(SocketType.PUB);
ZMQ.Socket m = zctx.socket(SocketType.PAIR)) {
s.monitor("inproc://TestEventResolution", eventFilter);
m.connect("inproc://TestEventResolution");
sender.send(s.base(), "tcp://127.0.0.1:8000");
return ZMQ.Event.recv(m);
}
} | #vulnerable code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
Ctx ctx = new Ctx();
@SuppressWarnings("deprecation")
SocketBase s = ctx.createSocket(ZMQ.PUB);
@SuppressWarnings("deprecation")
SocketBase m = ctx.createSocket(ZMQ.PAIR);
m.connect("inproc://TestEventResolution");
s.monitor("inproc://TestEventResolution", eventFilter);
sender.send(s, "tcp://127.0.0.1:8000");
zmq.ZMQ.Event ev = zmq.ZMQ.Event.read(m);
return new ZMQ.Event(ev.event, ev.arg, ev.addr);
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testProxy() throws Exception
{
int frontendPort = Utils.findOpenPort();
int backendPort = Utils.findOpenPort();
Context ctx = ZMQ.context(1);
assert (ctx != null);
Main mt = new Main(ctx, frontendPort, backendPort);
mt.start();
new Dealer(ctx, "AA", backendPort).start();
new Dealer(ctx, "BB", backendPort).start();
Thread.sleep(1000);
Thread c1 = new Client(ctx, "X", frontendPort);
c1.start();
Thread c2 = new Client(ctx, "Y", frontendPort);
c2.start();
c1.join();
c2.join();
ctx.term();
} | #vulnerable code
@Test
public void testProxy() throws Exception
{
Context ctx = ZMQ.context(1);
assert (ctx != null);
Main mt = new Main(ctx);
mt.start();
new Dealer(ctx, "AA").start();
new Dealer(ctx, "BB").start();
Thread.sleep(1000);
Thread c1 = new Client(ctx, "X");
c1.start();
Thread c2 = new Client(ctx, "Y");
c2.start();
c1.join();
c2.join();
ctx.term();
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected boolean xsend(Msg msg_)
{
// If this is the first part of the message it's the ID of the
// peer to send the message to.
if (!more_out) {
assert (current_out == null);
// If we have malformed message (prefix with no subsequent message)
// then just silently ignore it.
// TODO: The connections should be killed instead.
if (msg_.has_more()) {
more_out = true;
// Find the pipe associated with the identity stored in the prefix.
// If there's no such pipe just silently ignore the message, unless
// mandatory is set.
Blob identity = Blob.createBlob(msg_.data(), true);
Outpipe op = outpipes.get(identity);
if (op != null) {
current_out = op.pipe;
if (!current_out.check_write ()) {
op.active = false;
current_out = null;
if (mandatory) {
more_out = false;
errno.set(ZError.EAGAIN);
return false;
}
}
} else if (mandatory) {
more_out = false;
errno.set(ZError.EHOSTUNREACH);
return false;
}
}
return true;
}
// Check whether this is the last part of the message.
more_out = msg_.has_more();
// Push the message into the pipe. If there's no out pipe, just drop it.
if (current_out != null) {
boolean ok = current_out.write (msg_);
if (!ok)
current_out = null;
else if (!more_out) {
current_out.flush ();
current_out = null;
}
}
return true;
} | #vulnerable code
@Override
protected boolean xsend(Msg msg_)
{
// If this is the first part of the message it's the ID of the
// peer to send the message to.
if (!more_out) {
assert (current_out == null);
// If we have malformed message (prefix with no subsequent message)
// then just silently ignore it.
// TODO: The connections should be killed instead.
if (msg_.has_more()) {
more_out = true;
// Find the pipe associated with the identity stored in the prefix.
// If there's no such pipe just silently ignore the message, unless
// mandatory is set.
Blob identity = new Blob(msg_.data());
Outpipe op = outpipes.get(identity);
if (op != null) {
current_out = op.pipe;
if (!current_out.check_write ()) {
op.active = false;
current_out = null;
if (mandatory) {
more_out = false;
errno.set(ZError.EAGAIN);
return false;
}
}
} else if (mandatory) {
more_out = false;
errno.set(ZError.EHOSTUNREACH);
return false;
}
}
return true;
}
// Check whether this is the last part of the message.
more_out = msg_.has_more();
// Push the message into the pipe. If there's no out pipe, just drop it.
if (current_out != null) {
boolean ok = current_out.write (msg_);
if (!ok)
current_out = null;
else if (!more_out) {
current_out.flush ();
current_out = null;
}
}
return true;
}
#location 19
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int start ()
{
int rc = 0;
timers.addAll(newTimers);
newTimers.clear();
// Recalculate all timers now
for (STimer timer: timers) {
timer.when = timer.delay + System.currentTimeMillis();
}
Selector selector;
try {
selector = Selector.open();
} catch (IOException e) {
System.err.println (e.getMessage());
return -1;
}
// Main reactor loop
while (!Thread.currentThread().isInterrupted()) {
if (dirty) {
// If s_rebuild_pollset() fails, break out of the loop and
// return its error
rebuild ();
}
long wait = ticklessTimer();
rc = zmq.ZMQ.zmq_poll (selector, pollset, wait);
if (rc == -1) {
if (verbose)
System.out.println("I: zloop: interrupted");
rc = 0;
break; // Context has been shut down
}
// Handle any timers that have now expired
Iterator<STimer> it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (System.currentTimeMillis() >= timer.when && timer.when != -1) {
if (verbose)
System.out.println ("I: zloop: call timer handler");
rc = timer.handler.handle(this, null, timer.arg);
if (rc == -1)
break; // Timer handler signalled break
if (timer.times != 0 && --timer.times == 0) {
it.remove();
}
else
timer.when = timer.delay + System.currentTimeMillis();
}
}
if (rc == -1)
break; // Some timer signalled break from the reactor loop
// Handle any pollers that are ready
for (int item_nbr = 0; item_nbr < poll_size; item_nbr++) {
SPoller poller = pollact [item_nbr];
assert (pollset [item_nbr].getSocket() == poller.item.getSocket());
if (pollset [item_nbr].isError()) {
if (verbose)
System.out.printf ("I: zloop: can't poll %s socket (%s, %s)",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
// Give handler one chance to handle error, then kill
// poller because it'll disrupt the reactor otherwise.
if (poller.errors++ > 0) {
pollerEnd (poller.item);
}
}
else
poller.errors = 0; // A non-error happened
if (pollset [item_nbr].readyOps() > 0) {
if (verbose)
System.out.printf ("I: zloop: call %s socket handler (%s, %s)\n",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
rc = poller.handler.handle (this, poller.item, poller.arg);
if (rc == -1)
break; // Poller handler signalled break
}
}
// Now handle any timer zombies
// This is going to be slow if we have many zombies
for (Object arg: zombies) {
it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (timer.arg == arg) {
it.remove();
}
}
}
// Now handle any new timers added inside the loop
timers.addAll(newTimers);
newTimers.clear();
if (rc == -1)
break;
}
try {
selector.close();
} catch (IOException e) {
}
return rc;
} | #vulnerable code
public int start ()
{
int rc = 0;
timers.addAll(newTimers);
newTimers.clear();
// Recalculate all timers now
for (STimer timer: timers) {
timer.when = timer.delay + System.currentTimeMillis();
}
Selector selector;
try {
selector = Selector.open();
} catch (IOException e) {
System.err.println (e.getMessage());
return -1;
}
// Main reactor loop
while (!Thread.currentThread().isInterrupted()) {
if (dirty) {
// If s_rebuild_pollset() fails, break out of the loop and
// return its error
rebuild ();
}
long wait = ticklessTimer();
rc = zmq.ZMQ.zmq_poll (selector, pollset, wait);
if (rc == -1) {
if (verbose)
System.out.printf ("I: zloop: interrupted\n", rc);
rc = 0;
break; // Context has been shut down
}
// Handle any timers that have now expired
Iterator<STimer> it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (System.currentTimeMillis() >= timer.when && timer.when != -1) {
if (verbose)
System.out.println ("I: zloop: call timer handler");
rc = timer.handler.handle(this, null, timer.arg);
if (rc == -1)
break; // Timer handler signalled break
if (timer.times != 0 && --timer.times == 0) {
it.remove();
}
else
timer.when = timer.delay + System.currentTimeMillis();
}
}
if (rc == -1)
break; // Some timer signalled break from the reactor loop
// Handle any pollers that are ready
for (int item_nbr = 0; item_nbr < poll_size; item_nbr++) {
SPoller poller = pollact [item_nbr];
assert (pollset [item_nbr].getSocket() == poller.item.getSocket());
if (pollset [item_nbr].isError()) {
if (verbose)
System.out.printf ("I: zloop: can't poll %s socket (%s, %s)",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
// Give handler one chance to handle error, then kill
// poller because it'll disrupt the reactor otherwise.
if (poller.errors++ > 0) {
pollerEnd (poller.item);
}
}
else
poller.errors = 0; // A non-error happened
if (pollset [item_nbr].readyOps() > 0) {
if (verbose)
System.out.printf ("I: zloop: call %s socket handler (%s, %s)\n",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
rc = poller.handler.handle (this, poller.item, poller.arg);
if (rc == -1)
break; // Poller handler signalled break
}
}
// Now handle any timer zombies
// This is going to be slow if we have many zombies
for (Object arg: zombies) {
it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (timer.arg == arg) {
it.remove();
}
}
}
// Now handle any new timers added inside the loop
timers.addAll(newTimers);
newTimers.clear();
if (rc == -1)
break;
}
try {
selector.close();
} catch (IOException e) {
}
return rc;
}
#location 32
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Command recv (long timeout_)
{
Command cmd_ = null;
// Try to get the command straight away.
if (active) {
cmd_ = cpipe.read ();
if (cmd_ != null) {
return cmd_;
}
// If there are no more commands available, switch into passive state.
active = false;
signaler.recv ();
}
// Wait for signal from the command sender.
boolean rc = signaler.wait_event (timeout_);
if (!rc)
return null;
// We've got the signal. Now we can switch into active state.
active = true;
// Get a command.
cmd_ = cpipe.read ();
assert (cmd_ != null);
return cmd_;
} | #vulnerable code
public Command recv (long timeout_)
{
Command cmd_ = null;
// Try to get the command straight away.
if (active) {
cmd_ = cpipe.read ();
if (cmd_ != null) {
return cmd_;
}
// If there are no more commands available, switch into passive state.
active = false;
signaler.recv ();
}
// Wait for signal from the command sender.
boolean rc = signaler.wait_event (timeout_);
if (!rc)
return null;
assert (rc);
// We've got the signal. Now we can switch into active state.
active = true;
// Get a command.
cmd_ = cpipe.read ();
assert (cmd_ != null);
return cmd_;
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
receiver.close ();
subscriber.close ();
context.term ();
} | #vulnerable code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
subscriber.close ();
context.term ();
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void destroySocket(Socket s)
{
if (s == null) {
return;
}
s.setLinger(linger);
s.close();
try {
mutex.lock();
this.sockets.remove(s);
}
finally {
mutex.unlock();
}
} | #vulnerable code
public void destroySocket(Socket s)
{
if (s == null) {
return;
}
if (sockets.remove(s)) {
s.setLinger(linger);
s.close();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectResolve() throws IOException
{
int port = Utils.findOpenPort();
System.out.println("test_connect_resolve running...\n");
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
// Create pair of socket, each with high watermark of 2. Thus the total
// buffer space should be 4 messages.
SocketBase sock = ZMQ.socket(ctx, ZMQ.ZMQ_PUB);
assertThat(sock, notNullValue());
boolean brc = ZMQ.connect(sock, "tcp://localhost:" + port);
assertThat(brc, is(true));
/*
try {
brc = ZMQ.connect (sock, "tcp://foobar123xyz:" + port);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
*/
ZMQ.close(sock);
ZMQ.term(ctx);
} | #vulnerable code
@Test
public void testConnectResolve()
{
System.out.println("test_connect_resolve running...\n");
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
// Create pair of socket, each with high watermark of 2. Thus the total
// buffer space should be 4 messages.
SocketBase sock = ZMQ.socket(ctx, ZMQ.ZMQ_PUB);
assertThat(sock, notNullValue());
boolean brc = ZMQ.connect(sock, "tcp://localhost:1234");
assertThat(brc, is(true));
/*
try {
brc = ZMQ.connect (sock, "tcp://foobar123xyz:1234");
assertTrue(false);
} catch (IllegalArgumentException e) {
}
*/
ZMQ.close(sock);
ZMQ.term(ctx);
}
#location 26
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
try (ZMQ.Context zctx = new ZMQ.Context(1);
ZMQ.Socket s = zctx.socket(SocketType.PUB);
ZMQ.Socket m = zctx.socket(SocketType.PAIR)) {
s.monitor("inproc://TestEventResolution", eventFilter);
m.connect("inproc://TestEventResolution");
sender.send(s.base(), "tcp://127.0.0.1:8000");
return ZMQ.Event.recv(m);
}
} | #vulnerable code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
Ctx ctx = new Ctx();
@SuppressWarnings("deprecation")
SocketBase s = ctx.createSocket(ZMQ.PUB);
@SuppressWarnings("deprecation")
SocketBase m = ctx.createSocket(ZMQ.PAIR);
m.connect("inproc://TestEventResolution");
s.monitor("inproc://TestEventResolution", eventFilter);
sender.send(s, "tcp://127.0.0.1:8000");
zmq.ZMQ.Event ev = zmq.ZMQ.Event.read(m);
return new ZMQ.Event(ev.event, ev.arg, ev.addr);
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
context = null;
}
} | #vulnerable code
public void destroy()
{
for (Socket socket : sockets) {
socket.setLinger(linger);
socket.close();
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
}
synchronized (this) {
context = null;
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test(timeout = 1000)
public void testSocketDoubleClose()
{
Context ctx = ZMQ.context(1);
Socket socket = ctx.socket(ZMQ.PUSH);
socket.close();
socket.close();
ctx.term();
} | #vulnerable code
@Test(timeout = 1000)
public void testSocketDoubleClose()
{
Context ctx = ZMQ.context(1);
Socket socket = ctx.socket(ZMQ.PUSH);
socket.close();
socket.close();
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testIssue476() throws InterruptedException, IOException, ExecutionException
{
final int front = Utils.findOpenPort();
final int back = Utils.findOpenPort();
final int max = 20;
ExecutorService service = Executors.newFixedThreadPool(3);
try (final ZContext ctx = new ZContext()) {
service.submit(() -> {
Thread.currentThread().setName("Proxy");
Socket xpub = ctx.createSocket(SocketType.XPUB);
xpub.bind("tcp://*:" + back);
Socket xsub = ctx.createSocket(SocketType.XSUB);
xsub.bind("tcp://*:" + front);
Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.bind("inproc://ctrl-proxy");
ZMQ.proxy(xpub, xsub, null, ctrl);
});
final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx);
ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.connect("inproc://ctrl-proxy");
ctrl.send(ZMQ.PROXY_TERMINATE);
ctrl.close();
service.shutdown();
service.awaitTermination(2, TimeUnit.SECONDS);
assertThat(error.get(), nullValue());
}
} | #vulnerable code
@Test
public void testIssue476() throws InterruptedException, IOException, ExecutionException
{
final int front = Utils.findOpenPort();
final int back = Utils.findOpenPort();
final int max = 10;
ExecutorService service = Executors.newFixedThreadPool(3);
final ZContext ctx = new ZContext();
service.submit(new Runnable()
{
@Override
public void run()
{
Thread.currentThread().setName("Proxy");
ZMQ.Socket xpub = ctx.createSocket(SocketType.XPUB);
xpub.bind("tcp://*:" + back);
ZMQ.Socket xsub = ctx.createSocket(SocketType.XSUB);
xsub.bind("tcp://*:" + front);
ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.bind("inproc://ctrl-proxy");
ZMQ.proxy(xpub, xsub, null, ctrl);
}
});
final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx);
ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.connect("inproc://ctrl-proxy");
ctrl.send(ZMQ.PROXY_TERMINATE);
ctrl.close();
service.shutdown();
service.awaitTermination(2, TimeUnit.SECONDS);
assertThat(error.get(), nullValue());
ctx.close();
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public byte[] receive(int flags)
{
final Msg msg = socketBase.recv(flags);
if (msg == null) {
return null;
}
return msg.data();
} | #vulnerable code
public byte[] receive(int flags)
{
final Msg msg = socketBase.recv(flags);
return msg.data();
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
receiver.close ();
subscriber.close ();
context.term ();
} | #vulnerable code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
subscriber.close ();
context.term ();
}
#location 30
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
boolean wasPending (kvmsg msg)
{
Iterator<kvmsg> it = pending.iterator();
while (it.hasNext()) {
if(java.util.Arrays.equals(msg.UUID(), it.next().UUID())){
it.remove();
return true;
}
}
return false;
} | #vulnerable code
boolean wasPending (kvmsg msg)
{
Iterator<kvmsg> it = pending.iterator();
while (it.hasNext()) {
if (msg.UUID().equals(it.next().UUID())) {
it.remove();
return true;
}
}
return false;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testHeartbeatTimeout() throws IOException, InterruptedException
{
testHeartbeatTimeout(false);
} | #vulnerable code
@Test
public void testHeartbeatTimeout() throws IOException, InterruptedException
{
Ctx ctx = ZMQ.createContext();
assertThat(ctx, notNullValue());
SocketBase server = prepServerSocket(ctx, true, false);
assertThat(server, notNullValue());
SocketBase monitor = ZMQ.socket(ctx, ZMQ.ZMQ_PAIR);
boolean rc = monitor.connect("inproc://monitor");
assertThat(rc, is(true));
String endpoint = (String) ZMQ.getSocketOptionExt(server, ZMQ.ZMQ_LAST_ENDPOINT);
assertThat(endpoint, notNullValue());
Socket socket = new Socket("127.0.0.1", TestUtils.port(endpoint));
// Mock a ZMTP 3 client so we can forcibly time out a connection
mockHandshake(socket);
// By now everything should report as connected
ZMQ.Event event = ZMQ.Event.read(monitor);
assertThat(event.event, is(ZMQ.ZMQ_EVENT_ACCEPTED));
// We should have been disconnected
event = ZMQ.Event.read(monitor);
assertThat(event.event, is(ZMQ.ZMQ_EVENT_DISCONNECTED));
socket.close();
ZMQ.close(monitor);
ZMQ.close(server);
ZMQ.term(ctx);
}
#location 35
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
context = null;
}
} | #vulnerable code
public void destroy()
{
for (Socket socket : sockets) {
socket.setLinger(linger);
socket.close();
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
}
synchronized (this) {
context = null;
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testLastEndpoint()
{
// Create the infrastructure
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
SocketBase sb = ZMQ.socket(ctx, ZMQ.ZMQ_ROUTER);
assertThat(sb, notNullValue());
bindAndVerify(sb, "tcp://127.0.0.1:5560");
bindAndVerify(sb, "tcp://127.0.0.1:5561");
bindAndVerify(sb, "ipc:///tmp/testep" + UUID.randomUUID().toString());
sb.close();
ctx.terminate();
} | #vulnerable code
@Test
public void testLastEndpoint()
{
// Create the infrastructure
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
SocketBase sb = ZMQ.socket(ctx, ZMQ.ZMQ_ROUTER);
assertThat(sb, notNullValue());
bindAndVerify(sb, "tcp://127.0.0.1:5560");
bindAndVerify(sb, "tcp://127.0.0.1:5561");
bindAndVerify(sb, "ipc:///tmp/testep");
sb.close();
ctx.terminate();
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain()) {
context.term();
}
} | #vulnerable code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
context = null;
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
try (ZMQ.Context zctx = new ZMQ.Context(1);
ZMQ.Socket s = zctx.socket(SocketType.PUB);
ZMQ.Socket m = zctx.socket(SocketType.PAIR)) {
s.monitor("inproc://TestEventResolution", eventFilter);
m.connect("inproc://TestEventResolution");
sender.send(s.base(), "tcp://127.0.0.1:8000");
return ZMQ.Event.recv(m);
}
} | #vulnerable code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
Ctx ctx = new Ctx();
@SuppressWarnings("deprecation")
SocketBase s = ctx.createSocket(ZMQ.PUB);
@SuppressWarnings("deprecation")
SocketBase m = ctx.createSocket(ZMQ.PAIR);
m.connect("inproc://TestEventResolution");
s.monitor("inproc://TestEventResolution", eventFilter);
sender.send(s, "tcp://127.0.0.1:8000");
zmq.ZMQ.Event ev = zmq.ZMQ.Event.read(m);
return new ZMQ.Event(ev.event, ev.arg, ev.addr);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean send(Msg msg_, int flags_) {
// Drop the message if required. If we are at the end of the message
// switch back to non-dropping mode.
if (dropping) {
more = msg_.has_more();
dropping = more;
msg_.close ();
return true;
}
while (active > 0) {
if (pipes.get(current).write (msg_))
break;
assert (!more);
active--;
if (current < active)
Utils.swap (pipes, current, active);
else
current = 0;
}
// If there are no pipes we cannot send the message.
if (active == 0) {
ZError.errno(ZError.EAGAIN);
return false;
}
// If it's final part of the message we can fluch it downstream and
// continue round-robinning (load balance).
more = msg_.has_more();
if (!more) {
pipes.get(current).flush ();
if (active > 1)
current = (current + 1) % active;
}
return true;
} | #vulnerable code
public boolean send(Msg msg_, int flags_) {
// Drop the message if required. If we are at the end of the message
// switch back to non-dropping mode.
if (dropping) {
more = msg_.has_more();
dropping = more;
msg_.close ();
return true;
}
Pipe pipe = null;
while (active > start) {
pipe = pipes.get(current);
if (pipe.write (msg_))
break;
assert (!more);
current++;
start = current;
if (current == active)
current = start = active = 0;
}
// If there are no pipes we cannot send the message.
if (active == start) {
ZError.errno(ZError.EAGAIN);
return false;
}
// If it's final part of the message we can fluch it downstream and
// continue round-robinning (load balance).
more = msg_.has_more();
if (!more) {
pipe.flush ();
current++;
if (current == active)
current = start;
}
return true;
}
#location 36
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void test_streaming_changes() throws IOException {
HttpResponse httpResponse = ResponseOnFileStub.newInstance(200, "changes/changes_full.json");
StreamingChangesResult changes = new StreamingChangesResult(new ObjectMapper(),
httpResponse);
int i = 0;
for (DocumentChange documentChange : changes) {
Assert.assertEquals(++i, documentChange.getSequence());
}
Assert.assertEquals(5, changes.getLastSeq());
changes.close();
} | #vulnerable code
@Test
public void test_streaming_changes() throws IOException {
HttpResponse httpResponse = ResponseOnFileStub.newInstance(200, "changes/changes_full.json");
StreamingChangesResult changes = new StreamingChangesResult(new ObjectMapper(),
httpResponse);
int i = 0;
for (DocumentChange documentChange : changes) {
Assert.assertEquals(++i, documentChange.getSequence());
}
Assert.assertEquals(5, changes.getLastSeq());
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected ReadResponse doRead(ServerIdentity identity, ReadRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (LwM2mInstanceEnabler instance : instances.values()) {
ReadResponse response = instance.read(identity);
if (response.isSuccess()) {
lwM2mObjectInstances.add((LwM2mObjectInstance) response.getContent());
}
}
return ReadResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ReadResponse.notFound();
if (path.getResourceId() == null) {
return instance.read(identity);
}
// Manage Resource case
return instance.read(identity, path.getResourceId());
} | #vulnerable code
@Override
protected ReadResponse doRead(ServerIdentity identity, ReadRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (Entry<Integer, LwM2mInstanceEnabler> entry : instances.entrySet()) {
lwM2mObjectInstances.add(getLwM2mObjectInstance(entry.getKey(), entry.getValue(), identity, false));
}
return ReadResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ReadResponse.notFound();
if (path.getResourceId() == null) {
return ReadResponse.success(getLwM2mObjectInstance(path.getObjectInstanceId(), instance, identity, false));
}
// Manage Resource case
return instance.read(identity, path.getResourceId());
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void createRPKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.rpk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, clientPublicKey.getEncoded(), clientPrivateKey.getEncoded(),
serverPublicKey.getEncoded()));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
// TODO no way to provide a dynamic config with the current scandium API
config.setIdentity(clientPrivateKey, clientPublicKey);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
} | #vulnerable code
public void createRPKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.rpk(
"coaps://" + server.getSecureAddress().getHostString() + ":"
+ server.getSecureAddress().getPort(),
12345, clientPublicKey.getEncoded(), clientPrivateKey.getEncoded(),
serverPublicKey.getEncoded()));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
// TODO no way to provide a dynamic config with the current scandium API
config.setIdentity(clientPrivateKey, clientPublicKey);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
private void loadFromFile() {
try {
File file = new File(filename);
if (file.exists()) {
try (InputStreamReader in = new InputStreamReader(new FileInputStream(file))) {
Map<String, BootstrapConfig> config = gson.fromJson(in, gsonType);
bootstrapByEndpoint.putAll(config);
}
} else {
// TODO temporary code for retro compatibility: remove it later.
if (DEFAULT_FILE.equals(filename)) {
file = new File("data/bootstrap.data");// old bootstrap configurations default filename
if (file.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
bootstrapByEndpoint.putAll((Map<String, BootstrapConfig>) in.readObject());
}
}
}
}
} catch (Exception e) {
LOG.error("Could not load bootstrap infos from file", e);
}
} | #vulnerable code
@SuppressWarnings("unchecked")
private void loadFromFile() {
try {
File file = new File(filename);
if (file.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
bootstrapByEndpoint.putAll((Map<String, BootstrapConfig>) in.readObject());
}
}
} catch (Exception e) {
LOG.error("Could not load bootstrap infos from file", e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException(String.format("TLV payload is mandatory for single resource %s", path));
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
} | #vulnerable code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
#location 76
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void visit(final UpdateRequest request) {
coapRequest = Request.newPut();
buildRequestSettings();
coapRequest.getOptions().setUriPath(request.getRegistrationId());
Long lifetime = request.getLifeTimeInSec();
if (lifetime != null)
coapRequest.getOptions().addUriQuery("lt=" + lifetime);
String smsNumber = request.getSmsNumber();
if (smsNumber != null)
coapRequest.getOptions().addUriQuery("sms=" + smsNumber);
BindingMode bindingMode = request.getBindingMode();
if (bindingMode != null)
coapRequest.getOptions().addUriQuery("b=" + bindingMode.toString());
LinkObject[] linkObjects = request.getObjectLinks();
if (linkObjects != null)
coapRequest.setPayload(LinkObject.serialyse(linkObjects));
} | #vulnerable code
@Override
public void visit(final UpdateRequest request) {
coapRequest = Request.newPut();
buildRequestSettings();
coapRequest.getOptions().setUriPath(request.getRegistrationId());
Long lifetime = request.getLifeTimeInSec();
if (lifetime != null)
coapRequest.getOptions().addUriQuery("lt=" + lifetime);
String smsNumber = request.getSmsNumber();
if (smsNumber != null)
coapRequest.getOptions().addUriQuery("sms=" + smsNumber);
BindingMode bindingMode = request.getBindingMode();
if (bindingMode != null)
coapRequest.getOptions().addUriQuery("b=" + bindingMode.toString());
LinkObject[] linkObjects = request.getObjectLinks();
if (linkObjects == null)
coapRequest.setPayload(LinkObject.serialyse(linkObjects));
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void createPSKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.psk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
} | #vulnerable code
public void createPSKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.psk(
"coaps://" + server.getSecureAddress().getHostString() + ":"
+ server.getSecureAddress().getPort(),
12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void fireResourcesChanged(int instanceid, int... resourceIds) {
transactionalListener.resourceChanged(this, instanceid, resourceIds);
} | #vulnerable code
protected void fireResourcesChanged(int instanceid, int... resourceIds) {
if (listener != null) {
listener.resourceChanged(this, instanceid, resourceIds);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException(String.format("TLV payload is mandatory for single resource %s", path));
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
} | #vulnerable code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
#location 49
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestination(helper.server.getUnsecuredAddress().getAddress());
coapRequest.setDestinationPort(helper.server.getUnsecuredAddress().getPort());
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
} | #vulnerable code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestination(helper.server.getNonSecureAddress().getAddress());
coapRequest.setDestinationPort(helper.server.getNonSecureAddress().getPort());
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestinationContext(new AddressEndpointContext(helper.server.getUnsecuredAddress()));
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
} | #vulnerable code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestination(helper.server.getUnsecuredAddress().getAddress());
coapRequest.setDestinationPort(helper.server.getUnsecuredAddress().getPort());
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void createX509CertClient(PrivateKey privatekey, Certificate[] trustedCertificates) {
ObjectsInitializer initializer = new ObjectsInitializer();
// TODO security instance with certificate info
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coaps://" + server.getSecuredAddress().getHostString() + ":" + server.getSecuredAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
config.setIdentity(privatekey, clientX509CertChain, false);
config.setTrustStore(trustedCertificates);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
} | #vulnerable code
public void createX509CertClient(PrivateKey privatekey, Certificate[] trustedCertificates) {
ObjectsInitializer initializer = new ObjectsInitializer();
// TODO security instance with certificate info
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coaps://" + server.getSecureAddress().getHostString() + ":" + server.getSecureAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
config.setIdentity(privatekey, clientX509CertChain, false);
config.setTrustStore(trustedCertificates);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected BootstrapWriteResponse doWrite(ServerIdentity identity, BootstrapWriteRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
for (LwM2mObjectInstance instanceNode : ((LwM2mObject) request.getNode()).getInstances().values()) {
LwM2mInstanceEnabler instanceEnabler = instances.get(instanceNode.getId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, path.getObjectId(), instanceEnabler.getId(),
instanceNode.getResources().values()));
}
}
return BootstrapWriteResponse.success();
}
// Manage Instance case
if (path.isObjectInstance()) {
LwM2mObjectInstance instanceNode = (LwM2mObjectInstance) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, request.getContentFormat(), path.getObjectId(),
path.getObjectInstanceId(), instanceNode.getResources().values()));
}
return BootstrapWriteResponse.success();
}
// Manage resource case
LwM2mResource resource = (LwM2mResource) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(),
new LwM2mObjectInstance(path.getObjectInstanceId(), resource)));
} else {
instanceEnabler.write(identity, path.getResourceId(), resource);
}
return BootstrapWriteResponse.success();
} | #vulnerable code
@Override
protected BootstrapWriteResponse doWrite(ServerIdentity identity, BootstrapWriteRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
for (LwM2mObjectInstance instanceNode : ((LwM2mObject) request.getNode()).getInstances().values()) {
LwM2mInstanceEnabler instanceEnabler = instances.get(instanceNode.getId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, path.getObjectId(), path.getObjectInstanceId(),
instanceNode.getResources().values()));
}
}
return BootstrapWriteResponse.success();
}
// Manage Instance case
if (path.isObjectInstance()) {
LwM2mObjectInstance instanceNode = (LwM2mObjectInstance) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, request.getContentFormat(), path.getObjectId(),
path.getObjectInstanceId(), instanceNode.getResources().values()));
}
return BootstrapWriteResponse.success();
}
// Manage resource case
LwM2mResource resource = (LwM2mResource) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(),
new LwM2mObjectInstance(path.getObjectInstanceId(), resource)));
} else {
instanceEnabler.write(identity, path.getResourceId(), resource);
}
return BootstrapWriteResponse.success();
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) {
final LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (LwM2mInstanceEnabler instance : instances.values()) {
ReadResponse response = instance.observe(identity);
if (response.isSuccess()) {
lwM2mObjectInstances.add((LwM2mObjectInstance) response.getContent());
}
}
return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ObserveResponse.notFound();
if (path.getResourceId() == null) {
return instance.observe(identity);
}
// Manage Resource case
return instance.observe(identity, path.getResourceId());
} | #vulnerable code
@Override
protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) {
final LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (Entry<Integer, LwM2mInstanceEnabler> entry : instances.entrySet()) {
lwM2mObjectInstances.add(getLwM2mObjectInstance(entry.getKey(), entry.getValue(), identity, true));
}
return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ObserveResponse.notFound();
if (path.getResourceId() == null) {
return ObserveResponse
.success(getLwM2mObjectInstance(path.getObjectInstanceId(), instance, identity, true));
}
// Manage Resource case
return instance.observe(identity, path.getResourceId());
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void remove(byte[] token) {
try (Jedis j = pool.getResource()) {
byte[] tokenKey = toKey(OBS_TKN, token);
// fetch the observation by token
byte[] serializedObs = j.get(tokenKey);
if (serializedObs == null)
return;
org.eclipse.californium.core.observe.Observation obs = deserializeObs(serializedObs);
String registrationId = obs.getRequest().getUserContext().get(CoapRequestBuilder.CTX_REGID);
Registration registration = getRegistration(j, registrationId);
if (registration == null) {
LOG.warn("Unable to remove observation {}, registration {} does not exist anymore", obs.getRequest(),
registrationId);
return;
}
String endpoint = registration.getEndpoint();
byte[] lockValue = null;
byte[] lockKey = toKey(LOCK_EP, endpoint);
try {
lockValue = RedisLock.acquire(j, lockKey);
unsafeRemoveObservation(j, registrationId, token);
} finally {
RedisLock.release(j, lockKey, lockValue);
}
}
} | #vulnerable code
@Override
public void remove(byte[] token) {
try (Jedis j = pool.getResource()) {
byte[] tokenKey = toKey(OBS_TKN, token);
// fetch the observation by token
byte[] serializedObs = j.get(tokenKey);
if (serializedObs == null)
return;
org.eclipse.californium.core.observe.Observation obs = deserializeObs(serializedObs);
String registrationId = obs.getRequest().getUserContext().get(CoapRequestBuilder.CTX_REGID);
Registration registration = getRegistration(j, registrationId);
String endpoint = registration.getEndpoint();
byte[] lockValue = null;
byte[] lockKey = toKey(LOCK_EP, endpoint);
try {
lockValue = RedisLock.acquire(j, lockKey);
unsafeRemoveObservation(j, registrationId, token);
} finally {
RedisLock.release(j, lockKey, lockValue);
}
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void handleUpdate(CoapExchange exchange, Request request, String registrationId) {
// Get identity
Identity sender = extractIdentity(exchange);
// Create LwM2m request from CoAP request
Long lifetime = null;
String smsNumber = null;
BindingMode binding = null;
Link[] objectLinks = null;
for (String param : request.getOptions().getUriQuery()) {
if (param.startsWith(QUERY_PARAM_LIFETIME)) {
lifetime = Long.valueOf(param.substring(3));
} else if (param.startsWith(QUERY_PARAM_SMS)) {
smsNumber = param.substring(4);
} else if (param.startsWith(QUERY_PARAM_BINDING_MODE)) {
binding = BindingMode.valueOf(param.substring(2));
}
}
if (request.getPayload() != null && request.getPayload().length > 0) {
objectLinks = Link.parse(request.getPayload());
}
UpdateRequest updateRequest = new UpdateRequest(registrationId, lifetime, smsNumber, binding, objectLinks);
// Handle request
final SendableResponse<UpdateResponse> sendableResponse = registrationHandler.update(sender, updateRequest);
UpdateResponse updateResponse = sendableResponse.getResponse();
// Create CoAP Response from LwM2m request
exchange.respond(fromLwM2mCode(updateResponse.getCode()), updateResponse.getErrorMessage());
sendableResponse.sent();
} | #vulnerable code
private void handleUpdate(CoapExchange exchange, Request request, String registrationId) {
// Get identity
Identity sender = extractIdentity(exchange);
// Create LwM2m request from CoAP request
Long lifetime = null;
String smsNumber = null;
BindingMode binding = null;
Link[] objectLinks = null;
for (String param : request.getOptions().getUriQuery()) {
if (param.startsWith(QUERY_PARAM_LIFETIME)) {
lifetime = Long.valueOf(param.substring(3));
} else if (param.startsWith(QUERY_PARAM_SMS)) {
smsNumber = param.substring(4);
} else if (param.startsWith(QUERY_PARAM_BINDING_MODE)) {
binding = BindingMode.valueOf(param.substring(2));
}
}
if (request.getPayload() != null && request.getPayload().length > 0) {
objectLinks = Link.parse(request.getPayload());
}
UpdateRequest updateRequest = new UpdateRequest(registrationId, lifetime, smsNumber, binding, objectLinks);
// Handle request
UpdateResponse updateResponse = registrationHandler.update(sender, updateRequest);
// Create CoAP Response from LwM2m request
exchange.respond(fromLwM2mCode(updateResponse.getCode()), updateResponse.getErrorMessage());
}
#location 25
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void beginTransaction() {
transactionalListener.beginTransaction();
} | #vulnerable code
protected void beginTransaction() {
if (listener != null) {
listener.beginTransaction();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void createRPKClient() {
createRPKClient(false);
} | #vulnerable code
public void createRPKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.rpk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, clientPublicKey.getEncoded(), clientPrivateKey.getEncoded(),
serverPublicKey.getEncoded()));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
// TODO no way to provide a dynamic config with the current scandium API
config.setIdentity(clientPrivateKey, clientPublicKey);
CoapServer coapServer = new CoapServer();
CoapEndpoint.CoapEndpointBuilder coapBuilder = new CoapEndpoint.CoapEndpointBuilder();
coapBuilder.setConnector(new DTLSConnector(config.build()));
coapBuilder.setNetworkConfig(new NetworkConfig());
coapServer.addEndpoint(coapBuilder.build());
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
setupClientMonitoring();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void createClient() {
// Create Security Object (with bootstrap server only)
String bsUrl = "coap://" + bootstrapServer.getUnsecuredAddress().getHostString() + ":"
+ bootstrapServer.getUnsecuredAddress().getPort();
Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345);
createClient(security);
} | #vulnerable code
@Override
public void createClient() {
// Create Security Object (with bootstrap server only)
String bsUrl = "coap://" + bootstrapServer.getNonSecureAddress().getHostString() + ":"
+ bootstrapServer.getNonSecureAddress().getPort();
Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345);
createClient(security);
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void fireInstancesAdded(int... instanceIds) {
transactionalListener.objectInstancesAdded(this, instanceIds);
} | #vulnerable code
protected void fireInstancesAdded(int... instanceIds) {
if (listener != null) {
listener.objectInstancesAdded(this, instanceIds);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Registration deserialize(JsonObject jObj) {
Registration.Builder b = new Registration.Builder(jObj.getString("regId", null), jObj.getString("ep", null),
IdentitySerDes.deserialize(jObj.get("identity").asObject()),
new InetSocketAddress(jObj.getString("regAddr", null), jObj.getInt("regPort", 0)));
b.bindingMode(BindingMode.valueOf(jObj.getString("bnd", null)));
b.lastUpdate(new Date(jObj.getLong("lastUp", 0)));
b.lifeTimeInSec(jObj.getLong("lt", 0));
b.lwM2mVersion(jObj.getString("ver", "1.0"));
b.registrationDate(new Date(jObj.getLong("regDate", 0)));
if (jObj.get("sms") != null) {
b.smsNumber(jObj.getString("sms", ""));
}
JsonArray links = (JsonArray) jObj.get("objLink");
Link[] linkObjs = new Link[links.size()];
for (int i = 0; i < links.size(); i++) {
JsonObject ol = (JsonObject) links.get(i);
Map<String, Object> attMap = new HashMap<>();
JsonObject att = (JsonObject) ol.get("at");
for (String k : att.names()) {
JsonValue jsonValue = att.get(k);
if (jsonValue.isNumber()) {
attMap.put(k, jsonValue.asInt());
} else {
attMap.put(k, jsonValue.asString());
}
}
Link o = new Link(ol.getString("url", null), attMap);
linkObjs[i] = o;
}
b.objectLinks(linkObjs);
Map<String, String> addAttr = new HashMap<>();
JsonObject o = (JsonObject) jObj.get("addAttr");
for (String k : o.names()) {
addAttr.put(k, o.getString(k, ""));
}
b.additionalRegistrationAttributes(addAttr);
return b.build();
} | #vulnerable code
public static Registration deserialize(JsonObject jObj) {
Registration.Builder b = new Registration.Builder(jObj.getString("regId", null), jObj.getString("ep", null),
new InetSocketAddress(jObj.getString("address", null), jObj.getInt("port", 0)).getAddress(),
jObj.getInt("port", 0),
new InetSocketAddress(jObj.getString("regAddr", null), jObj.getInt("regPort", 0)));
b.bindingMode(BindingMode.valueOf(jObj.getString("bnd", null)));
b.lastUpdate(new Date(jObj.getLong("lastUp", 0)));
b.lifeTimeInSec(jObj.getLong("lt", 0));
b.lwM2mVersion(jObj.getString("ver", "1.0"));
b.registrationDate(new Date(jObj.getLong("regDate", 0)));
if (jObj.get("sms") != null) {
b.smsNumber(jObj.getString("sms", ""));
}
JsonArray links = (JsonArray) jObj.get("objLink");
Link[] linkObjs = new Link[links.size()];
for (int i = 0; i < links.size(); i++) {
JsonObject ol = (JsonObject) links.get(i);
Map<String, Object> attMap = new HashMap<>();
JsonObject att = (JsonObject) ol.get("at");
for (String k : att.names()) {
JsonValue jsonValue = att.get(k);
if (jsonValue.isNumber()) {
attMap.put(k, jsonValue.asInt());
} else {
attMap.put(k, jsonValue.asString());
}
}
Link o = new Link(ol.getString("url", null), attMap);
linkObjs[i] = o;
}
b.objectLinks(linkObjs);
Map<String, String> addAttr = new HashMap<>();
JsonObject o = (JsonObject) jObj.get("addAttr");
for (String k : o.names()) {
addAttr.put(k, o.getString(k, ""));
}
b.additionalRegistrationAttributes(addAttr);
return b.build();
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void sendNotification(byte[] payload, Response firstCoapResponse, int contentFormat) {
// encode and send it
try (DatagramSocket clientSocket = new DatagramSocket()) {
// create observe response
Response response = new Response(org.eclipse.californium.core.coap.CoAP.ResponseCode.CONTENT);
response.setType(Type.NON);
response.setPayload(payload);
response.setMID(firstCoapResponse.getMID() + 1);
response.setToken(firstCoapResponse.getToken());
OptionSet options = new OptionSet().setContentFormat(contentFormat)
.setObserve(firstCoapResponse.getOptions().getObserve() + 1);
response.setOptions(options);
// serialize response
UdpDataSerializer serializer = new UdpDataSerializer();
RawData data = serializer.serializeResponse(response);
// send it
clientSocket.send(new DatagramPacket(data.bytes, data.bytes.length,
helper.server.getUnsecuredAddress().getAddress(), helper.server.getUnsecuredAddress().getPort()));
} catch (IOException e) {
throw new AssertionError("Error while timestamped notification", e);
}
} | #vulnerable code
private void sendNotification(byte[] payload, Response firstCoapResponse, int contentFormat) {
// encode and send it
try (DatagramSocket clientSocket = new DatagramSocket()) {
// create observe response
Response response = new Response(org.eclipse.californium.core.coap.CoAP.ResponseCode.CONTENT);
response.setType(Type.NON);
response.setPayload(payload);
response.setMID(firstCoapResponse.getMID() + 1);
response.setToken(firstCoapResponse.getToken());
OptionSet options = new OptionSet().setContentFormat(contentFormat)
.setObserve(firstCoapResponse.getOptions().getObserve() + 1);
response.setOptions(options);
// serialize response
UdpDataSerializer serializer = new UdpDataSerializer();
RawData data = serializer.serializeResponse(response);
// send it
clientSocket.send(new DatagramPacket(data.bytes, data.bytes.length,
helper.server.getNonSecureAddress().getAddress(), helper.server.getNonSecureAddress().getPort()));
} catch (IOException e) {
throw new AssertionError("Error while timestamped notification", e);
}
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void fireInstancesRemoved(int... instanceIds) {
transactionalListener.objectInstancesRemoved(this, instanceIds);
} | #vulnerable code
protected void fireInstancesRemoved(int... instanceIds) {
if (listener != null) {
listener.objectInstancesRemoved(this, instanceIds);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void createPSKClient() {
createPSKClient(false);
} | #vulnerable code
public void createPSKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.psk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
initializer.setDummyInstancesForObject(LwM2mId.ACCESS_CONTROL);
List<LwM2mObjectEnabler> objects = initializer.createAll();
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
// set an editable PSK store for tests
builder.setEndpointFactory(new EndpointFactory() {
@Override
public CoapEndpoint createUnsecuredEndpoint(InetSocketAddress address, NetworkConfig coapConfig,
ObservationStore store) {
CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
builder.setInetSocketAddress(address);
builder.setNetworkConfig(coapConfig);
return builder.build();
}
@Override
public CoapEndpoint createSecuredEndpoint(DtlsConnectorConfig dtlsConfig, NetworkConfig coapConfig,
ObservationStore store) {
CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
Builder dtlsConfigBuilder = new Builder(dtlsConfig);
if (dtlsConfig.getPskStore() != null) {
PskPublicInformation identity = dtlsConfig.getPskStore().getIdentity(null);
SecretKey key = dtlsConfig.getPskStore().getKey(identity);
singlePSKStore = new SinglePSKStore(identity, key);
dtlsConfigBuilder.setPskStore(singlePSKStore);
}
builder.setConnector(new DTLSConnector(dtlsConfigBuilder.build()));
builder.setNetworkConfig(coapConfig);
return builder.build();
}
});
// create client;
client = builder.build();
setupClientMonitoring();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void can_observe_timestamped_resource() throws InterruptedException {
TestObservationListener listener = new TestObservationListener();
helper.server.getObservationService().addListener(listener);
// observe device timezone
ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(),
new ObserveRequest(3, 0, 15));
assertEquals(ResponseCode.CONTENT, observeResponse.getCode());
assertNotNull(observeResponse.getCoapResponse());
assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class)));
// an observation response should have been sent
Observation observation = observeResponse.getObservation();
assertEquals("/3/0/15", observation.getPath().toString());
assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId());
// *** HACK send time-stamped notification as Leshan client does not support it *** //
// create time-stamped nodes
TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(),
LwM2mSingleResource.newStringResource(15, "Paris"));
List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>();
timestampedNodes.add(mostRecentNode);
timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2,
LwM2mSingleResource.newStringResource(15, "Londres")));
byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3/0/15"),
new LwM2mModel(helper.createObjectModels()), new DefaultLwM2mValueConverter());
Response firstCoapResponse = (Response) observeResponse.getCoapResponse();
sendNotification(payload, firstCoapResponse, ContentFormat.JSON_CODE);
// *** Hack End *** //
// verify result
listener.waitForNotification(2000);
assertTrue(listener.receivedNotify().get());
assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent());
assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode());
assertNotNull(listener.getResponse().getCoapResponse());
assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class)));
} | #vulnerable code
@Test
public void can_observe_timestamped_resource() throws InterruptedException {
TestObservationListener listener = new TestObservationListener();
helper.server.getObservationService().addListener(listener);
// observe device timezone
ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(),
new ObserveRequest(3, 0, 15));
assertEquals(ResponseCode.CONTENT, observeResponse.getCode());
assertNotNull(observeResponse.getCoapResponse());
assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class)));
// an observation response should have been sent
Observation observation = observeResponse.getObservation();
assertEquals("/3/0/15", observation.getPath().toString());
assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId());
// *** HACK send time-stamped notification as Leshan client does not support it *** //
// create time-stamped nodes
TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(),
LwM2mSingleResource.newStringResource(15, "Paris"));
List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>();
timestampedNodes.add(mostRecentNode);
timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2,
LwM2mSingleResource.newStringResource(15, "Londres")));
byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3/0/15"),
new LwM2mModel(helper.createObjectModels()));
Response firstCoapResponse = (Response) observeResponse.getCoapResponse();
sendNotification(payload, firstCoapResponse, ContentFormat.JSON_CODE);
// *** Hack End *** //
// verify result
listener.waitForNotification(2000);
assertTrue(listener.receivedNotify().get());
assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent());
assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode());
assertNotNull(listener.getResponse().getCoapResponse());
assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class)));
}
#location 35
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
Map<Integer, LwM2mObjectInstance> instances = new HashMap<>(tlvs.length);
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException("Object instance TLV is mandatory for multiple instances object [path:%s]",
path);
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path);
LwM2mObjectInstance objectInstance = parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model);
LwM2mObjectInstance previousObjectInstance = instances.put(objectInstance.getId(), objectInstance);
if (previousObjectInstance != null) {
throw new CodecException(
"2 OBJECT_INSTANCE nodes (%s,%s) with the same identifier %d for path %s",
previousObjectInstance, objectInstance, objectInstance.getId(), path);
}
}
}
return (T) new LwM2mObject(path.getObjectId(), instances.values());
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException("Id conflict between path [%s] and instance TLV [object instance id=%d]",
path, tlvs[0].getIdentifier());
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
// The object instance level should not be here, but if it is provided and consistent we tolerate it
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException("Id conflict between path [%s] and instance TLV [object instance id=%d]",
path, tlvs[0].getIdentifier());
}
tlvs = tlvs[0].getChildren();
}
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException("TLV payload is mandatory for single resource %s", path);
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
Tlv tlv = tlvs[0];
if (tlv.getType() != TlvType.RESOURCE_VALUE && tlv.getType() != TlvType.MULTIPLE_RESOURCE) {
throw new CodecException(
"Expected TLV of type RESOURCE_VALUE or MUlTIPLE_RESOURCE but was %s [path:%s]",
tlv.getType().name(), path);
}
if (path.isResource() && path.getResourceId() != tlv.getIdentifier()) {
throw new CodecException("Id conflict between path [%s] and resource TLV [resource id=%s]", path,
tlv.getIdentifier());
}
return (T) parseResourceTlv(tlv, path, model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
} | #vulnerable code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
Map<Integer, LwM2mObjectInstance> instances = new HashMap<>(tlvs.length);
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException("Object instance TLV is mandatory for multiple instances object [path:%s]",
path);
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path);
LwM2mObjectInstance objectInstance = parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model);
LwM2mObjectInstance previousObjectInstance = instances.put(objectInstance.getId(), objectInstance);
if (previousObjectInstance != null) {
throw new CodecException(
"2 OBJECT_INSTANCE nodes (%s,%s) with the same identifier %d for path %s",
previousObjectInstance, objectInstance, objectInstance.getId(), path);
}
}
}
return (T) new LwM2mObject(path.getObjectId(), instances.values());
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier());
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException("TLV payload is mandatory for single resource %s", path);
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier());
}
LwM2mPath resourcePath = new LwM2mPath(path.getObjectId(), path.getObjectInstanceId(),
tlvs[0].getIdentifier());
return (T) parseResourceTlv(tlvs[0], resourcePath, model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
#location 86
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void createPSKClient(String pskIdentity, byte[] pskKey) {
// Create Security Object (with bootstrap server only)
String bsUrl = "coaps://" + bootstrapServer.getSecuredAddress().getHostString() + ":"
+ bootstrapServer.getSecuredAddress().getPort();
byte[] pskId = pskIdentity.getBytes(StandardCharsets.UTF_8);
Security security = Security.pskBootstrap(bsUrl, pskId, pskKey);
createClient(security);
} | #vulnerable code
public void createPSKClient(String pskIdentity, byte[] pskKey) {
// Create Security Object (with bootstrap server only)
String bsUrl = "coaps://" + bootstrapServer.getSecureAddress().getHostString() + ":"
+ bootstrapServer.getSecureAddress().getPort();
byte[] pskId = pskIdentity.getBytes(StandardCharsets.UTF_8);
Security security = Security.pskBootstrap(bsUrl, pskId, pskKey);
createClient(security);
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void createClient() {
// Create objects Enabler
ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels()));
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coap://" + server.getUnsecuredAddress().getHostString() + ":" + server.getUnsecuredAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") {
@Override
public ExecuteResponse execute(int resourceid, String params) {
if (resourceid == 4) {
return ExecuteResponse.success();
} else {
return super.execute(resourceid, params);
}
}
});
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.addAll(initializer.create(2, 2000));
// Build Client
LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get());
builder.setObjects(objects);
client = builder.build();
} | #vulnerable code
public void createClient() {
// Create objects Enabler
ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels()));
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coap://" + server.getNonSecureAddress().getHostString() + ":" + server.getNonSecureAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") {
@Override
public ExecuteResponse execute(int resourceid, String params) {
if (resourceid == 4) {
return ExecuteResponse.success();
} else {
return super.execute(resourceid, params);
}
}
});
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.addAll(initializer.create(2, 2000));
// Build Client
LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static boolean checkRpkIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) {
// Manage RPK authentication
// ----------------------------------------------------
PublicKey publicKey = clientIdentity.getRawPublicKey();
if (publicKey == null || !publicKey.equals(securityInfo.getRawPublicKey())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Invalid rpk for client {}: expected \n'{}'\n but was \n'{}'", endpoint,
Hex.encodeHexString(securityInfo.getRawPublicKey().getEncoded()),
publicKey != null ? Hex.encodeHexString(publicKey.getEncoded()) : "null");
}
return false;
} else {
LOG.trace("authenticated client '{}' using DTLS RPK", endpoint);
return true;
}
} | #vulnerable code
private static boolean checkRpkIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) {
// Manage RPK authentication
// ----------------------------------------------------
PublicKey publicKey = clientIdentity.getRawPublicKey();
if (publicKey == null || !publicKey.equals(securityInfo.getRawPublicKey())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Invalid rpk for client {}: expected \n'{}'\n but was \n'{}'", endpoint,
Hex.encodeHexString(securityInfo.getRawPublicKey().getEncoded()),
Hex.encodeHexString(publicKey.getEncoded()));
}
return false;
} else {
LOG.trace("authenticated client '{}' using DTLS RPK", endpoint);
return true;
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static byte[] encodeInteger(Number number) {
ByteBuffer iBuf = null;
long lValue = number.longValue();
if (lValue >= Byte.MIN_VALUE && lValue <= Byte.MAX_VALUE) {
iBuf = ByteBuffer.allocate(1);
iBuf.put((byte) lValue);
} else if (lValue >= Short.MIN_VALUE && lValue <= Short.MAX_VALUE) {
iBuf = ByteBuffer.allocate(2);
iBuf.putShort((short) lValue);
} else if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) {
iBuf = ByteBuffer.allocate(4);
iBuf.putInt((int) lValue);
} else {
iBuf = ByteBuffer.allocate(8);
iBuf.putLong(lValue);
}
return iBuf.array();
} | #vulnerable code
public static byte[] encodeInteger(Number number) {
ByteBuffer iBuf = null;
long longValue = number.longValue();
if (longValue == Long.MIN_VALUE) {
throw new IllegalArgumentException(
"Could not encode Long.MIN_VALUE, because of signed magnitude representation.");
}
long positiveValue = longValue < 0 ? -longValue : longValue;
if (positiveValue <= Byte.MAX_VALUE) {
iBuf = ByteBuffer.allocate(1);
iBuf.put((byte) positiveValue);
} else if (positiveValue <= Short.MAX_VALUE) {
iBuf = ByteBuffer.allocate(2);
iBuf.putShort((short) positiveValue);
} else if (positiveValue <= Integer.MAX_VALUE) {
iBuf = ByteBuffer.allocate(4);
iBuf.putInt((int) positiveValue);
} else if (positiveValue <= Long.MAX_VALUE) {
iBuf = ByteBuffer.allocate(8);
iBuf.putLong(positiveValue);
}
byte[] bytes = iBuf.array();
// set the most significant bit to 1 if negative value
if (number.longValue() < 0) {
bytes[0] |= 0b1000_0000;
}
return bytes;
}
#location 25
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void endTransaction() {
transactionalListener.endTransaction();
} | #vulnerable code
protected void endTransaction() {
if (listener != null) {
listener.endTransaction();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object findInList(final Object current, final Method m, Node mapEq, String map)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
if (m.getParameterTypes().length != 1 && m.getParameterTypes()[0] != int.class) {
fail("Unable to navigate " + current.getClass().getCanonicalName() + " with method "
+ m.getName());
}
Method countM = GwtReflectionUtils.getMethod(current.getClass(), m.getName() + "Count");
if (countM == null) {
fail("Count method not found in " + current.getClass().getCanonicalName() + " method "
+ m.getName());
return null;
}
if (countM.getParameterTypes().length > 0) {
fail("Too many parameter in count method " + current.getClass().getCanonicalName()
+ " method " + countM.getName());
}
logger.debug("Searching in list, field " + mapEq + ", value " + map);
final int count = (Integer) countM.invoke(current);
return findInIterable(new Iterable<Object>() {
public Iterator<Object> iterator() {
return new Iterator<Object>() {
int counter = 0;
public boolean hasNext() {
return counter < count;
}
public Object next() {
try {
return m.invoke(current, counter++);
} catch (Exception e) {
throw new GwtTestCsvException("Iterator exception", e);
}
}
public void remove() {
throw new UnsupportedOperationException("Remove not implemented");
}
};
}
}, mapEq, map, current, m);
} | #vulnerable code
private Object findInList(final Object current, final Method m, Node mapEq, String map)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
if (m.getParameterTypes().length != 1 && m.getParameterTypes()[0] != int.class) {
fail("Unable to navigate " + current.getClass().getCanonicalName() + " with method "
+ m.getName());
}
Method countM = GwtReflectionUtils.getMethod(current.getClass(), m.getName() + "Count");
if (countM == null) {
fail("Count method not found in " + current.getClass().getCanonicalName() + " method "
+ m.getName());
}
if (countM.getParameterTypes().length > 0) {
fail("Too many parameter in count method " + current.getClass().getCanonicalName()
+ " method " + countM.getName());
}
logger.debug("Searching in list, field " + mapEq + ", value " + map);
final int count = (Integer) countM.invoke(current);
return findInIterable(new Iterable<Object>() {
public Iterator<Object> iterator() {
return new Iterator<Object>() {
int counter = 0;
public boolean hasNext() {
return counter < count;
}
public Object next() {
try {
return m.invoke(current, counter++);
} catch (Exception e) {
throw new GwtTestCsvException("Iterator exception", e);
}
}
public void remove() {
throw new UnsupportedOperationException("Remove not implemented");
}
};
}
}, mapEq, map, current, m);
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void initCsvTests(CsvDirectory csvDirectory) throws FileNotFoundException, IOException {
File testsRoot = getDirectory(csvDirectory.value());
String extension = csvDirectory.extension();
testMethods = new ArrayList<Method>();
tests = new HashMap<String, List<List<String>>>();
collectCsvTests(testsRoot, extension, tests);
} | #vulnerable code
private void initCsvTests(CsvDirectory csvDirectory) throws FileNotFoundException, IOException {
File directory = getDirectory(csvDirectory.value());
testMethods = new ArrayList<Method>();
tests = new HashMap<String, List<List<String>>>();
for (File f : directory.listFiles()) {
if (f.getName().endsWith(csvDirectory.extension())) {
tests.put(f.getAbsolutePath(), CsvReader.readCsv(new FileReader(f)));
}
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void close () {
super.close();
synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection.
}
// Select one last time to complete closing the socket.
if (!isClosed) {
isClosed = true;
selector.wakeup();
try {
selector.selectNow();
} catch (IOException ignored) {
}
}
} | #vulnerable code
public void close () {
super.close();
// Select one last time to complete closing the socket.
synchronized (updateLock) {
if (!isClosed) {
isClosed = true;
selector.wakeup();
try {
selector.selectNow();
} catch (IOException ignored) {
}
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
int read;
do
{
read = in.read(buffer, 0, buffer.length);
if (read > 0)
{
out.append(buffer, 0, read);
}
}
while (read >= 0);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return out.toString();
} | #vulnerable code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, "UTF-8");
int read;
do
{
read = in.read(buffer, 0, buffer.length);
if (read > 0)
{
out.append(buffer, 0, read);
}
}
while (read >= 0);
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return out.toString();
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Field<O> setLiteralInitializer(final String value)
{
String stub = "public class Stub { private String stub = " + value + " }";
JavaClass temp = (JavaClass) JavaParser.parse(stub);
VariableDeclarationFragment tempFrag = (VariableDeclarationFragment) temp.getFields().get(0).getInternal();
fragment.setInitializer((Expression) ASTNode.copySubtree(ast, tempFrag.getInitializer()));
return this;
} | #vulnerable code
@Override
public Field<O> setLiteralInitializer(final String value)
{
String stub = "public class Stub { private String stub = " + value + " }";
JavaClass temp = (JavaClass) JavaParser.parse(stub);
FieldDeclaration internal = (FieldDeclaration) temp.getFields().get(0).getInternal();
for (Object f : internal.fragments())
{
if (f instanceof VariableDeclarationFragment)
{
VariableDeclarationFragment tempFrag = (VariableDeclarationFragment) f;
VariableDeclarationFragment localFrag = getFragment(field);
localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, tempFrag.getInitializer()));
break;
}
}
return this;
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
int read;
do
{
read = in.read(buffer, 0, buffer.length);
if (read > 0)
{
out.append(buffer, 0, read);
}
}
while (read >= 0);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return out.toString();
} | #vulnerable code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, "UTF-8");
int read;
do
{
read = in.read(buffer, 0, buffer.length);
if (read > 0)
{
out.append(buffer, 0, read);
}
}
while (read >= 0);
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return out.toString();
}
#location 27
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean isReturnTypeVoid()
{
return getReturnType() == null || getReturnType().isType(Void.TYPE);
} | #vulnerable code
@Override
public boolean isReturnTypeVoid()
{
return getReturnType().isType(Void.TYPE);
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Specification<T> combinedSpecs = null;
for (Specification<T> spec : innerSpecs) {
if (combinedSpecs == null) {
combinedSpecs = Specification.where(spec);
} else {
combinedSpecs = combinedSpecs.or(spec);
}
}
return combinedSpecs.toPredicate(root, query, cb);
} | #vulnerable code
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Specifications<T> combinedSpecs = null;
for (Specification<T> spec : innerSpecs) {
if (combinedSpecs == null) {
combinedSpecs = Specifications.where(spec);
} else {
combinedSpecs = combinedSpecs.or(spec);
}
}
return combinedSpecs.toPredicate(root, query, cb);
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Bean(name = KAFKA_BEAN_NAME, destroyMethod = "stop")
@DependsOn("zookeeper")
public GenericContainer kafka(
KafkaStatusCheck kafkaStatusCheck,
KafkaConfigurationProperties kafkaProperties,
@Value("${embedded.zookeeper.containerZookeeperConnect}") String containerZookeeperConnect,
ConfigurableEnvironment environment,
Network network) {
int kafkaInternalPort = kafkaProperties.getContainerBrokerPort(); // for access from other containers
int kafkaExternalPort = kafkaProperties.getBrokerPort(); // for access from host
int saslPlaintextKafkaExternalPort = kafkaProperties.getSaslPlaintextBrokerPort();
// https://docs.confluent.io/current/installation/docker/docs/configuration.html search by KAFKA_ADVERTISED_LISTENERS
String dockerImageVersion = kafkaProperties.getDockerImageVersion();
log.info("Starting kafka broker. Docker image version: {}", dockerImageVersion);
KafkaContainer kafka = new KafkaContainer(dockerImageVersion)
{
@Override
public String getBootstrapServers() {
super.getBootstrapServers();
return "EXTERNAL_PLAINTEXT://" + getHost() + ":" + getMappedPort(kafkaExternalPort) + "," +
"EXTERNAL_SASL_PLAINTEXT://" + getHost() + ":" + getMappedPort(saslPlaintextKafkaExternalPort) + "," +
"INTERNAL_PLAINTEXT://" + KAFKA_HOST_NAME + ":" + kafkaInternalPort;
}
}
.withLogConsumer(containerLogsConsumer(log))
.withCreateContainerCmdModifier(cmd -> cmd.withHostName(KAFKA_HOST_NAME))
.withCreateContainerCmdModifier(cmd -> cmd.withCapAdd(Capability.NET_ADMIN))
.withExternalZookeeper(containerZookeeperConnect)
.withEnv("KAFKA_BROKER_ID", "-1")
//see: https://stackoverflow.com/questions/41868161/kafka-in-kubernetes-cluster-how-to-publish-consume-messages-from-outside-of-kub
//see: https://github.com/wurstmeister/kafka-docker/blob/master/README.md
// order matters: external then internal since kafka.client.ClientUtils.getPlaintextBrokerEndPoints take first for simple consumers
.withEnv("KAFKA_LISTENER_SECURITY_PROTOCOL_MAP",
"EXTERNAL_PLAINTEXT:PLAINTEXT," +
"EXTERNAL_SASL_PLAINTEXT:SASL_PLAINTEXT," +
"INTERNAL_PLAINTEXT:PLAINTEXT," +
"BROKER:PLAINTEXT"
)
.withEnv("KAFKA_LISTENERS",
"EXTERNAL_PLAINTEXT://0.0.0.0:" + kafkaExternalPort + "," +
"EXTERNAL_SASL_PLAINTEXT://0.0.0.0:" + saslPlaintextKafkaExternalPort + "," +
"INTERNAL_PLAINTEXT://0.0.0.0:" + kafkaInternalPort + "," +
"BROKER://0.0.0.0:9092"
)
.withEnv("KAFKA_INTER_BROKER_LISTENER_NAME", "INTERNAL_PLAINTEXT")
.withEnv("KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS", "1")
.withEnv("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", String.valueOf(kafkaProperties.getReplicationFactor()))
.withEnv("KAFKA_TRANSACTION_STATE_LOG_MIN_ISR", "1")
.withEnv("KAFKA_CONFLUENT_SUPPORT_METRICS_ENABLE", "false")
.withEnv("KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR", "1")
.withEnv("KAFKA_LOG_FLUSH_INTERVAL_MS", String.valueOf(kafkaProperties.getLogFlushIntervalMs()))
.withEnv("KAFKA_REPLICA_SOCKET_TIMEOUT_MS", String.valueOf(kafkaProperties.getReplicaSocketTimeoutMs()))
.withEnv("KAFKA_CONTROLLER_SOCKET_TIMEOUT_MS", String.valueOf(kafkaProperties.getControllerSocketTimeoutMs()))
.withEnv("KAFKA_SASL_ENABLED_MECHANISMS", "PLAIN")
.withEnv("ZOOKEEPER_SASL_ENABLED", "false")
.withCopyFileToContainer(MountableFile.forClasspathResource("kafka_server_jaas.conf"), "/etc/kafka/kafka_server_jaas.conf")
.withEnv("KAFKA_OPTS", "-Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf")
.withExposedPorts(kafkaInternalPort, kafkaExternalPort, saslPlaintextKafkaExternalPort, KAFKA_PORT)
.withNetwork(network)
.withNetworkAliases(KAFKA_HOST_NAME)
.withExtraHost(KAFKA_HOST_NAME, "127.0.0.1")
.waitingFor(kafkaStatusCheck)
.withStartupTimeout(kafkaProperties.getTimeoutDuration());
KafkaConfigurationProperties.FileSystemBind fileSystemBind = kafkaProperties.getFileSystemBind();
if (fileSystemBind.isEnabled()) {
String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH-mm-ss-nnnnnnnnn"));
String dataFolder = fileSystemBind.getDataFolder();
String kafkaData = Paths.get(dataFolder, currentTimestamp).toAbsolutePath().toString();
log.info("Writing kafka data to: {}", kafkaData);
kafka.withFileSystemBind(kafkaData, "/var/lib/kafka/data", BindMode.READ_WRITE);
}
startAndLogTime(kafka);
registerKafkaEnvironment(kafka, environment, kafkaProperties);
return kafka;
} | #vulnerable code
@Bean(name = KAFKA_BEAN_NAME, destroyMethod = "stop")
@DependsOn("zookeeper")
public GenericContainer kafka(
KafkaStatusCheck kafkaStatusCheck,
KafkaConfigurationProperties kafkaProperties,
@Value("${embedded.zookeeper.containerZookeeperConnect}") String containerZookeeperConnect,
ConfigurableEnvironment environment,
Network network) {
int kafkaInternalPort = kafkaProperties.getContainerBrokerPort(); // for access from other containers
int kafkaExternalPort = kafkaProperties.getBrokerPort(); // for access from host
int saslPlaintextKafkaExternalPort = kafkaProperties.getSaslPlaintextBrokerPort();
// https://docs.confluent.io/current/installation/docker/docs/configuration.html search by KAFKA_ADVERTISED_LISTENERS
log.info("Starting kafka broker. Docker image: {}", kafkaProperties.getDockerImage());
GenericContainer kafka = new FixedHostPortGenericContainer<>(kafkaProperties.getDockerImage())
.withLogConsumer(containerLogsConsumer(log))
.withCreateContainerCmdModifier(cmd -> cmd.withHostName(KAFKA_HOST_NAME))
.withCreateContainerCmdModifier(cmd -> cmd.withCapAdd(Capability.NET_ADMIN))
.withEnv("KAFKA_ZOOKEEPER_CONNECT", containerZookeeperConnect)
.withEnv("KAFKA_BROKER_ID", "-1")
//see: https://stackoverflow.com/questions/41868161/kafka-in-kubernetes-cluster-how-to-publish-consume-messages-from-outside-of-kub
//see: https://github.com/wurstmeister/kafka-docker/blob/master/README.md
// order matters: external then internal since kafka.client.ClientUtils.getPlaintextBrokerEndPoints take first for simple consumers
.withEnv("KAFKA_LISTENER_SECURITY_PROTOCOL_MAP",
"EXTERNAL_PLAINTEXT:PLAINTEXT," +
"EXTERNAL_SASL_PLAINTEXT:SASL_PLAINTEXT," +
"INTERNAL_PLAINTEXT:PLAINTEXT"
)
.withEnv("KAFKA_ADVERTISED_LISTENERS",
"EXTERNAL_PLAINTEXT://" + kafkaHost() + ":" + kafkaExternalPort + "," +
"EXTERNAL_SASL_PLAINTEXT://" + kafkaHost() + ":" + saslPlaintextKafkaExternalPort + "," +
"INTERNAL_PLAINTEXT://" + KAFKA_HOST_NAME + ":" + kafkaInternalPort
)
.withEnv("KAFKA_LISTENERS",
"EXTERNAL_PLAINTEXT://0.0.0.0:" + kafkaExternalPort + "," +
"EXTERNAL_SASL_PLAINTEXT://0.0.0.0:" + saslPlaintextKafkaExternalPort + "," +
"INTERNAL_PLAINTEXT://0.0.0.0:" + kafkaInternalPort
)
.withEnv("KAFKA_INTER_BROKER_LISTENER_NAME", "INTERNAL_PLAINTEXT")
.withEnv("KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS", "1")
.withEnv("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", String.valueOf(kafkaProperties.getReplicationFactor()))
.withEnv("KAFKA_TRANSACTION_STATE_LOG_MIN_ISR", "1")
.withEnv("KAFKA_CONFLUENT_SUPPORT_METRICS_ENABLE", "false")
.withEnv("KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR", "1")
.withEnv("KAFKA_LOG_FLUSH_INTERVAL_MS", String.valueOf(kafkaProperties.getLogFlushIntervalMs()))
.withEnv("KAFKA_REPLICA_SOCKET_TIMEOUT_MS", String.valueOf(kafkaProperties.getReplicaSocketTimeoutMs()))
.withEnv("KAFKA_CONTROLLER_SOCKET_TIMEOUT_MS", String.valueOf(kafkaProperties.getControllerSocketTimeoutMs()))
.withEnv("KAFKA_SASL_ENABLED_MECHANISMS", "PLAIN")
.withEnv("ZOOKEEPER_SASL_ENABLED", "false")
.withCopyFileToContainer(MountableFile.forClasspathResource("kafka_server_jaas.conf"), "/etc/kafka/kafka_server_jaas.conf")
.withEnv("KAFKA_OPTS", "-Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf")
.withExposedPorts(kafkaInternalPort, kafkaExternalPort, saslPlaintextKafkaExternalPort)
.withFixedExposedPort(kafkaInternalPort, kafkaInternalPort)
.withFixedExposedPort(kafkaExternalPort, kafkaExternalPort)
.withFixedExposedPort(saslPlaintextKafkaExternalPort, saslPlaintextKafkaExternalPort)
.withNetwork(network)
.withNetworkAliases(KAFKA_HOST_NAME)
.withExtraHost(KAFKA_HOST_NAME, "127.0.0.1")
.waitingFor(kafkaStatusCheck)
.withStartupTimeout(kafkaProperties.getTimeoutDuration());
KafkaConfigurationProperties.FileSystemBind fileSystemBind = kafkaProperties.getFileSystemBind();
if (fileSystemBind.isEnabled()) {
String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH-mm-ss-nnnnnnnnn"));
String dataFolder = fileSystemBind.getDataFolder();
String kafkaData = Paths.get(dataFolder, currentTimestamp).toAbsolutePath().toString();
log.info("Writing kafka data to: {}", kafkaData);
kafka.withFileSystemBind(kafkaData, "/var/lib/kafka/data", BindMode.READ_WRITE);
}
startAndLogTime(kafka);
registerKafkaEnvironment(kafka, environment, kafkaProperties);
return kafka;
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Bean(name = BEAN_NAME_EMBEDDED_SELENIUM, destroyMethod = "stop")
@ConditionalOnMissingBean
public BrowserWebDriverContainer selenium(
ConfigurableEnvironment environment,
SeleniumProperties properties,
MutableCapabilities capabilities
) {
String imageName = properties.getImageName();
BrowserWebDriverContainer container = isNotBlank(imageName)
? new BrowserWebDriverContainer<>(imageName)
: new BrowserWebDriverContainer<>();
container.withCapabilities(capabilities);
container.withRecordingFileFactory(getRecordingFileFactory());
File recordingDirOrNull = null;
if (properties.getVnc().getMode().convert() != BrowserWebDriverContainer.VncRecordingMode.SKIP) {
recordingDirOrNull = getOrCreateTempDir(properties.getVnc().getRecordingDir());
}
container.withRecordingMode(properties.getVnc().getMode().convert(), recordingDirOrNull);
log.info("Starting Selenium. Docker image: {}", container.getDockerImageName());
ContainerUtils.configureCommonsAndStart(container, properties, log);
Map<String, Object> seleniumEnv = registerSeleniumEnvironment(environment, container, properties.getVnc().getMode().convert(), recordingDirOrNull);
log.info("Started Selenium server. Connection details: {}", seleniumEnv);
return container;
} | #vulnerable code
@Bean(name = BEAN_NAME_EMBEDDED_SELENIUM, destroyMethod = "stop")
@ConditionalOnMissingBean
public BrowserWebDriverContainer selenium(
ConfigurableEnvironment environment,
SeleniumProperties properties,
MutableCapabilities capabilities
) {
BrowserWebDriverContainer container = new BrowserWebDriverContainer<>().withCapabilities(capabilities);
container.withRecordingFileFactory(getRecordingFileFactory());
File recordingDirOrNull = null;
if (properties.getVnc().getMode().convert() != BrowserWebDriverContainer.VncRecordingMode.SKIP) {
recordingDirOrNull = getOrCreateTempDir(properties.getVnc().getRecordingDir());
}
container.withRecordingMode(properties.getVnc().getMode().convert(), recordingDirOrNull);
log.info("Starting Selenium. Docker image: {}", container.getDockerImageName());
ContainerUtils.configureCommonsAndStart(container, properties, log);
Map<String, Object> seleniumEnv = registerSeleniumEnvironment(environment, container, properties.getVnc().getMode().convert(), recordingDirOrNull);
log.info("Started Selenium server. Connection details: {}", seleniumEnv);
return container;
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
protected void createBean(AbstractClassBean<?> bean, Set<AbstractBean<?, ?>> beans)
{
beans.add(bean);
manager.getResolver().addInjectionPoints(bean.getInjectionPoints());
for (AnnotatedMethod<Object> producerMethod : bean.getProducerMethods())
{
ProducerMethodBean<?> producerMethodBean = createProducerMethodBean(producerMethod, bean, manager);
beans.add(producerMethodBean);
manager.getResolver().addInjectionPoints(producerMethodBean.getInjectionPoints());
registerEvents(producerMethodBean.getInjectionPoints(), beans);
log.info("Web Bean: " + producerMethodBean);
}
for (AnnotatedField<Object> producerField : bean.getProducerFields())
{
ProducerFieldBean<?> producerFieldBean = createProducerFieldBean(producerField, bean, manager);
beans.add(producerFieldBean);
log.info("Web Bean: " + producerFieldBean);
}
for (AnnotatedMethod<Object> initializerMethod : bean.getInitializerMethods())
{
for (AnnotatedParameter<Object> parameter : initializerMethod.getAnnotatedParameters(Observable.class))
{
registerEvent(parameter, beans);
}
}
for (AnnotatedItem injectionPoint : bean.getInjectionPoints())
{
if ( injectionPoint.isAnnotationPresent(Observable.class) )
{
registerEvent(injectionPoint, beans);
}
if ( injectionPoint.isAnnotationPresent(Obtainable.class) )
{
InstanceBean<Object, Field> instanceBean = createInstanceBean(injectionPoint, manager);
beans.add(instanceBean);
log.info("Web Bean: " + instanceBean);
}
}
for (AnnotatedMethod<Object> observerMethod : bean.getObserverMethods())
{
ObserverImpl<?> observer = createObserver(observerMethod, bean, manager);
if (observerMethod.getAnnotatedParameters(Observes.class).size() == 1)
{
registerObserver(observer, observerMethod.getAnnotatedParameters(Observes.class).get(0).getType(), observerMethod.getAnnotatedParameters(Observes.class).get(0).getBindingTypesAsArray());
}
else
{
throw new DefinitionException("Observer method can only have one parameter annotated @Observes " + observer);
}
}
log.info("Web Bean: " + bean);
} | #vulnerable code
@SuppressWarnings("unchecked")
protected void createBean(AbstractClassBean<?> bean, Set<AbstractBean<?, ?>> beans)
{
beans.add(bean);
manager.getResolver().addInjectionPoints(bean.getInjectionPoints());
for (AnnotatedMethod<Object> producerMethod : bean.getProducerMethods())
{
ProducerMethodBean<?> producerMethodBean = createProducerMethodBean(producerMethod, bean, manager);
beans.add(producerMethodBean);
manager.getResolver().addInjectionPoints(producerMethodBean.getInjectionPoints());
for (AnnotatedItem injectionPoint : producerMethodBean.getInjectionPoints())
{
if ( injectionPoint.isAnnotationPresent(Observable.class) )
{
EventBean<Object, Method> eventBean = createEventBean(injectionPoint, manager);
beans.add(eventBean);
log.info("Web Bean: " + eventBean);
}
}
log.info("Web Bean: " + producerMethodBean);
}
for (AnnotatedField<Object> producerField : bean.getProducerFields())
{
ProducerFieldBean<?> producerFieldBean = createProducerFieldBean(producerField, bean, manager);
beans.add(producerFieldBean);
log.info("Web Bean: " + producerFieldBean);
}
for (AnnotatedItem injectionPoint : bean.getInjectionPoints())
{
if ( injectionPoint.isAnnotationPresent(Observable.class) )
{
EventBean<Object, Field> eventBean = createEventBean(injectionPoint, manager);
beans.add(eventBean);
log.info("Web Bean: " + eventBean);
}
if ( injectionPoint.isAnnotationPresent(Obtainable.class) )
{
InstanceBean<Object, Field> instanceBean = createInstanceBean(injectionPoint, manager);
beans.add(instanceBean);
log.info("Web Bean: " + instanceBean);
}
}
for (AnnotatedMethod<Object> observerMethod : bean.getObserverMethods())
{
ObserverImpl<?> observer = createObserver(observerMethod, bean, manager);
if (observerMethod.getAnnotatedParameters(Observes.class).size() == 1)
{
registerObserver(observer, observerMethod.getAnnotatedParameters(Observes.class).get(0).getType(), observerMethod.getAnnotatedParameters(Observes.class).get(0).getBindingTypesAsArray());
}
else
{
throw new DefinitionException("Observer method can only have one parameter annotated @Observes " + observer);
}
}
log.info("Web Bean: " + bean);
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void beginRequest(HttpServletRequest request) {
} | #vulnerable code
public static void beginRequest(HttpServletRequest request) {
ManagerImpl manager = (ManagerImpl) JNDI.lookup("manager");
SessionContext sessionContext = (SessionContext) manager.getContext(SessionScoped.class);
BeanMap sessionBeans = (BeanMap) request.getAttribute(SESSION_BEANMAP_KEY);
sessionContext.setBeans(sessionBeans);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String toString()
{
if (toString != null)
{
return toString;
}
toString = toDetailedString();
return toString;
} | #vulnerable code
@Override
public String toString()
{
if (toString != null)
{
return toString;
}
toString = "Annotated parameter " + Names.type2String(getDelegate().getClass());
return toString;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("Manager\n");
buffer.append("Enabled deployment types: " + getEnabledDeploymentTypes() + "\n");
buffer.append("Registered contexts: " + contextMap.keySet() + "\n");
buffer.append("Registered beans: " + getBeans().size() + "\n");
buffer.append("Registered decorators: " + decorators.size() + "\n");
buffer.append("Registered interceptors: " + interceptors.size() + "\n");
return buffer.toString();
} | #vulnerable code
@Override
public String toString()
{
StringBuilder buffer = new StringBuilder();
buffer.append(Strings.collectionToString("Enabled deployment types: ", getEnabledDeploymentTypes()));
buffer.append(eventManager.toString() + "\n");
buffer.append(MetaDataCache.instance().toString() + "\n");
buffer.append(resolver.toString() + "\n");
buffer.append(contextMap.toString() + "\n");
buffer.append(proxyPool.toString() + "\n");
buffer.append(Strings.collectionToString("Registered beans: ", getBeans()));
buffer.append(Strings.collectionToString("Registered decorators: ", decorators));
buffer.append(Strings.collectionToString("Registered interceptors: ", interceptors));
return buffer.toString();
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public final boolean isWebElementSufficientlyShown(WebElement webElement){
final WebView webView = viewFetcher.getFreshestView(viewFetcher.getCurrentViews(WebView.class));
final int[] xyWebView = new int[2];
if(webView != null && webElement != null){
webView.getLocationOnScreen(xyWebView);
if(xyWebView[1] + webView.getHeight() > webElement.getLocationY())
return true;
}
return false;
} | #vulnerable code
public final boolean isWebElementSufficientlyShown(WebElement webElement){
final WebView webView = viewFetcher.getFreshestView(viewFetcher.getCurrentViews(WebView.class));
final int[] xyWebView = new int[2];
if(webElement != null){
webView.getLocationOnScreen(xyWebView);
if(xyWebView[1] + webView.getHeight() > webElement.getLocationY())
return true;
}
return false;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private View getViewOnListLine(AbsListView absListView, int lineIndex){
final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
View view = absListView.getChildAt(lineIndex);
while(view == null){
final boolean timedOut = SystemClock.uptimeMillis() > endTime;
if (timedOut){
Assert.fail("View is null and can therefore not be clicked!");
}
sleeper.sleep();
absListView = (AbsListView) viewFetcher.getIdenticalView(absListView);
if(absListView != null){
view = absListView.getChildAt(lineIndex);
}
}
return view;
} | #vulnerable code
private View getViewOnListLine(AbsListView absListView, int lineIndex){
final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
View view = absListView.getChildAt(lineIndex);
while(view == null){
final boolean timedOut = SystemClock.uptimeMillis() > endTime;
if (timedOut){
Assert.fail("View is null and can therefore not be clicked!");
}
sleeper.sleep();
absListView = (AbsListView) viewFetcher.getIdenticalView(absListView);
view = absListView.getChildAt(lineIndex);
}
return view;
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean scrollScrollView(int direction, ArrayList<ScrollView> scrollViews){
ScrollView scroll = viewFetcher.getView(ScrollView.class, scrollViews, 0);
if(scroll !=null){
int height = scroll.getHeight();
height--;
int scrollTo = 0;
if (direction == DOWN) {
scrollTo = (height);
}
else if (direction == UP) {
scrollTo = (-height);
}
scrollAmount = scroll.getScrollY();
scrollScrollViewTo(scroll,0, scrollTo);
if (scrollAmount == scroll.getScrollY()) {
return false;
}
else{
return true;
}
}
return false;
} | #vulnerable code
private boolean scrollScrollView(int direction, ArrayList<ScrollView> scrollViews){
ScrollView scroll = viewFetcher.getView(ScrollView.class, scrollViews, 0);
int height = scroll.getHeight();
height--;
int scrollTo = 0;
if (direction == DOWN) {
scrollTo = (height);
}
else if (direction == UP) {
scrollTo = (-height);
}
scrollAmount = scroll.getScrollY();
scrollScrollViewTo(scroll,0, scrollTo);
if (scrollAmount == scroll.getScrollY()) {
return false;
}
else{
return true;
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Bitmap getBitmapOfView(final View view){
view.destroyDrawingCache();
view.buildDrawingCache(false);
Bitmap orig = view.getDrawingCache();
Bitmap.Config config = null;
if(orig == null) {
return null;
}
config = orig.getConfig();
if(config == null) {
config = Bitmap.Config.ARGB_8888;
}
Bitmap b = orig.copy(config, false);
view.destroyDrawingCache();
return b;
} | #vulnerable code
private Bitmap getBitmapOfView(final View view){
view.destroyDrawingCache();
view.buildDrawingCache(false);
Bitmap orig = view.getDrawingCache();
Bitmap.Config config = null;
if(orig != null) {
config = orig.getConfig();
}
if(config == null) {
config = Bitmap.Config.ARGB_8888;
}
Bitmap b = orig.copy(config, false);
view.destroyDrawingCache();
return b;
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private View getViewOnRecyclerItemIndex(ViewGroup recyclerView, int recyclerViewIndex, int itemIndex){
final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
View view = recyclerView.getChildAt(itemIndex);
while(view == null){
final boolean timedOut = SystemClock.uptimeMillis() > endTime;
if (timedOut){
Assert.fail("View is null and can therefore not be clicked!");
}
sleeper.sleep();
recyclerView = (ViewGroup) viewFetcher.getIdenticalView(recyclerView);
if(recyclerView == null){
recyclerView = (ViewGroup) viewFetcher.getRecyclerView(false, recyclerViewIndex);
}
if(recyclerView != null){
view = recyclerView.getChildAt(itemIndex);
}
}
return view;
} | #vulnerable code
private View getViewOnRecyclerItemIndex(ViewGroup recyclerView, int recyclerViewIndex, int itemIndex){
final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
View view = recyclerView.getChildAt(itemIndex);
while(view == null){
final boolean timedOut = SystemClock.uptimeMillis() > endTime;
if (timedOut){
Assert.fail("View is null and can therefore not be clicked!");
}
sleeper.sleep();
recyclerView = (ViewGroup) viewFetcher.getIdenticalView(recyclerView);
if(recyclerView == null){
recyclerView = (ViewGroup) viewFetcher.getRecyclerView(false, recyclerViewIndex);
}
view = recyclerView.getChildAt(itemIndex);
}
return view;
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void finishOpenedActivities(){
// Stops the activityStack listener
activitySyncTimer.cancel();
ArrayList<Activity> activitiesOpened = getAllOpenedActivities();
// Finish all opened activities
for (int i = activitiesOpened.size()-1; i >= 0; i--) {
sleeper.sleep(MINISLEEP);
finishActivity(activitiesOpened.get(i));
}
// Finish the initial activity, pressing Back for good measure
finishActivity(getCurrentActivity());
sleeper.sleepMini();
try {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
sleeper.sleep(MINISLEEP);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
} catch (Throwable ignored) {
// Guard against lack of INJECT_EVENT permission
}
activityStack.clear();
} | #vulnerable code
public void finishOpenedActivities(){
ArrayList<Activity> activitiesOpened = getAllOpenedActivities();
// Finish all opened activities
for (int i = activitiesOpened.size()-1; i >= 0; i--) {
sleeper.sleep(MINISLEEP);
finishActivity(activitiesOpened.get(i));
}
// Finish the initial activity, pressing Back for good measure
finishActivity(getCurrentActivity());
sleeper.sleepMini();
try {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
sleeper.sleep(MINISLEEP);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
} catch (Throwable ignored) {
// Guard against lack of INJECT_EVENT permission
}
activityList.clear();
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void colorize(InputFile i) {
final File f = i.file();
LOGGER.info("Color the file: " + f.getPath());
highlighting.onFile(i);
try (final BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8))) {
String line;
int lineNumber = 1;
while ((line = br.readLine()) != null) {
searchAndColor(line, lineNumber);
lineNumber++;
}
br.close();
} catch (final IOException e) {
LOGGER.error("IO Exception", e);
}
highlighting.save();
} | #vulnerable code
public void colorize(InputFile i) {
final File f = i.file();
LOGGER.info("Color the file: " + f.getPath());
highlighting.onFile(i);
try {
final BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8));
String line;
int lineNumber = 1;
while ((line = br.readLine()) != null) {
searchAndColor(line, lineNumber);
lineNumber++;
}
br.close();
} catch (final IOException e) {
LOGGER.error("IO Exception", e);
}
highlighting.save();
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExecution() {
final CoverageSensor sensor = new CoverageSensor();
initFile();
sensor.execute(testerContext);
Map<String, Map<Integer, Integer>> map = new HashMap<>();
map.put("myProjectKey:mathutil/mathutil.go", ImmutableMap.of(7, 1));
map.put("myProjectKey:pixel/pixel.go", ImmutableMap.of(21, 0, 37, 0));
Map<Integer, Integer> testValuesMap = new HashMap<>();
testValuesMap.put(3, null);
testValuesMap.put(1, null);
testValuesMap.put(4, null);
testValuesMap.put(8, 0);
testValuesMap.put(12, 0);
map.put("myProjectKey:mathutil/filewithnocoverage.go", testValuesMap);
map.put("myProjectKey:issue60/a.go", ImmutableMap.of(8, 0, 9, 0));
Map<Integer, Integer> testValuesMap2 = new HashMap<>();
testValuesMap2.put(1, null);
testValuesMap2.put(2, null);
testValuesMap2.put(3, null);
testValuesMap2.put(4, null);
testValuesMap2.put(5, null);
testValuesMap2.put(6, null);
testValuesMap2.put(8, 0);
testValuesMap2.put(9, 0);
testValuesMap2.put(11, null);
map.put("myProjectKey:issue61/simplelinecomment.go", testValuesMap2);
Map<Integer, Integer> testValuesMap3 = new HashMap<>();
for (int i = 1; i <= 20; i++) {
testValuesMap3.put(i, null);
}
testValuesMap3.put(26, null);
testValuesMap3.put(27, null);
testValuesMap3.put(28, null);
testValuesMap3.put(30, 0);
testValuesMap3.put(31, 0);
map.put("myProjectKey:issue61/multilinecomment.go", testValuesMap3);
Map<Integer, Integer> testValuesMap4 = new HashMap<>();
for (int i = 6; i <= 48; i++) {
testValuesMap4.put(i, null);
}
map.put("myProjectKey:issue61/typestruct.go", testValuesMap4);
map.forEach((key, mapValue) -> {
mapValue.forEach((line, value) -> {
assertEquals("line " + line + " " + key, value, testerContext.lineHits(key, CoverageType.UNIT, line));
});
});
} | #vulnerable code
@Test
public void testExecution() {
final CoverageSensor sensor = new CoverageSensor();
try {
BufferedReader reader = new BufferedReader(
new FileReader(new File(CoverageSensor.class.getResource("/coverage/util/util.go").getFile())));
String sCurrentLine;
StringBuilder sb = new StringBuilder();
while ((sCurrentLine = reader.readLine()) != null) {
sb.append(sCurrentLine + "\n");
}
testerContext.fileSystem().add(new DefaultInputFile("myProjectKey", "util/util.go")
.setLanguage(GoLanguage.KEY).initMetadata(sb.toString()));
reader = new BufferedReader(new FileReader(
new File(CoverageSensor.class.getResource("/coverage/mathutil/mathutil.go").getFile())));
sb = new StringBuilder();
while ((sCurrentLine = reader.readLine()) != null) {
sb.append(sCurrentLine + "\n");
}
testerContext.fileSystem().add(new DefaultInputFile("myProjectKey", "mathutil/mathutil.go")
.setLanguage(GoLanguage.KEY).initMetadata(sb.toString()));
reader = new BufferedReader(
new FileReader(new File(CoverageSensor.class.getResource("/coverage/pixel/pixel.go").getFile())));
sb = new StringBuilder();
while ((sCurrentLine = reader.readLine()) != null) {
sb.append(sCurrentLine + "\n");
}
testerContext.fileSystem().add(new DefaultInputFile("myProjectKey", "pixel/pixel.go")
.setLanguage(GoLanguage.KEY).initMetadata(sb.toString()));
reader = new BufferedReader(new FileReader(
new File(CoverageSensor.class.getResource("/coverage/mathutil/filewithnocoverage.go").getFile())));
sb = new StringBuilder();
while ((sCurrentLine = reader.readLine()) != null) {
sb.append(sCurrentLine + "\n");
}
testerContext.fileSystem().add(new DefaultInputFile("myProjectKey", "mathutil/filewithnocoverage.go")
.setLanguage(GoLanguage.KEY).initMetadata(sb.toString()));
reader = new BufferedReader(
new FileReader(new File(CoverageSensor.class.getResource("/coverage/mathutil/a.go").getFile())));
sb = new StringBuilder();
while ((sCurrentLine = reader.readLine()) != null) {
sb.append(sCurrentLine + "\n");
}
testerContext.fileSystem().add(new DefaultInputFile("myProjectKey", "mathutil/a.go")
.setLanguage(GoLanguage.KEY).initMetadata(sb.toString()));
sensor.execute(testerContext);
Map<String, Map<Integer, Integer>> map = new HashMap<>();
map.put("myProjectKey:mathutil/mathutil.go", ImmutableMap.of(7, 1));
map.put("myProjectKey:pixel/pixel.go", ImmutableMap.of(21, 0, 37, 0));
Map<Integer, Integer> testValuesMap = new HashMap<>();
testValuesMap.put(3, null);
testValuesMap.put(1, null);
testValuesMap.put(4, null);
testValuesMap.put(8, 0);
testValuesMap.put(12, 0);
map.put("myProjectKey:mathutil/filewithnocoverage.go", testValuesMap);
map.put("myProjectKey:mathutil/a.go", ImmutableMap.of(8, 0, 9, 0));
map.forEach((key, mapValue) -> {
mapValue.forEach((line, value) -> {
assertEquals("line " + line + " " + key, value,
testerContext.lineHits(key, CoverageType.UNIT, line));
});
});
} catch (final FileNotFoundException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
}
#location 87
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void init() {
try {
LOGGER.info("Load "+PATH_FILE);
InputStream input=GoKeyRule.class.getResourceAsStream(PATH_FILE);
if(input==null){
throw new FileNotFoundException(PATH_FILE);
}
prop.load(input);
} catch (IOException e) {
LOGGER.error("Unable to load the config file", e);
}
} | #vulnerable code
private static void init() {
try {
prop.load(new FileInputStream(new File(PATH_FILE)));
} catch (FileNotFoundException e) {
LOGGER.error("Unable to load the config file", e);
} catch (IOException e) {
LOGGER.error("Unable to load the config file", e);
}
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private CharBuffer getFileAsBufferFromPath(Path p) {
try (FileInputStream input = new FileInputStream(p.toString())) {
FileChannel channel = input.getChannel();
ByteBuffer bbuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size());
return Charset.forName("utf8").newDecoder().decode(bbuf);
} catch (FileNotFoundException e) {
LOGGER.warn("IO Exception caught -", e);
} catch (IOException e) {
LOGGER.warn("IO Exception caught -", e);
}
return null;
} | #vulnerable code
private CharBuffer getFileAsBufferFromPath(Path p) throws IOException {
FileInputStream input = new FileInputStream(p.toString());
FileChannel channel = input.getChannel();
ByteBuffer bbuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size());
return Charset.forName("utf8").newDecoder().decode(bbuf);
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public RulesProfile createProfile(ValidationMessages validation) {
LOGGER.info("Golint Quality profile");
RulesProfile profile = RulesProfile.create("Golint Rules", GoLanguage.KEY);
profile.setDefaultProfile(Boolean.TRUE);
Properties prop=new Properties();
try {
prop.load(GoQualityProfile.class.getResourceAsStream(GoQualityProfile.PROFILE_PATH));
for (Entry<Object, Object> e : prop.entrySet()) {
if(Boolean.TRUE.equals(Boolean.parseBoolean((String) e.getValue()))){
profile.activateRule(Rule.create(REPO_KEY,(String) e.getKey(),REPO_NAME), null);
}
}
}catch (IOException e) {
LOGGER.error((new StringBuilder()).append("Unable to load ").append(PROFILE_PATH).toString(), e);
}
LOGGER.info((new StringBuilder()).append("Profil generate: ").append(profile.getActiveRules()).toString());
return profile;
} | #vulnerable code
@Override
public RulesProfile createProfile(ValidationMessages validation) {
LOGGER.info("Golint Quality profile");
RulesProfile profile = RulesProfile.create("Golint Rules", GoLanguage.KEY);
profile.setDefaultProfile(Boolean.TRUE);
Properties prop=new Properties();
try {
prop.load(new FileInputStream(new File(PROFILE_PATH)));
for (Entry<Object, Object> e : prop.entrySet()) {
if(Boolean.TRUE.equals(Boolean.parseBoolean((String) e.getValue()))){
profile.activateRule(Rule.create(REPO_KEY,(String) e.getKey(),REPO_NAME), null);
}
}
}catch (IOException e) {
LOGGER.error((new StringBuilder()).append("Unable to load ").append(PROFILE_PATH).toString(), e);
}
LOGGER.info((new StringBuilder()).append("Profil generate: ").append(profile.getActiveRules()).toString());
return profile;
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void check(GitlabMergeRequest gitlabMergeRequest) {
if (_mergeRequestStatus == null) {
_mergeRequestStatus = new GitlabMergeRequestStatus();
}
if (_iid == null) {
_iid = gitlabMergeRequest.getIid();
}
if (_targetBranch == null) {
_targetBranch = gitlabMergeRequest.getTargetBranch();
}
if (_sourceBranch == null) {
_sourceBranch = gitlabMergeRequest.getSourceBranch();
}
if (_sourceProject == null) {
try {
GitlabAPI api = _builder.getGitlab().get();
_sourceProject = getSourceProject(gitlabMergeRequest, api);
} catch (IOException e) {
_logger.log(Level.SEVERE, "Failed to get source project for Merge request " + gitlabMergeRequest.getId() + " :\n" + e.getMessage());
return;
}
}
try {
GitlabAPI api = _builder.getGitlab().get();
GitlabNote lastJenkinsNote = getJenkinsNote(gitlabMergeRequest, api);
GitlabCommit latestCommit = getLatestCommit(gitlabMergeRequest, api);
if (lastJenkinsNote == null) {
_shouldRun = true;
} else if (latestCommit == null) {
_logger.log(Level.SEVERE, "Failed to determine the lastest commit for merge request {" + gitlabMergeRequest.getId() + "}. This might be caused by a stalled MR in gitlab.");
return;
} else {
_shouldRun = latestCommitIsNotReached(latestCommit);
}
if (_shouldRun) {
_mergeRequestStatus.setLatestCommitOfMergeRequest(_id.toString(), latestCommit.getId());
}
} catch (IOException e) {
_logger.log(Level.SEVERE, "Failed to fetch commits for Merge Request " + gitlabMergeRequest.getId());
}
if (_shouldRun) {
build();
}
} | #vulnerable code
public void check(GitlabMergeRequest gitlabMergeRequest) {
if (_iid == null) {
_iid = gitlabMergeRequest.getIid();
}
if (_targetBranch == null) {
_targetBranch = gitlabMergeRequest.getTargetBranch();
}
if (_sourceBranch == null) {
_sourceBranch = gitlabMergeRequest.getSourceBranch();
}
if (_sourceProject == null) {
try {
GitlabAPI api = _builder.getGitlab().get();
_sourceProject = getSourceProject(gitlabMergeRequest, api);
} catch (IOException e) {
_logger.log(Level.SEVERE, "Failed to get source project for Merge request " + gitlabMergeRequest.getId() + " :\n" + e.getMessage());
return;
}
}
try {
GitlabAPI api = _builder.getGitlab().get();
GitlabNote lastJenkinsNote = getJenkinsNote(gitlabMergeRequest, api);
GitlabCommit latestCommit = getLatestCommit(gitlabMergeRequest, api);
if (lastJenkinsNote == null) {
_shouldRun = true;
} else {
_shouldRun = latestCommitIsNotReached(latestCommit);
}
if (_shouldRun) {
_mergeRequestStatus.setLatestCommitOfMergeRequest(_id.toString(), latestCommit.getId());
}
} catch (IOException e) {
_logger.log(Level.SEVERE, "Failed to fetch commits for Merge Request " + gitlabMergeRequest.getId());
}
if (_shouldRun) {
build();
}
}
#location 35
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void check(GitlabMergeRequest gitlabMergeRequest) {
if (mergeRequestStatus == null) {
mergeRequestStatus = new GitlabMergeRequestStatus();
}
if (iid == null) {
iid = gitlabMergeRequest.getIid();
}
if (targetBranch == null || targetBranch.trim().isEmpty()) {
targetBranch = gitlabMergeRequest.getTargetBranch();
}
if (sourceBranch == null || sourceBranch.trim().isEmpty()) {
sourceBranch = gitlabMergeRequest.getSourceBranch();
}
if (description == null || description.trim().isEmpty()) {
description = gitlabMergeRequest.getDescription();
if (description == null) { description = ""; }
}
if (sourceProject == null || sourceProject.getId() == null || sourceProject.getName() == null) {
try {
GitlabAPI api = builder.getGitlab().get();
sourceProject = getSourceProject(gitlabMergeRequest, api);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to get source project for Merge request " + gitlabMergeRequest.getId() + " :\n" + e.getMessage());
return;
}
}
try {
GitlabAPI api = builder.getGitlab().get();
GitlabCommit latestCommit = getLatestCommit(gitlabMergeRequest, api);
if (latestCommit == null) { // the source branch has been removed
return;
}
Map<String, String> customParameters = getSpecifiedCustomParameters(gitlabMergeRequest, api);
build(customParameters, latestCommit.getId(), gitlabMergeRequest);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to fetch commits for Merge Request " + gitlabMergeRequest.getId());
}
} | #vulnerable code
public void check(GitlabMergeRequest gitlabMergeRequest) {
if (mergeRequestStatus == null) {
mergeRequestStatus = new GitlabMergeRequestStatus();
}
if (iid == null) {
iid = gitlabMergeRequest.getIid();
}
if (targetBranch == null || targetBranch.trim().isEmpty()) {
targetBranch = gitlabMergeRequest.getTargetBranch();
}
if (sourceBranch == null || sourceBranch.trim().isEmpty()) {
sourceBranch = gitlabMergeRequest.getSourceBranch();
}
if (description == null || description.trim().isEmpty()) {
description = gitlabMergeRequest.getDescription();
if (description == null) { description = ""; }
}
if (sourceProject == null || sourceProject.getId() == null || sourceProject.getName() == null) {
try {
GitlabAPI api = builder.getGitlab().get();
sourceProject = getSourceProject(gitlabMergeRequest, api);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to get source project for Merge request " + gitlabMergeRequest.getId() + " :\n" + e.getMessage());
return;
}
}
try {
GitlabAPI api = builder.getGitlab().get();
GitlabCommit latestCommit = getLatestCommit(gitlabMergeRequest, api);
Map<String, String> customParameters = getSpecifiedCustomParameters(gitlabMergeRequest, api);
build(customParameters, latestCommit.getId(), gitlabMergeRequest);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to fetch commits for Merge Request " + gitlabMergeRequest.getId());
}
}
#location 40
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Field getField(final Class<?> clazz, final String fieldName) throws Exception {
Field field = clazz.getDeclaredField(fieldName);
if (field != null)
field.setAccessible(true);
else if (clazz.getSuperclass() != null)
field = getField(clazz.getSuperclass(), fieldName);
return field;
} | #vulnerable code
public static Field getField(final Class<?> clazz, final String fieldName) throws Exception {
Field field = clazz.getDeclaredField(fieldName);
if (field == null && clazz.getSuperclass() != null) {
field = getField(clazz.getSuperclass(), fieldName);
}
field.setAccessible(true);
return field;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShortArray_AsShorts() throws Exception {
assertArrayEquals(new byte[]{1, 2, 3, 4}, BeginBin().Short((short)0x0102, (short)0x0304).End().toByteArray());
} | #vulnerable code
@Test
public void testShortArray_AsShorts() throws Exception {
assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBitArrayAsBytes() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).End().toByteArray());
} | #vulnerable code
@Test
public void testBitArrayAsBytes() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int read() throws IOException {
final int result;
if (this.bitsInBuffer == 0) {
result = this.readByteFromStream();
if (result >= 0) {
this.byteCounter++;
}
return result;
}
else {
return this.readBits(JBBPBitNumber.BITS_8);
}
} | #vulnerable code
@Override
public int read() throws IOException {
final int result;
if (this.bitsInBuffer == 0) {
result = this.readByteFromStream();
if (result < 0) {
return result;
}
return result;
}
else {
return this.readBits(JBBPBitNumber.BITS_8);
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testByteArrayAsByteArray() throws Exception {
assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, BeginBin().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).End().toByteArray());
} | #vulnerable code
@Test
public void testByteArrayAsByteArray() throws Exception {
assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBit_MSB0() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).End().toByteArray());
} | #vulnerable code
@Test
public void testBit_MSB0() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testByte() throws Exception {
assertArrayEquals(new byte[]{-34}, BeginBin().Byte(-34).End().toByteArray());
} | #vulnerable code
@Test
public void testByte() throws Exception {
assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBitArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(1, 3, 0, 2, 4, 1, 3, 7).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(1, 3, 0, 7).End().toByteArray());
} | #vulnerable code
@Test
public void testBitArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray());
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFlush() throws Exception {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final JBBPOut out = BeginBin(buffer);
out.Bit(true);
assertEquals(0, buffer.size());
out.Flush();
assertEquals(1, buffer.size());
} | #vulnerable code
@Test
public void testFlush() throws Exception {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final JBBPOut out = binStart(buffer);
out.Bit(true);
assertEquals(0, buffer.size());
out.Flush();
assertEquals(1, buffer.size());
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.