input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Override public Transaction getTx(NulsDigestData hash) { TransactionLocalPo localPo = localTxDao.get(hash.getDigestHex()); if (localPo != null) { try { Transaction tx = UtxoTransferTool.toTransaction(localPo); return tx; } catch (Exception e) { Log.error(e); } } TransactionPo po = txDao.get(hash.getDigestHex()); if (null == po) { return null; } try { Transaction tx = UtxoTransferTool.toTransaction(po); return tx; } catch (Exception e) { Log.error(e); } return null; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Transaction getTx(NulsDigestData hash) { TransactionPo po = txDao.get(hash.getDigestHex()); if (null != po) { try { Transaction tx = UtxoTransferTool.toTransaction(po); return tx; } catch (Exception e) { Log.error(e); } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Result<Account> importAccount(String prikey, String password) { if (!ECKey.isValidPrivteHex(prikey)) { return Result.getFailed(AccountErrorCode.PARAMETER_ERROR); } Account account; try { account = AccountTool.createAccount(prikey); } catch (NulsException e) { return Result.getFailed(AccountErrorCode.FAILED); } Account accountDB = getAccountByAddress(account.getAddress().toString()); if (null != accountDB) { return Result.getFailed(AccountErrorCode.ACCOUNT_EXIST); } if (StringUtils.validPassword(password)) { try { account.encrypt(password); } catch (NulsException e) { Log.error(e); } } AccountPo po = new AccountPo(account); accountStorageService.saveAccount(po); LOCAL_ADDRESS_LIST.add(account.getAddress().toString()); accountLedgerService.importAccountLedger(account.getAddress().getBase58()); return Result.getSuccess().setData(account); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Result<Account> importAccount(String prikey, String password) { if (!ECKey.isValidPrivteHex(prikey)) { return Result.getFailed(AccountErrorCode.PARAMETER_ERROR); } Account account; try { account = AccountTool.createAccount(prikey); } catch (NulsException e) { return Result.getFailed(AccountErrorCode.FAILED); } if (StringUtils.validPassword(password)) { try { account.encrypt(password); } catch (NulsException e) { Log.error(e); } } AccountPo po = new AccountPo(account); accountStorageService.saveAccount(po); LOCAL_ADDRESS_LIST.add(account.getAddress().toString()); accountLedgerService.importAccountLedger(account.getAddress().getBase58()); return Result.getSuccess().setData(account); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void reSendLocalTx() throws NulsException { List<Transaction> txList = getLedgerCacheService().getUnconfirmTxList(); List<Transaction> helpList = new ArrayList<>(); for (Transaction tx : txList) { if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) { continue; } ValidateResult result = getLedgerService().verifyTx(tx, helpList); if (result.isFailed()) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex()); continue; } Transaction transaction = getLedgerService().getTx(tx.getHash()); if (transaction != null) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex()); continue; } helpList.add(tx); TransactionEvent event = new TransactionEvent(); event.setEventBody(tx); getEventBroadcaster().publishToLocal(event); } } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private void reSendLocalTx() throws NulsException { List<Transaction> txList = ledgerCacheService.getUnconfirmTxList(); List<Transaction> helpList = new ArrayList<>(); for (Transaction tx : txList) { if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) { continue; } ValidateResult result = getLedgerService().verifyTx(tx, helpList); if (result.isFailed()) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex()); continue; } Transaction transaction = getLedgerService().getTx(tx.getHash()); if (transaction != null) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex()); continue; } helpList.add(tx); TransactionEvent event = new TransactionEvent(); event.setEventBody(tx); getEventBroadcaster().publishToLocal(event); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start() { Log.debug("Start"); notificationController = new NotificationController(); EventBusService eventBusService = NulsContext.getServiceBean(EventBusService.class); eventBusService.subscribeEvent(BaseEvent.class,notificationController.getNulsEventHandler()); notificationController.setListenPort(port); notificationController.start(); NulsEventHandler handler = new NulsEventHandler(); String subscribeId = NulsContext.getServiceBean(EventBusService.class).subscribeEvent(BaseEvent.class,handler); Log.debug("subscribe base event:"+subscribeId); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void start() { Log.debug("Start"); notificationController = new NotificationController(); EventBusService eventBusService = NulsContext.getServiceBean(EventBusService.class); eventBusService.subscribeEvent(BaseEvent.class,notificationController.getNulsEventHandler()); notificationController.setListenPort(port); notificationController.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isLocalHasSeed(List<Account> accountList) { for (Account account : accountList) { for (PocMeetingMember seed : this.getDefaultSeedList()) { if (seed.getAgentAddress().equals(account.getAddress().getBase58())) { return true; } } } return false; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean isLocalHasSeed(List<Account> accountList) { for (Account account : accountList) { for (String seedAddress : csManager.getSeedNodeList()) { if (seedAddress.equals(account.getAddress().getBase58())) { return true; } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void start() { try { ChannelFuture future = boot.connect(node.getIp(), node.getSeverPort()).sync(); if (future.isSuccess()) { socketChannel = (SocketChannel) future.channel(); } else { System.out.println("---------------client start !success remove node-----------------" + node.getId()); getNetworkService().removeNode(node.getId()); } future.channel().closeFuture().sync(); } catch (Exception e) { Log.debug("-------------NettyClient start error: " + e.getMessage()); //maybe time out or refused or something if (socketChannel != null) { socketChannel.close(); } System.out.println("---------------client start exception remove node-----------------" + node.getId()); getNetworkService().removeNode(node.getId()); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public void start() { try { ChannelFuture future = boot.connect(node.getIp(), node.getSeverPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { socketChannel = (SocketChannel) future.channel(); } else { Log.info("Client connect to host error: " + future.cause() + ", remove node: " + node.getId()); getNetworkService().removeNode(node.getId()); } } }); future.channel().closeFuture().sync(); } catch (Exception e) { //maybe time out or refused or something if (socketChannel != null) { socketChannel.close(); } Log.error("Client start exception:" + e.getMessage() + ", remove node: " + node.getId()); getNetworkService().removeNode(node.getId()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<Transaction> getWaitingTxList() throws NulsException { List<TransactionLocalPo> poList = localTxDao.getUnConfirmTxs(); List<Transaction> txList = new ArrayList<>(); for (TransactionLocalPo po : poList) { Transaction tx = UtxoTransferTool.toTransaction(po); txList.add(tx); } return txList; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public List<Transaction> getWaitingTxList() throws NulsException { return ledgerCacheService.getUnconfirmTxList(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start() { this.waitForDependencyRunning(MessageBusConstant.MODULE_ID_MESSAGE_BUS); this.initHandlers(); ((DownloadServiceImpl) NulsContext.getServiceBean(DownloadService.class)).start(); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void start() { this.waitForDependencyRunning(MessageBusConstant.MODULE_ID_MESSAGE_BUS); this.waitForDependencyInited(ConsensusConstant.MODULE_ID_CONSENSUS); this.initHandlers(); ((DownloadServiceImpl) NulsContext.getServiceBean(DownloadService.class)).start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { alias = new String(byteBuffer.readByLengthByte()); address = new Address(new String(byteBuffer.readByLengthByte())); encryptedPriKey = byteBuffer.readByLengthByte(); pubKey = byteBuffer.readByLengthByte(); status = (int)(byteBuffer.readVarInt()); extend = byteBuffer.readByLengthByte(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { address = Address.fromHashs(byteBuffer.readByLengthByte()); alias = new String(byteBuffer.readByLengthByte()); encryptedPriKey = byteBuffer.readByLengthByte(); pubKey = byteBuffer.readByLengthByte(); status = (int) (byteBuffer.readByte()); extend = byteBuffer.readByLengthByte(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void calc() { if (null == nodeIdList || nodeIdList.isEmpty()) { throw new NulsRuntimeException(ErrorCode.FAILED, "success list of nodes is empty!"); } int size = nodeIdList.size(); int halfSize = (size + 1) / 2; if (hashesMap.size() <= halfSize) { return; } BlockInfo result = null; for (String key : calcMap.keySet()) { List<String> nodes = calcMap.get(key); if (nodes.size() > halfSize) { result = new BlockInfo(); BlockHashResponse response = hashesMap.get(result.getNodeIdList().get(0)); Long bestHeight = 0L; NulsDigestData bestHash = null; for (int i = 0; i < response.getHeightList().size(); i++) { Long height = response.getHeightList().get(i); NulsDigestData hash = response.getHashList().get(i); if (height > bestHeight) { bestHash = hash; bestHeight = height; } result.putHash(height, hash); } result.setBestHash(bestHash); result.setBestHeight(bestHeight); result.setNodeIdList(nodes); result.setFinished(true); break; } } if (null != result) { bestBlockInfo = result; } else if (size == calcMap.size()) { try { Thread.sleep(2000L); } catch (InterruptedException e) { Log.error(e); } this.request(start, end, split); } } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code private void calc() { if (null == nodeIdList || nodeIdList.isEmpty()) { throw new NulsRuntimeException(ErrorCode.FAILED, "success list of nodes is empty!"); } int size = nodeIdList.size(); int halfSize = (size + 1) / 2; //todo 临时去掉=号 if (hashesMap.size() < halfSize) { return; } BlockInfo result = null; for (String key : calcMap.keySet()) { List<String> nodes = calcMap.get(key); //todo 临时加上=号 if (nodes.size() >= halfSize) { result = new BlockInfo(); BlockHashResponse response = hashesMap.get(nodes.get(0)); Long bestHeight = 0L; NulsDigestData bestHash = null; for (int i = 0; i < response.getHeightList().size(); i++) { Long height = response.getHeightList().get(i); NulsDigestData hash = response.getHashList().get(i); if (height > bestHeight) { bestHash = hash; bestHeight = height; } result.putHash(height, hash); } result.setBestHash(bestHash); result.setBestHeight(bestHeight); result.setNodeIdList(nodes); result.setFinished(true); break; } } if (null != result) { bestBlockInfo = result; } else if (size == calcMap.size()) { try { Thread.sleep(2000L); } catch (InterruptedException e) { Log.error(e); } this.request(start, end, split); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public TransferTransaction createTransferTx(CoinTransferData transferData, String password, String remark) throws Exception { TransferTransaction tx = new TransferTransaction(transferData, password); tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING)); tx.setHash(NulsDigestData.calcDigestData(tx.serialize())); tx.setSign(getAccountService().signData(tx.getHash(), password)); return tx; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public TransferTransaction createTransferTx(CoinTransferData transferData, String password, String remark) throws Exception { TransferTransaction tx = new TransferTransaction(transferData, password); tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING)); tx.setHash(NulsDigestData.calcDigestData(tx.serialize())); AccountService accountService = getAccountService(); if (transferData.getFrom().isEmpty()) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } Account account = accountService.getAccount(transferData.getFrom().get(0)); tx.setSign(accountService.signData(tx.getHash(), account, password)); return tx; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void handleKey(SelectionKey key) { ConnectionHandler handler = (ConnectionHandler) key.attachment(); try { if (!key.isValid()) { // Key has been cancelled, make sure the socket gets closed System.out.println("--------------------destory 1"); handler.peer.destroy(); return; } if (key.isReadable()) { // Do a socket read and invoke the connection's receiveBytes message int len = handler.channel.read(handler.readBuffer); if (len == 0) { // Was probably waiting on a write return; } else if (len == -1) { // Socket was closed key.cancel(); System.out.println(handler.peer.getIp()); System.out.println("--------------------destory 2"); handler.peer.destroy(); return; } System.out.println("--------len : " + len); // "flip" the buffer - setting the limit to the current position and setting position to 0 handler.readBuffer.flip(); handler.peer.receiveMessage(handler.readBuffer); // Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative position) handler.readBuffer.compact(); } if (key.isWritable()) { handler.writeBytes(); } } catch (Exception e) { // This can happen eg if the channel closes while the thread is about to get killed // (ClosedByInterruptException), or if handler.connection.receiveBytes throws something e.printStackTrace(); Throwable t = e; Log.warn("Error handling SelectionKey: {}", t.getMessage() != null ? t.getMessage() : t.getClass().getName()); System.out.println("--------------------destory 3"); handler.peer.destroy(); } } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void handleKey(SelectionKey key) { ConnectionHandler handler = (ConnectionHandler) key.attachment(); try { if (!key.isValid()) { // Key has been cancelled, make sure the socket gets closed System.out.println("--------------------destory 1" + handler.peer.getIp()); handler.peer.destroy(); return; } if (key.isReadable()) { // Do a socket read and invoke the connection's receiveBytes message int len = handler.channel.read(handler.readBuffer); if (len == 0) { // Was probably waiting on a write return; } else if (len == -1) { // Socket was closed key.cancel(); System.out.println("--------------------destory 2" + handler.peer.getIp()); handler.peer.destroy(); return; } // "flip" the buffer - setting the limit to the current position and setting position to 0 handler.readBuffer.flip(); handler.peer.receiveMessage(handler.readBuffer); // Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative position) handler.readBuffer.compact(); } if (key.isWritable()) { handler.writeBytes(); } } catch (Exception e) { // This can happen eg if the channel closes while the thread is about to get killed // (ClosedByInterruptException), or if handler.connection.receiveBytes throws something e.printStackTrace(); Throwable t = e; Log.warn("Error handling SelectionKey: {}", t.getMessage() != null ? t.getMessage() : t.getClass().getName()); System.out.println("--------------------destory 3" + handler.peer.getIp()); handler.peer.destroy(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HeaderDigest getLastHd() { if (null == lastHd) { List<HeaderDigest> list = new ArrayList<>(headerDigestList); if(list.size() > 0) { this.lastHd = list.get(list.size() - 1); } } return lastHd; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public HeaderDigest getLastHd() { List<HeaderDigest> list = new ArrayList<>(headerDigestList); if (list.size() > 0) { return list.get(list.size() - 1); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public double readDouble() throws NulsException { return Utils.bytes2Double(this.readByLengthByte()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public double readDouble() throws NulsException { byte[] bytes = this.readByLengthByte(); if(null==bytes){ return 0; } return Utils.bytes2Double(bytes); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) { if (!hashesMap.containsKey(nodeId)) { return false; } if (!requesting) { return false; } if(hashesMap.get(nodeId)==null){ hashesMap.put(nodeId, response); }else{ BlockHashResponse instance = hashesMap.get(nodeId); instance.merge(response); hashesMap.put(nodeId,instance); } if(response.getHeightList().get(response.getHeightList().size()-1)<end){ return true; } String key = response.getHash().getDigestHex(); List<String> nodes = calcMap.get(key); if (null == nodes) { nodes = new ArrayList<>(); } if (!nodes.contains(nodeId)) { nodes.add(nodeId); } calcMap.put(key, nodes); calc(); return true; } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) { if (!hashesMap.containsKey(nodeId)) { return false; } if (!requesting) { return false; } if (hashesMap.get(nodeId) == null) { hashesMap.put(nodeId, response); } else { BlockHashResponse instance = hashesMap.get(nodeId); instance.merge(response); hashesMap.put(nodeId, instance); } if (response.getHeightList().get(response.getHeightList().size() - 1) < end) { return true; } String key = response.getHash().getDigestHex(); List<String> nodes = calcMap.get(key); if (null == nodes) { nodes = new ArrayList<>(); } if (!nodes.contains(nodeId)) { nodes.add(nodeId); } calcMap.put(key, nodes); calc(); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (!Address.validAddress(alias.getAddress())) { return ValidateResult.getFailedResult("The address format error"); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult("The alias is between 3 to 20 characters"); } long aliasValue = 0; UtxoData utxoData = (UtxoData) tx.getCoinData(); for (UtxoInput input : utxoData.getInputs()) { if (input.getFrom() == null) { return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } aliasValue += input.getFrom().getValue(); } if (aliasValue < AccountConstant.ALIAS_NA.add(getLedgerService().getTxFee(TransactionConstant.TX_TYPE_SET_ALIAS)).getValue()) { return ValidateResult.getFailedResult("utxo not enough"); } if (tx.getStatus() == TxStatusEnum.CACHED) { List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS); if (txList != null && tx.size() > 0) { for (Transaction trx : txList) { if(trx.getHash().equals(tx.getHash())) { continue; } Alias a = ((AliasTransaction) trx).getTxData(); if (alias.getAddress().equals(a.getAddress())) { return ValidateResult.getFailedResult("Alias has been set up "); } if (alias.getAlias().equals(a.getAlias())) { return ValidateResult.getFailedResult("The alias has been occupied"); } } } } AliasPo aliasPo = getAliasDataService().get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult("The alias has been occupied"); } return ValidateResult.getSuccessResult(); } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (!Address.validAddress(alias.getAddress())) { return ValidateResult.getFailedResult(ErrorCode.ADDRESS_ERROR); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult(ErrorCode.ALIAS_ERROR); } long aliasValue = 0; UtxoData utxoData = (UtxoData) tx.getCoinData(); for (UtxoInput input : utxoData.getInputs()) { aliasValue += input.getFrom().getValue(); } if (aliasValue < AccountConstant.ALIAS_NA.getValue() + tx.getFee().getValue()) { return ValidateResult.getFailedResult(ErrorCode.INVALID_INPUT); } if (tx.getStatus() == TxStatusEnum.CACHED) { List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS); if (txList != null && tx.size() > 0) { for (Transaction trx : txList) { if (trx.getHash().equals(tx.getHash())) { continue; } Alias a = ((AliasTransaction) trx).getTxData(); if (alias.getAddress().equals(a.getAddress())) { return ValidateResult.getFailedResult(ErrorCode.ACCOUNT_ALREADY_SET_ALIAS); } if (alias.getAlias().equals(a.getAlias())) { return ValidateResult.getFailedResult("The alias has been occupied"); } } } } AliasPo aliasPo = getAliasDataService().get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult(ErrorCode.ALIAS_EXIST); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRun() { assertNotNull(blockProcessTask); ConsensusStatusContext.setConsensusStatus(ConsensusStatus.WAIT_START); blockProcessTask.run(); assert(!ConsensusStatusContext.isRunning()); ConsensusDownloadServiceImpl downloadService = SpringLiteContext.getBean(ConsensusDownloadServiceImpl.class); downloadService.setDownloadSuccess(true); blockProcessTask.run(); assert(ConsensusStatusContext.isRunning()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRun() { assertNotNull(blockProcessTask); if(downloadService.isDownloadSuccess().isSuccess()) { downloadService.setDownloadSuccess(false); } ConsensusStatusContext.setConsensusStatus(ConsensusStatus.WAIT_START); blockProcessTask.run(); assert(!ConsensusStatusContext.isRunning()); downloadService.setDownloadSuccess(true); blockProcessTask.run(); assert(ConsensusStatusContext.isRunning()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void start() { List<Peer> peers = discovery.getLocalPeers(10); if (peers.isEmpty()) { peers = getSeedPeers(); } for (Peer peer : peers) { peer.setType(Peer.OUT); addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer); } boolean isConsensus = ConfigLoader.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false); if (isConsensus) { network.maxOutCount(network.maxOutCount() * 5); network.maxInCount(network.maxInCount() * 5); } System.out.println("-----------peerManager start"); //start heart beat thread ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void start() { List<Peer> peers = discovery.getLocalPeers(10); if (peers.isEmpty()) { peers = getSeedPeers(); } for (Peer peer : peers) { peer.setType(Peer.OUT); addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer); } boolean isConsensus = NulsContext.MODULES_CONFIG.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false); if (isConsensus) { network.maxOutCount(network.maxOutCount() * 5); network.maxInCount(network.maxInCount() * 5); } System.out.println("-----------peerManager start"); //start heart beat thread ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) { return ValidateResult.getFailedResult("The address format error"); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult("The alias is between 3 to 20 characters"); } AliasPo aliasPo = getAliasDataService().get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult("The alias has been occupied"); } return ValidateResult.getSuccessResult(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) { return ValidateResult.getFailedResult("The address format error"); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult("The alias is between 3 to 20 characters"); } List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS); if (txList != null && tx.size() > 0) { for (Transaction trx : txList) { Alias a = ((AliasTransaction) trx).getTxData(); if(alias.getAddress().equals(a.getAlias())) { return ValidateResult.getFailedResult("The alias has been occupied"); } if(alias.getAlias().equals(a.getAlias())){ return ValidateResult.getFailedResult("The alias has been occupied"); } } } AliasPo aliasPo = getAliasDataService().get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult("The alias has been occupied"); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Set<K> keySet(String cacheTitle) { Iterator it = cacheManager.getCache(cacheTitle).iterator(); Set<K> set = new HashSet<>(); while (it.hasNext()) { Cache.Entry<K, T> entry = (Cache.Entry<K, T>) it.next(); set.add((K) entry.getKey()); } return set; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Set<K> keySet(String cacheTitle) { Cache cache = this.cacheManager.getCache(cacheTitle); if (null == cache) { return new HashSet<>(); } Iterator it = cache.iterator(); Set<K> set = new HashSet<>(); while (it.hasNext()) { Cache.Entry<K, T> entry = (Cache.Entry<K, T>) it.next(); set.add((K) entry.getKey()); } return set; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Result createArea(String areaName) { // prevent too many areas if(AREAS.size() > (MAX -1)) { return new Result(false, "KV_AREA_CREATE_ERROR"); } if(StringUtils.isBlank(areaName)) { return Result.getFailed(ErrorCode.NULL_PARAMETER); } if (AREAS.containsKey(areaName)) { return new Result(true, "KV_AREA_EXISTS"); } //TODO 特殊字符校验 if(!checkPathLegal(areaName)) { return new Result(false, "KV_AREA_CREATE_ERROR"); } Result result; try { File dir = new File(dataPath + File.separator + areaName); if(!dir.exists()) { dir.mkdir(); } String filePath = dataPath + File.separator + areaName + File.separator + BASE_DB_NAME; DB db = openDB(filePath, true); AREAS.put(areaName, db); result = Result.getSuccess(); } catch (Exception e) { Log.error("error create area: " + areaName, e); result = new Result(false, "KV_AREA_CREATE_ERROR"); } return result; } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static Result createArea(String areaName) { // prevent too many areas if(AREAS.size() > (MAX -1)) { return new Result(false, "KV_AREA_CREATE_ERROR"); } if(StringUtils.isBlank(areaName)) { return Result.getFailed(ErrorCode.NULL_PARAMETER); } if (AREAS.containsKey(areaName)) { return new Result(true, "KV_AREA_EXISTS"); } if(!checkPathLegal(areaName)) { return new Result(false, "KV_AREA_CREATE_ERROR"); } Result result; try { File dir = new File(dataPath + File.separator + areaName); if(!dir.exists()) { dir.mkdir(); } String filePath = dataPath + File.separator + areaName + File.separator + BASE_DB_NAME; DB db = openDB(filePath, true); AREAS.put(areaName, db); result = Result.getSuccess(); } catch (Exception e) { Log.error("error create area: " + areaName, e); result = new Result(false, "KV_AREA_CREATE_ERROR"); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void nextRound() throws NulsException, IOException { packingRoundManager.calc(getBestBlock()); while (TimeService.currentTimeMillis() < (packingRoundManager.getCurrentRound().getStartTime())) { try { Thread.sleep(100L); } catch (InterruptedException e) { Log.error(e); } } boolean imIn = consensusManager.isPartakePacking() && packingRoundManager.getCurrentRound().getLocalPacker() != null; if (imIn) { startMeeting(); } } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private void nextRound() throws NulsException, IOException { packingRoundManager.calc(getBestBlock()); PocMeetingRound round = packingRoundManager.getCurrentRound(); while (TimeService.currentTimeMillis() < round.getStartTime()) { try { Thread.sleep(100L); } catch (InterruptedException e) { Log.error(e); } } boolean imIn = consensusManager.isPartakePacking() &&round.getLocalPacker() != null; if (imIn) { startMeeting(round); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() { //load five(CACHE_COUNT) round from db on the start time ; Block bestBlock = NulsContext.getInstance().getBestBlock(); BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend()); for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) { Block firstBlock = getBlockService().getRoundFirstBlock(bestBlock, i - 1); BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend()); PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime()); ROUND_MAP.put(round.getIndex(), round); Log.debug("load the round data index:{}", round.getIndex()); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void init() { //load five(CACHE_COUNT) round from db on the start time ; Block bestBlock = getBestBlock(); BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend()); for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) { Block firstBlock = getBlockService().getRoundFirstBlock(bestBlock, i - 1); BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend()); PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime()); ROUND_MAP.put(round.getIndex(), round); Log.debug("load the round data index:{}", round.getIndex()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public PocMeetingRound getCurrentRound() { Block currentBlock = NulsContext.getInstance().getBestBlock(); BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend()); PocMeetingRound round = ROUND_MAP.get(currentRoundData.getRoundIndex()); if (null == round) { round = resetCurrentMeetingRound(); } return round; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public PocMeetingRound getCurrentRound() { return currentRound; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void rollbackAppraval(Block block) { if (null == block) { Log.warn("the block is null!"); return; } this.rollbackTxList(block.getTxs(), 0, block.getTxs().size()); PackingRoundManager.getValidateInstance().calc(this.getBlock(block.getHeader().getPreHash().getDigestHex())); List<String> hashList = this.bifurcateProcessor.getHashList(block.getHeader().getHeight() - 1); if (hashList.size() > 1) { Block preBlock = confirmingBlockCacheManager.getBlock(block.getHeader().getPreHash().getDigestHex()); context.setBestBlock(preBlock); this.rollbackAppraval(preBlock); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private void rollbackAppraval(Block block) { if (null == block) { Log.warn("the block is null!"); return; } this.rollbackTxList(block.getTxs(), 0, block.getTxs().size()); Block preBlock =this.getBlock(block.getHeader().getPreHash().getDigestHex()); context.setBestBlock(preBlock); PackingRoundManager.getValidateInstance().calc(preBlock); List<String> hashList = this.bifurcateProcessor.getHashList(block.getHeader().getHeight() - 1); if (hashList.size() > 1) { this.rollbackAppraval(preBlock); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() { //load five(CACHE_COUNT) round from db on the start time ; Block bestBlock = getBestBlock(); BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend()); for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) { Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1); BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend()); PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime()); ROUND_MAP.put(round.getIndex(), round); Log.debug("load the round data index:{}", round.getIndex()); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void init() { //load five(CACHE_COUNT) round from db on the start time ; Block bestBlock = getBestBlock(); BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend()); for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) { Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1); BlockRoundData preRoundData = new BlockRoundData(firstBlock.getHeader().getExtend()); PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, preRoundData.getRoundEndTime()); ROUND_MAP.put(round.getIndex(), round); Log.debug("load the round data index:{}", round.getIndex()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private PocMeetingRound calcNextRound(BlockHeader bestBlockHeader, long bestHeight, BlockRoundData bestRoundData) { PocMeetingRound round = new PocMeetingRound(); round.setIndex(bestRoundData.getRoundIndex() + 1); round.setStartTime(bestRoundData.getRoundEndTime()); long calcHeight = 0L; if (bestRoundData.getPackingIndexOfRound() == bestRoundData.getConsensusMemberCount() || NulsContext.getInstance().getBestHeight() <= bestHeight) { calcHeight = bestHeight - PocConsensusConstant.CONFIRM_BLOCK_COUNT; } else { Block bestBlock = NulsContext.getInstance().getBestBlock(); if (null == bestBlock) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "best block is null"); } BlockRoundData localBestRoundData = new BlockRoundData(bestBlock.getHeader().getExtend()); if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() != localBestRoundData.getConsensusMemberCount()) { throw new NulsRuntimeException(ErrorCode.FAILED, "The next round of information is not yet available."); } else if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() == localBestRoundData.getConsensusMemberCount()) { return calcNextRound(bestBlock.getHeader(), bestBlock.getHeader().getHeight(), localBestRoundData); } else { Block nextRoundFirstBlock = getBlockService().getRoundFirstBlockFromDb(round.getIndex()); if (null == nextRoundFirstBlock) { long height = bestHeight + 1; while (true) { Block block = getBlockService().getBlock(height); height++; BlockRoundData blockRoundData = new BlockRoundData(block.getHeader().getExtend()); if (blockRoundData.getRoundIndex() == round.getIndex()) { nextRoundFirstBlock = block; break; } } } calcHeight = nextRoundFirstBlock.getHeader().getHeight() - PocConsensusConstant.CONFIRM_BLOCK_COUNT - 1; } } List<PocMeetingMember> memberList = getMemberList(calcHeight, round, bestBlockHeader); Collections.sort(memberList); round.setMemberList(memberList); round.setMemberCount(memberList.size()); while (round.getEndTime() < TimeService.currentTimeMillis()) { long time = TimeService.currentTimeMillis() - round.getStartTime(); long roundTime = round.getEndTime() - round.getStartTime(); long index = time / roundTime; long startTime = round.getStartTime() + index * roundTime; round.setStartTime(startTime); round.setIndex(bestRoundData.getRoundIndex() + index); } return round; } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code private PocMeetingRound calcNextRound(BlockHeader bestBlockHeader, long bestHeight, BlockRoundData bestRoundData) { PocMeetingRound round = new PocMeetingRound(); round.setIndex(bestRoundData.getRoundIndex() + 1); round.setStartTime(bestRoundData.getRoundEndTime()); long calcHeight = 0L; if (bestRoundData.getPackingIndexOfRound() == bestRoundData.getConsensusMemberCount() || NulsContext.getInstance().getBestHeight() <= bestHeight) { calcHeight = bestHeight - PocConsensusConstant.CONFIRM_BLOCK_COUNT; } else { Block bestBlock = NulsContext.getInstance().getBestBlock(); if (null == bestBlock) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "best block is null"); } BlockRoundData localBestRoundData = new BlockRoundData(bestBlock.getHeader().getExtend()); if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() != localBestRoundData.getConsensusMemberCount()) { throw new NulsRuntimeException(ErrorCode.FAILED, "The next round of information is not yet available."); } else if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() == localBestRoundData.getConsensusMemberCount()) { return calcNextRound(bestBlock.getHeader(), bestBlock.getHeader().getHeight(), localBestRoundData); } else { Block nextRoundFirstBlock = getBlockService().getRoundFirstBlockFromDb(round.getIndex()); if (null == nextRoundFirstBlock) { long height = bestHeight + 1; while (true) { Block block = getBlockService().getBlock(height); height++; BlockRoundData blockRoundData = new BlockRoundData(block.getHeader().getExtend()); if (blockRoundData.getRoundIndex() == round.getIndex()) { nextRoundFirstBlock = block; break; } } } calcHeight = nextRoundFirstBlock.getHeader().getHeight() - PocConsensusConstant.CONFIRM_BLOCK_COUNT - 1; } } List<PocMeetingMember> memberList = getMemberList(calcHeight, round, bestBlockHeader); Collections.sort(memberList); round.setMemberList(memberList); round.setMemberCount(memberList.size()); while (round.getEndTime() < TimeService.currentTimeMillis()) { long time = TimeService.currentTimeMillis() - round.getStartTime(); long roundTime = round.getEndTime() - round.getStartTime(); long index = time / roundTime; long startTime = round.getStartTime() + index * roundTime; round.setStartTime(startTime); round.setIndex(bestRoundData.getRoundIndex() + index); } for(PocMeetingMember member:memberList){ member.setRoundIndex(round.getIndex()); member.setRoundStartTime(round.getStartTime()); } return round; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Result<Balance> getBalance(byte[] address) throws NulsException { if (address == null || address.length != AddressTool.HASH_LENGTH) { return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR); } if (!isLocalAccount(address)) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } Balance balance = balanceProvider.getBalance(address).getData(); if (balance == null) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } return Result.getSuccess().setData(balance); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Result<Balance> getBalance(byte[] address) throws NulsException { if (address == null || address.length != AddressTool.HASH_LENGTH) { return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR); } if (!isLocalAccount(address)) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } Balance balance = balanceManager.getBalance(address).getData(); if (balance == null) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } return Result.getSuccess().setData(balance); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean processingBifurcation(long height) { return this.bifurcateProcessor.processing(height); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean processingBifurcation(long height) { lock.lock(); try { return this.bifurcateProcessor.processing(height); } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static UtxoOutputPo toOutputPojo(UtxoOutput output) { UtxoOutputPo po = new UtxoOutputPo(); po.setTxHash(output.getTxHash().getDigestHex()); po.setOutIndex(output.getIndex()); po.setValue(output.getValue()); po.setLockTime(output.getLockTime()); po.setAddress(Address.fromHashs(output.getAddress()).getBase58()); if(null==output.getScript()){ po.setScript(output.getScript().getBytes()); } po.setStatus((byte) output.getStatus()); return po; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static UtxoOutputPo toOutputPojo(UtxoOutput output) { UtxoOutputPo po = new UtxoOutputPo(); po.setTxHash(output.getTxHash().getDigestHex()); po.setOutIndex(output.getIndex()); po.setValue(output.getValue()); po.setLockTime(output.getLockTime()); po.setAddress(Address.fromHashs(output.getAddress()).getBase58()); if(null!=output.getScript()){ po.setScript(output.getScript().getBytes()); } po.setStatus((byte) output.getStatus()); return po; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult validate(AbstractCoinTransaction tx) { UtxoData data = (UtxoData) tx.getCoinData(); for (int i = 0; i < data.getInputs().size(); i++) { UtxoInput input = data.getInputs().get(i); UtxoOutput output = input.getFrom(); if (output == null && tx.getStatus() == TxStatusEnum.CACHED) { return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } if (tx.getStatus() == TxStatusEnum.CACHED) { if (!output.isUsable()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } else if (tx.getStatus() == TxStatusEnum.AGREED) { if (!output.isSpend()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } byte[] owner = output.getOwner(); P2PKHScriptSig p2PKHScriptSig = null; try { p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig()); } catch (NulsException e) { return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR); } byte[] user = p2PKHScriptSig.getSignerHash160(); if (!Arrays.equals(owner, user)) { return ValidateResult.getFailedResult(ErrorCode.INVALID_OUTPUT); } return ValidateResult.getSuccessResult(); } return ValidateResult.getSuccessResult(); } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ValidateResult validate(AbstractCoinTransaction tx) { UtxoData data = (UtxoData) tx.getCoinData(); for (int i = 0; i < data.getInputs().size(); i++) { UtxoInput input = data.getInputs().get(i); UtxoOutput output = input.getFrom(); if (output == null && tx.getStatus() == TxStatusEnum.CACHED) { return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } else if (output == null) { return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND); } if (tx.getStatus() == TxStatusEnum.CACHED) { if (!output.isUsable()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } else if (tx.getStatus() == TxStatusEnum.AGREED) { if (!output.isSpend()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } byte[] owner = output.getOwner(); P2PKHScriptSig p2PKHScriptSig = null; try { p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig()); } catch (NulsException e) { return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR); } byte[] user = p2PKHScriptSig.getSignerHash160(); if (!Arrays.equals(owner, user)) { return ValidateResult.getFailedResult(ErrorCode.INVALID_OUTPUT); } return ValidateResult.getSuccessResult(); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BlockInfo request(long height, List<String> sendList) { return this.request(height, height, 1,nodeIdList); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public BlockInfo request(long height, List<String> sendList) { return this.request(height, height, 1, sendList); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void cacheBlockToBuffer(Block block) { blockCacheBuffer.cacheBlock(block); BlockLog.info("orphan cache block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress())); Block preBlock = blockCacheBuffer.getBlock(block.getHeader().getPreHash().getDigestHex()); if (preBlock == null) { if (NulsContext.getServiceBean(DownloadService.class).getStatus() != DownloadStatus.DOWNLOADING) { downloadUtils.getBlockByHash(block.getHeader().getPreHash().getDigestHex()); } } else { this.addBlock(preBlock, true, null); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private void cacheBlockToBuffer(Block block) { blockCacheBuffer.cacheBlock(block); BlockLog.info("orphan cache block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress())); Block preBlock = blockCacheBuffer.getBlock(block.getHeader().getPreHash().getDigestHex()); if (preBlock == null) { if (this.downloadService.getStatus() != DownloadStatus.DOWNLOADING) { downloadUtils.getBlockByHash(block.getHeader().getPreHash().getDigestHex()); } } else { this.addBlock(preBlock, true, null); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void addTx(Block block) { BlockHeader blockHeader = block.getHeader(); List<Transaction> txs = block.getTxs(); Transaction<Agent> agentTx = new CreateAgentTransaction(); Agent agent = new Agent(); agent.setPackingAddress(AddressTool.getAddress(ecKey.getPubKey())); agent.setAgentAddress(AddressTool.getAddress(ecKey.getPubKey())); agent.setTime(System.currentTimeMillis()); agent.setDeposit(Na.NA.multiply(20000)); agent.setAgentName("test".getBytes()); agent.setIntroduction("test agent".getBytes()); agent.setCommissionRate(0.3d); agent.setBlockHeight(blockHeader.getHeight()); agentTx.setTxData(agent); agentTx.setTime(agent.getTime()); agentTx.setBlockHeight(blockHeader.getHeight()); NulsSignData signData = null; try { signData = accountService.signData(agentTx.getHash().getDigestBytes(), ecKey); } catch (NulsException e) { e.printStackTrace(); } agentTx.setScriptSig(signData.getSignBytes()); // add the agent tx into agent list txs.add(agentTx); // new a deposit Deposit deposit = new Deposit(); deposit.setAddress(AddressTool.getAddress(ecKey.getPubKey())); deposit.setAgentHash(agentTx.getHash()); deposit.setTime(System.currentTimeMillis()); deposit.setDeposit(Na.NA.multiply(200000)); deposit.setBlockHeight(blockHeader.getHeight()); DepositTransaction depositTx = new DepositTransaction(); depositTx.setTime(deposit.getTime()); depositTx.setTxData(deposit); depositTx.setBlockHeight(blockHeader.getHeight()); txs.add(depositTx); } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code protected void addTx(Block block) { BlockHeader blockHeader = block.getHeader(); List<Transaction> txs = block.getTxs(); Transaction<Agent> agentTx = new CreateAgentTransaction(); Agent agent = new Agent(); agent.setPackingAddress(AddressTool.getAddress(ecKey.getPubKey())); agent.setAgentAddress(AddressTool.getAddress(ecKey.getPubKey())); agent.setTime(System.currentTimeMillis()); agent.setDeposit(Na.NA.multiply(20000)); agent.setAgentName("test".getBytes()); agent.setIntroduction("test agent".getBytes()); agent.setCommissionRate(0.3d); agent.setBlockHeight(blockHeader.getHeight()); agentTx.setTxData(agent); agentTx.setTime(agent.getTime()); agentTx.setBlockHeight(blockHeader.getHeight()); NulsSignData signData = signDigest(agentTx.getHash().getDigestBytes(), ecKey); agentTx.setScriptSig(signData.getSignBytes()); // add the agent tx into agent list txs.add(agentTx); // new a deposit Deposit deposit = new Deposit(); deposit.setAddress(AddressTool.getAddress(ecKey.getPubKey())); deposit.setAgentHash(agentTx.getHash()); deposit.setTime(System.currentTimeMillis()); deposit.setDeposit(Na.NA.multiply(200000)); deposit.setBlockHeight(blockHeader.getHeight()); DepositTransaction depositTx = new DepositTransaction(); depositTx.setTime(deposit.getTime()); depositTx.setTxData(deposit); depositTx.setBlockHeight(blockHeader.getHeight()); txs.add(depositTx); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void newTx() throws Exception { assertNotNull(service); // new a tx Transaction tx = new TestTransaction(); CoinData coinData = new CoinData(); List<Coin> fromList = new ArrayList<>(); fromList.add(new Coin(new byte[20], Na.NA, 0L)); coinData.setFrom(fromList); tx.setCoinData(coinData); tx.setTime(1l); assertNotNull(tx); assertNotNull(tx.getHash()); assertEquals(tx.getHash().getDigestHex(), "08001220b9ab6a1e5ab8e2b09758d6143bb9b66b8fe0c2c4bf49f2bfb74709ef2bf1d02f"); Result result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); //test orphan NulsDataValidator<TestTransaction> testValidator = new NulsDataValidator<TestTransaction>() { @Override public ValidateResult validate(TestTransaction data) { if (data.getHash().getDigestHex().equals("08001220328876d03b50feba0ac58d3fcb4638a2fb95847315a88c8de7105408d931999a")) { return ValidateResult.getFailedResult("test.transaction", TransactionErrorCode.ORPHAN_TX); } else { return ValidateResult.getSuccessResult(); } } }; ValidatorManager.addValidator(TestTransaction.class, testValidator); tx = new TestTransaction(); tx.setTime(2l); result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); List<Transaction> list = TxMemoryPool.getInstance().getAll(); assertNotNull(list); assertEquals(list.size(), 1); List<Transaction> orphanList = TxMemoryPool.getInstance().getAllOrphan(); assertNotNull(orphanList); assertEquals(orphanList.size(), 1); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void newTx() throws Exception { assertNotNull(service); // new a tx Transaction tx = new TestTransaction(); CoinData coinData = new CoinData(); List<Coin> fromList = new ArrayList<>(); fromList.add(new Coin(new byte[20], Na.NA, 0L)); coinData.setFrom(fromList); tx.setCoinData(coinData); tx.setTime(1l); assertNotNull(tx); assertNotNull(tx.getHash()); assertEquals(tx.getHash().getDigestHex(), "00204a54f8b12b75c3c1fe5f261416adaf1a1b906ccf5673bb7a133ede5a0a4c56f8"); Result result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); //test orphan NulsDataValidator<TestTransaction> testValidator = new NulsDataValidator<TestTransaction>() { @Override public ValidateResult validate(TestTransaction data) { if (data.getHash().getDigestHex().equals("0020e27ee243921bf482d7b62b6ee63c7ab1938953c834318b79fa3204c5c869e26b")) { return ValidateResult.getFailedResult("test.transaction", TransactionErrorCode.ORPHAN_TX); } else { return ValidateResult.getSuccessResult(); } } }; ValidatorManager.addValidator(TestTransaction.class, testValidator); tx = new TestTransaction(); tx.setTime(2l); assertEquals(tx.getHash().getDigestHex(), "0020e27ee243921bf482d7b62b6ee63c7ab1938953c834318b79fa3204c5c869e26b"); result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); List<Transaction> list = TxMemoryPool.getInstance().getAll(); assertNotNull(list); assertEquals(list.size(), 1); List<Transaction> orphanList = TxMemoryPool.getInstance().getAllOrphan(); assertNotNull(orphanList); assertEquals(orphanList.size(), 1); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void checkCache() { if (null == blockService) { blockService = NulsContext.getServiceBean(BlockService.class); } Block block = blockService.getBlock(blockService.getLocalSavedHeight()); boolean b = (TimeService.currentTimeMillis() - startTime) > 300000; b = b && (TimeService.currentTimeMillis() - block.getHeader().getTime()) > 300000; if (b) { ConsensusManager consensusManager = ConsensusManager.getInstance(); consensusManager.destroy(); NulsContext.getInstance().setBestBlock(blockService.getBlock(blockService.getLocalSavedHeight())); this.startTime = TimeService.currentTimeMillis(); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private void checkCache() { // if (null == blockService) { // blockService = NulsContext.getServiceBean(BlockService.class); // } // Block block = blockService.getBlock(blockService.getLocalSavedHeight()); // boolean b = (TimeService.currentTimeMillis() - startTime) > 300000; // b = b && (TimeService.currentTimeMillis() - block.getHeader().getTime()) > 300000; // if (b) { // ConsensusManager consensusManager = ConsensusManager.getInstance(); // consensusManager.destroy(); // this.startTime = TimeService.currentTimeMillis(); // } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash160().length > 25) { return ValidateResult.getFailedResult("The address format error"); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult("The alias is between 3 to 20 characters"); } AliasPo aliasPo = aliasDataService.get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult("The alias has been occupied"); } return ValidateResult.getSuccessResult(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length !=23 ) { return ValidateResult.getFailedResult("The address format error"); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult("The alias is between 3 to 20 characters"); } AliasPo aliasPo = aliasDataService.get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult("The alias has been occupied"); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void init() { cacheService = LedgerCacheService.getInstance(); registerService(); ledgerService = NulsContext.getServiceBean(LedgerService.class); coinManager = UtxoCoinManager.getInstance(); UtxoOutputDataService outputDataService = NulsContext. getServiceBean(UtxoOutputDataService.class); coinManager.setOutputDataService(outputDataService); ledgerService.init(); addNormalTxValidator(); UtxoCoinDataProvider provider = NulsContext.getServiceBean(UtxoCoinDataProvider.class); provider.setInputDataService(NulsContext.getServiceBean(UtxoInputDataService.class)); provider.setOutputDataService(outputDataService); this.registerTransaction(TransactionConstant.TX_TYPE_COIN_BASE, CoinBaseTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_TRANSFER, TransferTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_UNLOCK, UnlockNulsTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_LOCK, LockNulsTransaction.class, CoinDataTxService.getInstance()); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void init() { cacheService = LedgerCacheService.getInstance(); registerService(); ledgerService = NulsContext.getServiceBean(LedgerService.class); coinManager = UtxoCoinManager.getInstance(); UtxoOutputDataService outputDataService = NulsContext.getServiceBean(UtxoOutputDataService.class); coinManager.setOutputDataService(outputDataService); addNormalTxValidator(); this.registerTransaction(TransactionConstant.TX_TYPE_COIN_BASE, CoinBaseTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_TRANSFER, TransferTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_UNLOCK, UnlockNulsTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_LOCK, LockNulsTransaction.class, CoinDataTxService.getInstance()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void init(Map<String, String> initParams) { String dataBaseType = null; if(initParams.get("dataBaseType") != null) { dataBaseType = initParams.get("dataBaseType"); } if (!StringUtils.isEmpty(dataBaseType) && hasType(dataBaseType)) { String path = "classpath:/database-" + dataBaseType + ".xml"; NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext())); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void init(Map<String, String> initParams) { String databaseType = null; if(initParams.get("databaseType") != null) { databaseType = initParams.get("databaseType"); } if (!StringUtils.isEmpty(databaseType) && hasType(databaseType)) { String path = "classpath:/database-" + databaseType + ".xml"; NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void start() { getNetworkStorage().init(); List<Node> nodeList = getNetworkStorage().getLocalNodeList(20); nodeList.addAll(getSeedNodes()); for (Node node : nodeList) { addNode(node); } running = true; TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this); nodeDiscoverHandler.start(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void start() { List<Node> nodeList = getNetworkStorage().getLocalNodeList(20); nodeList.addAll(getSeedNodes()); for (Node node : nodeList) { addNode(node); } running = true; TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this); nodeDiscoverHandler.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean resetSystem(String reason) { if ((TimeService.currentTimeMillis() - lastResetTime) <= INTERVAL_TIME) { Log.info("system reset interrupt!"); return true; } Log.info("---------------reset start----------------"); Log.info("Received a reset system request, reason: 【" + reason + "】"); NetworkService networkService = NulsContext.getServiceBean(NetworkService.class); networkService.reset(); DownloadService downloadService = NulsContext.getServiceBean(DownloadService.class); downloadService.reset(); NulsContext.getServiceBean(LedgerService.class).resetLedgerCache(); ConsensusMeetingRunner consensusMeetingRunner = ConsensusMeetingRunner.getInstance(); consensusMeetingRunner.resetConsensus(); Log.info("---------------reset end----------------"); this.lastResetTime = TimeService.currentTimeMillis(); return true; } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean resetSystem(String reason) { if ((TimeService.currentTimeMillis() - lastResetTime) <= INTERVAL_TIME) { Log.info("system reset interrupt!"); return true; } Log.info("---------------reset start----------------"); Log.info("Received a reset system request, reason: 【" + reason + "】"); NetworkService networkService = NulsContext.getServiceBean(NetworkService.class); networkService.reset(); DownloadService downloadService = NulsContext.getServiceBean(DownloadService.class); downloadService.reset(); ConsensusManager.getInstance().clearCache(); Log.info("---------------reset end----------------"); this.lastResetTime = TimeService.currentTimeMillis(); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HeaderDigest getLastHd() { if(null==lastHd){ List<HeaderDigest> list = new ArrayList<>(headerDigestList); this.lastHd = list.get(list.size()-1); } return lastHd; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public HeaderDigest getLastHd() { if (null == lastHd) { List<HeaderDigest> list = new ArrayList<>(headerDigestList); this.lastHd = list.get(list.size() - 1); } return lastHd; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public NetworkEventResult process(BaseEvent event, Node node) { GetNodeEvent getNodeEvent = (GetNodeEvent) event; String key = event.getHeader().getEventType() + "-" + node.getIp(); if (cacheService.existEvent(key)) { getNetworkService().removeNode(node.getId()); return null; } cacheService.putEvent(key, event, false); List<Node> list = getAvailableNodes(getNodeEvent.getLength(), node.getId()); NodeEvent replyEvent = new NodeEvent(list); return new NetworkEventResult(true, replyEvent); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public NetworkEventResult process(BaseEvent event, Node node) { GetNodeEvent getNodeEvent = (GetNodeEvent) event; // String key = event.getHeader().getEventType() + "-" + node.getIp(); // if (cacheService.existEvent(key)) { // getNetworkService().removeNode(node.getId()); // return null; // } // cacheService.putEvent(key, event, false); List<Node> list = getAvailableNodes(getNodeEvent.getLength(), node.getId()); NodeEvent replyEvent = new NodeEvent(list); return new NetworkEventResult(true, replyEvent); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start() { List<Account> accounts = getAccountList(); Set<String> addressList = new HashSet<>(); if (accounts != null && !accounts.isEmpty()) { NulsContext.DEFAULT_ACCOUNT_ID = accounts.get(0).getAddress().getBase58(); for (Account account : accounts) { addressList.add(account.getAddress().getBase58()); } NulsContext.LOCAL_ADDRESS_LIST = addressList; } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void start() { getAccountList(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HeaderDigest getLastHd() { if (null == lastHd) { List<HeaderDigest> list = new ArrayList<>(headerDigestList); if(list.size() > 0) { this.lastHd = list.get(list.size() - 1); } } return lastHd; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public HeaderDigest getLastHd() { List<HeaderDigest> list = new ArrayList<>(headerDigestList); if (list.size() > 0) { return list.get(list.size() - 1); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean processing(long height) { if (chainList.isEmpty()) { return false; } this.checkIt(); if (null == approvingChain) { return false; } if (approvingChain.getLastHd() != null && approvingChain.getLastHd().getHeight() >= (height + PocConsensusConstant.CONFIRM_BLOCK_COUNT)) { return true; } return false; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean processing(long height) { if (chainList.isEmpty()) { return false; } this.checkIt(); if (null == approvingChain) { return false; } Set<HeaderDigest> removeHashSet = new HashSet<>(); for (int i = chainList.size() - 1; i >= 0; i--) { BlockHeaderChain chain = chainList.get(i); if (chain.size() < (approvingChain.size() - 6)) { removeHashSet.addAll(chain.getHeaderDigestList()); this.chainList.remove(chain); } } for (HeaderDigest hd : removeHashSet) { if (!approvingChain.contains(hd)) { confirmingBlockCacheManager.removeBlock(hd.getHash()); } } if (approvingChain.getLastHd() != null && approvingChain.getLastHd().getHeight() >= (height + PocConsensusConstant.CONFIRM_BLOCK_COUNT)) { return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult validate(AbstractCoinTransaction tx) { UtxoData data = (UtxoData) tx.getCoinData(); for (int i = 0; i < data.getInputs().size(); i++) { UtxoInput input = data.getInputs().get(i); UtxoOutput output = input.getFrom(); if (output == null && tx.getStatus() == TxStatusEnum.CACHED) { return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } if (tx.getStatus() == TxStatusEnum.CACHED) { if (!output.isUsable()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } else if (tx.getStatus() == TxStatusEnum.AGREED) { if (!output.isSpend()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } byte[] owner = output.getOwner(); P2PKHScriptSig p2PKHScriptSig = null; try { p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig()); } catch (NulsException e) { return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR); } byte[] user = p2PKHScriptSig.getSignerHash160(); if (!Arrays.equals(owner, user)) { return ValidateResult.getFailedResult(ErrorCode.INVALID_OUTPUT); } return ValidateResult.getSuccessResult(); } return ValidateResult.getSuccessResult(); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ValidateResult validate(AbstractCoinTransaction tx) { UtxoData data = (UtxoData) tx.getCoinData(); for (int i = 0; i < data.getInputs().size(); i++) { UtxoInput input = data.getInputs().get(i); UtxoOutput output = input.getFrom(); if (output == null && tx.getStatus() == TxStatusEnum.CACHED) { return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } else if (output == null) { return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND); } if (tx.getStatus() == TxStatusEnum.CACHED) { if (!output.isUsable()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } else if (tx.getStatus() == TxStatusEnum.AGREED) { if (!output.isSpend()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } byte[] owner = output.getOwner(); P2PKHScriptSig p2PKHScriptSig = null; try { p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig()); } catch (NulsException e) { return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR); } byte[] user = p2PKHScriptSig.getSignerHash160(); if (!Arrays.equals(owner, user)) { return ValidateResult.getFailedResult(ErrorCode.INVALID_OUTPUT); } return ValidateResult.getSuccessResult(); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @PluginFactory public static <S extends Serializable> SyslogAppender<S> createAppender(@PluginAttr("host") final String host, @PluginAttr("port") final String portNum, @PluginAttr("protocol") final String protocol, @PluginAttr("reconnectionDelay") final String delay, @PluginAttr("immediateFail") final String immediateFail, @PluginAttr("name") final String name, @PluginAttr("immediateFlush") final String immediateFlush, @PluginAttr("suppressExceptions") final String suppress, @PluginAttr("facility") final String facility, @PluginAttr("id") final String id, @PluginAttr("enterpriseNumber") final String ein, @PluginAttr("includeMDC") final String includeMDC, @PluginAttr("mdcId") final String mdcId, @PluginAttr("mdcPrefix") final String mdcPrefix, @PluginAttr("eventPrefix") final String eventPrefix, @PluginAttr("newLine") final String includeNL, @PluginAttr("newLineEscape") final String escapeNL, @PluginAttr("appName") final String appName, @PluginAttr("messageId") final String msgId, @PluginAttr("mdcExcludes") final String excludes, @PluginAttr("mdcIncludes") final String includes, @PluginAttr("mdcRequired") final String required, @PluginAttr("format") final String format, @PluginElement("filters") final Filter filter, @PluginConfiguration final Configuration config, @PluginAttr("charset") final String charsetName, @PluginAttr("exceptionPattern") final String exceptionPattern, @PluginElement("LoggerFields") final LoggerFields loggerFields, @PluginAttr("advertise") final String advertise) { final boolean isFlush = immediateFlush == null ? true : Boolean.valueOf(immediateFlush); final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress); final int reconnectDelay = delay == null ? 0 : Integer.parseInt(delay); final boolean fail = immediateFail == null ? true : Boolean.valueOf(immediateFail); final int port = portNum == null ? 0 : Integer.parseInt(portNum); final boolean isAdvertise = advertise == null ? false : Boolean.valueOf(advertise); @SuppressWarnings("unchecked") final Layout<S> layout = (Layout<S>) (RFC5424.equalsIgnoreCase(format) ? RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, mdcPrefix, eventPrefix, includeNL, escapeNL, appName, msgId, excludes, includes, required, exceptionPattern, loggerFields, config) : SyslogLayout.createLayout(facility, includeNL, escapeNL, charsetName)); if (name == null) { LOGGER.error("No name provided for SyslogAppender"); return null; } final String prot = protocol != null ? protocol : Protocol.UDP.name(); final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol); final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout); if (manager == null) { return null; } return new SyslogAppender<S>(name, layout, filter, handleExceptions, isFlush, manager, isAdvertise ? config.getAdvertiser() : null); } #location 50 #vulnerability type NULL_DEREFERENCE
#fixed code @PluginFactory public static <S extends Serializable> SyslogAppender<S> createAppender(@PluginAttr("host") final String host, @PluginAttr("port") final String portNum, @PluginAttr("protocol") final String protocol, @PluginAttr("reconnectionDelay") final String delay, @PluginAttr("immediateFail") final String immediateFail, @PluginAttr("name") final String name, @PluginAttr("immediateFlush") final String immediateFlush, @PluginAttr("suppressExceptions") final String suppress, @PluginAttr("facility") final String facility, @PluginAttr("id") final String id, @PluginAttr("enterpriseNumber") final String ein, @PluginAttr("includeMDC") final String includeMDC, @PluginAttr("mdcId") final String mdcId, @PluginAttr("mdcPrefix") final String mdcPrefix, @PluginAttr("eventPrefix") final String eventPrefix, @PluginAttr("newLine") final String includeNL, @PluginAttr("newLineEscape") final String escapeNL, @PluginAttr("appName") final String appName, @PluginAttr("messageId") final String msgId, @PluginAttr("mdcExcludes") final String excludes, @PluginAttr("mdcIncludes") final String includes, @PluginAttr("mdcRequired") final String required, @PluginAttr("format") final String format, @PluginElement("filters") final Filter filter, @PluginConfiguration final Configuration config, @PluginAttr("charset") final String charsetName, @PluginAttr("exceptionPattern") final String exceptionPattern, @PluginElement("LoggerFields") final LoggerFields loggerFields, @PluginAttr("advertise") final String advertise) { final boolean isFlush = immediateFlush == null ? true : Boolean.valueOf(immediateFlush); final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress); final int reconnectDelay = Integers.parseInt(delay); final boolean fail = immediateFail == null ? true : Boolean.valueOf(immediateFail); final int port = Integers.parseInt(portNum); final boolean isAdvertise = advertise == null ? false : Boolean.valueOf(advertise); @SuppressWarnings("unchecked") final Layout<S> layout = (Layout<S>) (RFC5424.equalsIgnoreCase(format) ? RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, mdcPrefix, eventPrefix, includeNL, escapeNL, appName, msgId, excludes, includes, required, exceptionPattern, loggerFields, config) : SyslogLayout.createLayout(facility, includeNL, escapeNL, charsetName)); if (name == null) { LOGGER.error("No name provided for SyslogAppender"); return null; } final String prot = protocol != null ? protocol : Protocol.UDP.name(); final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol); final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout); if (manager == null) { return null; } return new SyslogAppender<S>(name, layout, filter, handleExceptions, isFlush, manager, isAdvertise ? config.getAdvertiser() : null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static OutputStream getOutputStream(final boolean follow, final Target target) { final PrintStream printStream = target == Target.SYSTEM_OUT ? follow ? new PrintStream(new SystemOutStream()) : System.out : follow ? new PrintStream(new SystemErrStream()) : System.err; if (!System.getProperty("os.name").startsWith("Windows") || Boolean.getBoolean("log4j.skipJansi")) { return printStream; } else { try { final ClassLoader loader = Loader.getClassLoader(); // We type the parameter as a wildcard to avoid a hard reference to Jansi. final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream"); final Constructor<?> constructor = clazz.getConstructor(OutputStream.class); return (OutputStream) constructor.newInstance(printStream); } catch (final ClassNotFoundException cnfe) { LOGGER.debug("Jansi is not installed"); } catch (final NoSuchMethodException nsme) { LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor"); } catch (final Exception ex) { LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream"); } return printStream; } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private static OutputStream getOutputStream(final boolean follow, final Target target) { final PrintStream printStream = target == Target.SYSTEM_OUT ? follow ? new PrintStream(new SystemOutStream()) : System.out : follow ? new PrintStream(new SystemErrStream()) : System.err; PropertiesUtil propsUtil = PropertiesUtil.getProperties(); if (!propsUtil.getStringProperty("os.name").startsWith("Windows") || propsUtil.getBooleanProperty("log4j.skipJansi")) { return printStream; } else { try { final ClassLoader loader = Loader.getClassLoader(); // We type the parameter as a wildcard to avoid a hard reference to Jansi. final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream"); final Constructor<?> constructor = clazz.getConstructor(OutputStream.class); return (OutputStream) constructor.newInstance(printStream); } catch (final ClassNotFoundException cnfe) { LOGGER.debug("Jansi is not installed"); } catch (final NoSuchMethodException nsme) { LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor"); } catch (final Exception ex) { LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream"); } return printStream; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAppender() throws Exception { for (int i = 0; i < 8; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); for (final File file : files) { assertHeader(file); assertFooter(file); } final File logFile = new File(LOGFILE); assertTrue("Expected logfile to exist: " + LOGFILE, logFile.exists()); assertHeader(logFile); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAppender() throws Exception { for (int i = 0; i < 8; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); for (final File file : files) { assertHeader(file); assertFooter(file); } final File logFile = new File(LOGFILE); assertThat(logFile, exists()); assertHeader(logFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void releaseSub() { if (rpcClient != null) { try { rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void releaseSub() { if (rpcClient != null) { try { synchronized(this) { try { if (batchSize > 1 && batchEvent.getEvents().size() > 0) { send(batchEvent); } } catch (final Exception ex) { LOGGER.error("Error sending final batch: {}", ex.getMessage()); } } rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush) { if (socket == null) { if (connector != null && !immediateFail) { connector.latch(); } if (socket == null) { final String msg = "Error writing to " + getName() + " socket not available"; throw new AppenderLoggingException(msg); } } synchronized (this) { try { final OutputStream outputStream = getOutputStream(); outputStream.write(bytes, offset, length); if (immediateFlush) { outputStream.flush(); } } catch (final IOException ex) { if (retry && connector == null) { connector = new Reconnector(this); connector.setDaemon(true); connector.setPriority(Thread.MIN_PRIORITY); connector.start(); } final String msg = "Error writing to " + getName(); throw new AppenderLoggingException(msg, ex); } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush) { if (socket == null) { if (reconnector != null && !immediateFail) { reconnector.latch(); } if (socket == null) { final String msg = "Error writing to " + getName() + " socket not available"; throw new AppenderLoggingException(msg); } } synchronized (this) { try { final OutputStream outputStream = getOutputStream(); outputStream.write(bytes, offset, length); if (immediateFlush) { outputStream.flush(); } } catch (final IOException ex) { if (retry && reconnector == null) { reconnector = new Reconnector(this); reconnector.setDaemon(true); reconnector.setPriority(Thread.MIN_PRIORITY); reconnector.start(); } final String msg = "Error writing to " + getName(); throw new AppenderLoggingException(msg, ex); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerFilterOutputStream los = new LoggerFilterOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void copyFile(final File source, final File destination) throws IOException { if (!destination.exists()) { destination.createNewFile(); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); destChannel = new FileOutputStream(destination).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if(srcChannel != null) { srcChannel.close(); } if (destChannel != null) { destChannel.close(); } } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private static void copyFile(final File source, final File destination) throws IOException { if (!destination.exists()) { destination.createNewFile(); } FileChannel srcChannel = null; FileChannel destChannel = null; FileInputStream srcStream = null; FileOutputStream destStream = null; try { srcStream = new FileInputStream(source); destStream = new FileOutputStream(destination); srcChannel = srcStream.getChannel(); destChannel = destStream.getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if(srcChannel != null) { srcChannel.close(); } if (srcStream != null) { srcStream.close(); } if (destChannel != null) { destChannel.close(); } if (destStream != null) { destStream.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void forcedLog(String fqcn, Priority level, Object message, Throwable t) { org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); logger.log(null, fqcn, lvl, new ObjectMessage(message), t); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void forcedLog(String fqcn, Priority level, Object message, Throwable t) { org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); Message msg = message instanceof Message ? (ObjectMessage) message : new ObjectMessage(message); logger.log(null, fqcn, lvl, msg, t); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void addScript(Script script) { ScriptEngine engine = manager.getEngineByName(script.getLanguage()); if (engine == null) { logger.error("No ScriptEngine found for language " + script.getLanguage()); } if (engine.getFactory().getParameter("THREADING") == null) { scripts.put(script.getName(), new ThreadLocalScriptRunner(script)); } else { scripts.put(script.getName(), new MainScriptRunner(engine, script)); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public void addScript(Script script) { ScriptEngine engine = manager.getEngineByName(script.getLanguage()); if (engine == null) { logger.error("No ScriptEngine found for language " + script.getLanguage() + ". Available languages are: " + languages); return; } if (engine.getFactory().getParameter("THREADING") == null) { scripts.put(script.getName(), new ThreadLocalScriptRunner(script)); } else { scripts.put(script.getName(), new MainScriptRunner(engine, script)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); Logger logger = LogManager.getLogger(); if (!(logger instanceof AsyncLogger)) { throw new IllegalStateException(); } logger.info("Starting..."); Thread.sleep(100); final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); // warmup final int ITERATIONS = 100000; long startMs = System.currentTimeMillis(); long end = startMs + TimeUnit.SECONDS.toMillis(10); long total = 0; int count = 0; StringBuilder sb = new StringBuilder(512); do { sb.setLength(0); long startNanos = System.nanoTime(); long uptime = runtimeMXBean.getUptime(); loop(logger, ITERATIONS); long endNanos = System.nanoTime(); long durationNanos = endNanos - startNanos; final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos; sb.append(uptime).append(" Warmup: Throughput: ").append(opsPerSec).append(" ops/s"); System.out.println(sb); total += opsPerSec; count++; // Thread.sleep(1000);// drain buffer } while (System.currentTimeMillis() < end); System.out.printf("Average warmup throughput: %,d ops/s%n", total/count); final int COUNT = 10; final long[] durationNanos = new long[10]; for (int i = 0; i < COUNT; i++) { final long startNanos = System.nanoTime(); loop(logger, ITERATIONS); long endNanos = System.nanoTime(); durationNanos[i] = endNanos - startNanos; // Thread.sleep(1000);// drain buffer } total = 0; for (int i = 0; i < COUNT; i++) { final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos[i]; System.out.printf("Throughput: %,d ops/s%n", opsPerSec); total += opsPerSec; } System.out.printf("Average throughput: %,d ops/s%n", total/COUNT); } #location 34 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code public static void main(String[] args) throws Exception { System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); Logger logger = LogManager.getLogger(); if (!(logger instanceof AsyncLogger)) { throw new IllegalStateException(); } // work around a bug in Log4j-2.5 workAroundLog4j2_5Bug(); logger.error("Starting..."); System.out.println("Starting..."); Thread.sleep(100); final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); final long testStartNanos = System.nanoTime(); final long[] UPTIMES = new long[1024]; final long[] DURATIONS = new long[1024]; // warmup long startMs = System.currentTimeMillis(); long end = startMs + TimeUnit.SECONDS.toMillis(10); int warmupCount = 0; do { runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, warmupCount); warmupCount++; // Thread.sleep(1000);// drain buffer } while (System.currentTimeMillis() < end); final int COUNT = 10; for (int i = 0; i < COUNT; i++) { int count = warmupCount + i; runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, count); // Thread.sleep(1000);// drain buffer } double testDurationNanos = System.nanoTime() - testStartNanos; System.out.println("Done. Calculating stats..."); printReport("Warmup", UPTIMES, DURATIONS, 0, warmupCount); printReport("Test", UPTIMES, DURATIONS, warmupCount, COUNT); StringBuilder sb = new StringBuilder(512); sb.append("Test took: ").append(testDurationNanos/(1000.0*1000.0*1000.0)).append(" sec"); System.out.println(sb); final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (int i = 0; i < gcBeans.size(); i++) { GarbageCollectorMXBean gcBean = gcBeans.get(i); sb.setLength(0); sb.append("GC[").append(gcBean.getName()).append("] "); sb.append(gcBean.getCollectionCount()).append(" collections, collection time="); sb.append(gcBean.getCollectionTime()).append(" millis."); System.out.println(sb); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAppender() throws Exception { final Logger logger = ctx.getLogger(); logger.debug("This is test message number 1"); Thread.sleep(1500); // Trigger the rollover for (int i = 0; i < 16; ++i) { logger.debug("This is test message number " + i + 1); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final int MAX_TRIES = 20; for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); for (final File file : files) { if (file.getName().endsWith(".gz")) { return; // test succeeded } } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No compressed files found"); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAppender() throws Exception { final Logger logger = ctx.getLogger(); logger.debug("This is test message number 1"); Thread.sleep(1500); // Trigger the rollover for (int i = 0; i < 16; ++i) { logger.debug("This is test message number " + i + 1); } final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final int MAX_TRIES = 20; final Matcher<File[]> hasGzippedFile = hasItemInArray(that(hasName(that(endsWith(".gz"))))); for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); if (hasGzippedFile.matches(files)) { return; // test succeeded } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No compressed files found"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toSerializable(final LogEvent event) { final Message message = event.getMessage(); final Object[] parameters = message.getParameters(); final StringBuilder buffer = prepareStringBuilder(strBuilder); try { // Revisit when 1.3 is out so that we do not need to create a new // printer for each event. // No need to close the printer. final CSVPrinter printer = new CSVPrinter(buffer, getFormat()); printer.printRecord(parameters); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(message, e); return getFormat().getCommentMarker() + " " + e; } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String toSerializable(final LogEvent event) { final Message message = event.getMessage(); final Object[] parameters = message.getParameters(); final StringBuilder buffer = getStringBuilder(); // Revisit when 1.3 is out so that we do not need to create a new // printer for each event. // No need to close the printer. try (final CSVPrinter printer = new CSVPrinter(buffer, getFormat())) { printer.printRecord(parameters); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(message, e); return getFormat().getCommentMarker() + " " + e; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean hasFilters() { return hasFilters; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean hasFilters() { return filters.hasFilters(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void releaseSub() { if (rpcClient != null) { try { rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void releaseSub() { if (rpcClient != null) { try { synchronized(this) { try { if (batchSize > 1 && batchEvent.getEvents().size() > 0) { send(batchEvent); } } catch (final Exception ex) { LOGGER.error("Error sending final batch: {}", ex.getMessage()); } } rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void logToFile() throws Exception { final FileOutputStream fos = new FileOutputStream(LOGFILE, false); fos.flush(); fos.close(); final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test"); logger.debug("This is a test"); final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE))); int count = 0; String str = ""; while (is.available() != 0) { str = is.readLine(); ++count; } assertTrue("Incorrect count " + count, count == 1); assertTrue("Bad data", str.endsWith("This is a test")); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void logToFile() throws Exception { final FileOutputStream fos = new FileOutputStream(LOGFILE, false); fos.flush(); fos.close(); final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test"); logger.debug("This is a test"); final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE))); try { int count = 0; String str = ""; while (is.available() != 0) { str = is.readLine(); ++count; } assertTrue("Incorrect count " + count, count == 1); assertTrue("Bad data", str.endsWith("This is a test")); } finally { is.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public EventRoute getEventRoute(final Level logLevel) { final int remainingCapacity = remainingDisruptorCapacity(); if (remainingCapacity < 0) { return EventRoute.DISCARD; } return asyncEventRouter.getRoute(backgroundThreadId, logLevel); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public EventRoute getEventRoute(final Level logLevel) { final int remainingCapacity = remainingDisruptorCapacity(); if (remainingCapacity < 0) { return EventRoute.DISCARD; } return asyncQueueFullPolicy.getRoute(backgroundThreadId, logLevel); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(final String[] args) throws Exception { if (args.length != 4) { usage("Wrong number of arguments."); } final String tcfBindingName = args[0]; final String topicBindingName = args[1]; final String username = args[2]; final String password = args[3]; final JmsServer server = new JmsServer(tcfBindingName, topicBindingName, username, password); server.start(); final Charset enc = Charset.defaultCharset(); final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, enc)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JmsTopicReceiver."); while (true) { final String line = stdin.readLine(); if (line == null || line.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); server.stop(); return; } } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(final String[] args) throws Exception { final JmsTopicReceiver receiver = new JmsTopicReceiver(); receiver.doMain(args); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConfig() { final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-sdfilter.xml"); final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No StructuredDataFilter", filter); assertTrue("Not a StructuredDataFilter", filter instanceof StructuredDataFilter); final StructuredDataFilter sdFilter = (StructuredDataFilter) filter; assertFalse("Should not be And filter", sdFilter.isAnd()); final Map<String, List<String>> map = sdFilter.getMap(); assertNotNull("No Map", map); assertFalse("No elements in Map", map.isEmpty()); assertEquals("Incorrect number of elements in Map", 1, map.size()); assertTrue("Map does not contain key eventId", map.containsKey("eventId")); assertEquals("List does not contain 2 elements", 2, map.get("eventId").size()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testConfig() { final Configuration config = context.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No StructuredDataFilter", filter); assertTrue("Not a StructuredDataFilter", filter instanceof StructuredDataFilter); final StructuredDataFilter sdFilter = (StructuredDataFilter) filter; assertFalse("Should not be And filter", sdFilter.isAnd()); final Map<String, List<String>> map = sdFilter.getMap(); assertNotNull("No Map", map); assertFalse("No elements in Map", map.isEmpty()); assertEquals("Incorrect number of elements in Map", 1, map.size()); assertTrue("Map does not contain key eventId", map.containsKey("eventId")); assertEquals("List does not contain 2 elements", 2, map.get("eventId").size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void setUpClass() throws Exception { // TODO: refactor PluginManager.decode() into this module? pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>(); final Enumeration<URL> resources = PluginProcessor.class.getClassLoader().getResources(CACHE_FILE); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); final ObjectInput in = new ObjectInputStream(new BufferedInputStream(url.openStream())); try { final int count = in.readInt(); for (int i = 0; i < count; i++) { final String category = in.readUTF(); pluginCategories.putIfAbsent(category, new ConcurrentHashMap<String, PluginEntry>()); final ConcurrentMap<String, PluginEntry> m = pluginCategories.get(category); final int entries = in.readInt(); for (int j = 0; j < entries; j++) { final PluginEntry entry = new PluginEntry(); entry.setKey(in.readUTF()); entry.setClassName(in.readUTF()); entry.setName(in.readUTF()); entry.setPrintable(in.readBoolean()); entry.setDefer(in.readBoolean()); entry.setCategory(category); m.putIfAbsent(entry.getKey(), entry); } pluginCategories.putIfAbsent(category, m); } } finally { in.close(); } } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @BeforeClass public static void setUpClass() throws Exception { // TODO: refactor PluginManager.decode() into this module? pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>(); final Enumeration<URL> resources = PluginProcessor.class.getClassLoader().getResources(CACHE_FILE); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); final DataInputStream in = new DataInputStream(new BufferedInputStream(url.openStream())); try { final int count = in.readInt(); for (int i = 0; i < count; i++) { final String category = in.readUTF(); pluginCategories.putIfAbsent(category, new ConcurrentHashMap<String, PluginEntry>()); final ConcurrentMap<String, PluginEntry> m = pluginCategories.get(category); final int entries = in.readInt(); for (int j = 0; j < entries; j++) { final PluginEntry entry = new PluginEntry(); entry.setKey(in.readUTF()); entry.setClassName(in.readUTF()); entry.setName(in.readUTF()); entry.setPrintable(in.readBoolean()); entry.setDefer(in.readBoolean()); entry.setCategory(category); m.putIfAbsent(entry.getKey(), entry); } pluginCategories.putIfAbsent(category, m); } } finally { in.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); Logger logger = LogManager.getLogger(); if (!(logger instanceof AsyncLogger)) { throw new IllegalStateException(); } logger.info("Starting..."); Thread.sleep(100); final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); // warmup final int ITERATIONS = 100000; long startMs = System.currentTimeMillis(); long end = startMs + TimeUnit.SECONDS.toMillis(10); long total = 0; int count = 0; StringBuilder sb = new StringBuilder(512); do { sb.setLength(0); long startNanos = System.nanoTime(); long uptime = runtimeMXBean.getUptime(); loop(logger, ITERATIONS); long endNanos = System.nanoTime(); long durationNanos = endNanos - startNanos; final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos; sb.append(uptime).append(" Warmup: Throughput: ").append(opsPerSec).append(" ops/s"); System.out.println(sb); total += opsPerSec; count++; // Thread.sleep(1000);// drain buffer } while (System.currentTimeMillis() < end); System.out.printf("Average warmup throughput: %,d ops/s%n", total/count); final int COUNT = 10; final long[] durationNanos = new long[10]; for (int i = 0; i < COUNT; i++) { final long startNanos = System.nanoTime(); loop(logger, ITERATIONS); long endNanos = System.nanoTime(); durationNanos[i] = endNanos - startNanos; // Thread.sleep(1000);// drain buffer } total = 0; for (int i = 0; i < COUNT; i++) { final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos[i]; System.out.printf("Throughput: %,d ops/s%n", opsPerSec); total += opsPerSec; } System.out.printf("Average throughput: %,d ops/s%n", total/COUNT); } #location 51 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code public static void main(String[] args) throws Exception { System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); Logger logger = LogManager.getLogger(); if (!(logger instanceof AsyncLogger)) { throw new IllegalStateException(); } // work around a bug in Log4j-2.5 workAroundLog4j2_5Bug(); logger.error("Starting..."); System.out.println("Starting..."); Thread.sleep(100); final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); final long testStartNanos = System.nanoTime(); final long[] UPTIMES = new long[1024]; final long[] DURATIONS = new long[1024]; // warmup long startMs = System.currentTimeMillis(); long end = startMs + TimeUnit.SECONDS.toMillis(10); int warmupCount = 0; do { runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, warmupCount); warmupCount++; // Thread.sleep(1000);// drain buffer } while (System.currentTimeMillis() < end); final int COUNT = 10; for (int i = 0; i < COUNT; i++) { int count = warmupCount + i; runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, count); // Thread.sleep(1000);// drain buffer } double testDurationNanos = System.nanoTime() - testStartNanos; System.out.println("Done. Calculating stats..."); printReport("Warmup", UPTIMES, DURATIONS, 0, warmupCount); printReport("Test", UPTIMES, DURATIONS, warmupCount, COUNT); StringBuilder sb = new StringBuilder(512); sb.append("Test took: ").append(testDurationNanos/(1000.0*1000.0*1000.0)).append(" sec"); System.out.println(sb); final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (int i = 0; i < gcBeans.size(); i++) { GarbageCollectorMXBean gcBean = gcBeans.get(i); sb.setLength(0); sb.append("GC[").append(gcBean.getName()).append("] "); sb.append(gcBean.getCollectionCount()).append(" collections, collection time="); sb.append(gcBean.getCollectionTime()).append(" millis."); System.out.println(sb); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean compare(final Class<?> testClass, final String file1, final String file2) throws IOException { final BufferedReader in1 = new BufferedReader(new FileReader(file1)); final BufferedReader in2 = new BufferedReader(new InputStreamReader( open(testClass, file2))); try { return compare(testClass, file1, file2, in1, in2); } finally { in1.close(); in2.close(); } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public static boolean compare(final Class<?> testClass, final String file1, final String file2) throws IOException { try (final BufferedReader in1 = new BufferedReader(new FileReader(file1)); final BufferedReader in2 = new BufferedReader(new InputStreamReader(open(testClass, file2)))) { return compare(testClass, file1, file2, in1, in2); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void compareLogEvents(final LogEvent orig, final LogEvent changed) { // Ensure that everything but the Mapped Data is still the same Assert.assertEquals("LoggerName changed", orig.getLoggerName(), changed.getLoggerName()); Assert.assertEquals("Marker changed", orig.getMarker(), changed.getMarker()); Assert.assertEquals("FQCN changed", orig.getLoggerFqcn(), changed.getLoggerFqcn()); Assert.assertEquals("Level changed", orig.getLevel(), changed.getLevel()); Assert.assertArrayEquals("Throwable changed", orig.getThrown() == null // ? null // : ((Log4jLogEvent) orig).getThrownProxy().getExtendedStackTrace(), // changed.getThrown() == null // ? null // : ((Log4jLogEvent) changed).getThrownProxy().getExtendedStackTrace()); Assert.assertEquals("ContextMap changed", orig.getContextMap(), changed.getContextMap()); Assert.assertEquals("ContextStack changed", orig.getContextStack(), changed.getContextStack()); Assert.assertEquals("ThreadName changed", orig.getThreadName(), changed.getThreadName()); Assert.assertEquals("Source changed", orig.getSource(), changed.getSource()); Assert.assertEquals("Millis changed", orig.getTimeMillis(), changed.getTimeMillis()); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private void compareLogEvents(final LogEvent orig, final LogEvent changed) { // Ensure that everything but the Mapped Data is still the same assertEquals("LoggerName changed", orig.getLoggerName(), changed.getLoggerName()); assertEquals("Marker changed", orig.getMarker(), changed.getMarker()); assertEquals("FQCN changed", orig.getLoggerFqcn(), changed.getLoggerFqcn()); assertEquals("Level changed", orig.getLevel(), changed.getLevel()); assertArrayEquals("Throwable changed", orig.getThrown() == null ? null : orig.getThrownProxy().getExtendedStackTrace(), changed.getThrown() == null ? null : changed.getThrownProxy().getExtendedStackTrace() ); assertEquals("ContextMap changed", orig.getContextMap(), changed.getContextMap()); assertEquals("ContextStack changed", orig.getContextStack(), changed.getContextStack()); assertEquals("ThreadName changed", orig.getThreadName(), changed.getThreadName()); assertEquals("Source changed", orig.getSource(), changed.getSource()); assertEquals("Millis changed", orig.getTimeMillis(), changed.getTimeMillis()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMissingRootLogger() throws Exception { PluginManager.addPackage("org.apache.logging.log4j.test.appender"); final LoggerContext ctx = Configurator.initialize("Test1", "missingRootLogger.xml"); final Logger logger = LogManager.getLogger("sample.Logger1"); final Configuration config = ctx.getConfiguration(); assertNotNull("Config not null", config); // final String MISSINGROOT = "MissingRootTest"; // assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(), // MISSINGROOT.equals(config.getName())); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders not null", map); assertEquals("Appenders Size", 2, map.size()); assertTrue("Contains List", map.containsKey("List")); assertTrue("Contains Console", map.containsKey("Console")); final Map<String, LoggerConfig> loggerMap = config.getLoggers(); assertNotNull("loggerMap not null", loggerMap); assertEquals("loggerMap Size", 1, loggerMap.size()); // only the sample logger, no root logger in loggerMap! assertTrue("contains key=sample", loggerMap.containsKey("sample")); final LoggerConfig sample = loggerMap.get("sample"); final Map<String, Appender> sampleAppenders = sample.getAppenders(); assertEquals("sampleAppenders Size", 1, sampleAppenders.size()); // sample only has List appender, not Console! assertTrue("sample has appender List", sampleAppenders.containsKey("List")); final AbstractConfiguration baseConfig = (AbstractConfiguration) config; final LoggerConfig root = baseConfig.getRootLogger(); final Map<String, Appender> rootAppenders = root.getAppenders(); assertEquals("rootAppenders Size", 1, rootAppenders.size()); // root only has Console appender! assertTrue("root has appender Console", rootAppenders.containsKey("Console")); assertEquals(Level.ERROR, root.getLevel()); logger.isDebugEnabled(); Configurator.shutdown(ctx); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMissingRootLogger() throws Exception { final LoggerContext ctx = context.getContext(); final Logger logger = ctx.getLogger("sample.Logger1"); assertTrue("Logger should have the INFO level enabled", logger.isInfoEnabled()); assertFalse("Logger should have the DEBUG level disabled", logger.isDebugEnabled()); final Configuration config = ctx.getConfiguration(); assertNotNull("Config not null", config); // final String MISSINGROOT = "MissingRootTest"; // assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(), // MISSINGROOT.equals(config.getName())); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders not null", map); assertEquals("There should only be two appenders", 2, map.size()); assertTrue("Contains List", map.containsKey("List")); assertTrue("Contains Console", map.containsKey("Console")); final Map<String, LoggerConfig> loggerMap = config.getLoggers(); assertNotNull("loggerMap not null", loggerMap); assertEquals("There should only be one configured logger", 1, loggerMap.size()); // only the sample logger, no root logger in loggerMap! assertTrue("contains key=sample", loggerMap.containsKey("sample")); final LoggerConfig sample = loggerMap.get("sample"); final Map<String, Appender> sampleAppenders = sample.getAppenders(); assertEquals("The sample logger should only have one appender", 1, sampleAppenders.size()); // sample only has List appender, not Console! assertTrue("The sample appender should be a ListAppender", sampleAppenders.containsKey("List")); final AbstractConfiguration baseConfig = (AbstractConfiguration) config; final LoggerConfig root = baseConfig.getRootLogger(); final Map<String, Appender> rootAppenders = root.getAppenders(); assertEquals("The root logger should only have one appender", 1, rootAppenders.size()); // root only has Console appender! assertTrue("The root appender should be a ConsoleAppender", rootAppenders.containsKey("Console")); assertEquals(Level.ERROR, root.getLevel()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { final FileInputStream fis = new FileInputStream(source); final FileOutputStream fos = new FileOutputStream(destination); final ZipOutputStream zos = new ZipOutputStream(fos); zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } zos.close(); fis.close(); if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { try (final FileInputStream fis = new FileInputStream(source); final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination))) { zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } } if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream(); filteredOut.flush(); filteredOut.close(); verify(out); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); try (final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream()) { filteredOut.flush(); } verify(out); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNoMsg() { final RegexFilter filter = RegexFilter.createFilter(Pattern.compile(".* test .*"), false, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (String) null, (Throwable) null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Message) null, (Throwable) null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Object[]) null)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testNoMsg() throws Exception { final RegexFilter filter = RegexFilter.createFilter(".* test .*", null, false, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (String) null, (Throwable) null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Message) null, (Throwable) null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Object[]) null)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testThresholds() { final ThresholdFilter filter = ThresholdFilter.createFilter("ERROR", null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Throwable) null)); assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, null, (Throwable) null)); LogEvent event = new Log4jLogEvent(null, null, null, Level.DEBUG, new SimpleMessage("Test"), null); assertSame(Filter.Result.DENY, filter.filter(event)); event = new Log4jLogEvent(null, null, null, Level.ERROR, new SimpleMessage("Test"), null); assertSame(Filter.Result.NEUTRAL, filter.filter(event)); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testThresholds() { final ThresholdFilter filter = ThresholdFilter.createFilter(Level.ERROR, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Throwable) null)); assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, null, (Throwable) null)); LogEvent event = new Log4jLogEvent(null, null, null, Level.DEBUG, new SimpleMessage("Test"), null); assertSame(Filter.Result.DENY, filter.filter(event)); event = new Log4jLogEvent(null, null, null, Level.ERROR, new SimpleMessage("Test"), null); assertSame(Filter.Result.NEUTRAL, filter.filter(event)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Object deserializeStream(final String witness) throws Exception { final FileInputStream fileIs = new FileInputStream(witness); final ObjectInputStream objIs = new ObjectInputStream(fileIs); try { return objIs.readObject(); } finally { objIs.close(); } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public static Object deserializeStream(final String witness) throws Exception { try (final ObjectInputStream objIs = new ObjectInputStream(new FileInputStream(witness))) { return objIs.readObject(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMemMapLocation() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final int expectedFileLength = Integers.ceilingNextPowerOfTwo(32000); assertEquals(32768, expectedFileLength); final Logger log = LogManager.getLogger(); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", expectedFileLength, f.length()); log.warn("Test log2"); assertEquals("not grown", expectedFileLength, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.getProperty("line.separator").length(); assertEquals("Shrunk to actual used size", 474 + 2 * LINESEP, f.length()); String line1, line2, line3; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); final String location1 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:65)"; assertThat(line1, containsString(location1)); assertNotNull(line2); assertThat(line2, containsString("Test log2")); final String location2 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:69)"; assertThat(line2, containsString(location2)); assertNull("only two lines were logged", line3); } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMemMapLocation() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final int expectedFileLength = Integers.ceilingNextPowerOfTwo(32000); assertEquals(32768, expectedFileLength); final Logger log = LogManager.getLogger(); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", expectedFileLength, f.length()); log.warn("Test log2"); assertEquals("not grown", expectedFileLength, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.lineSeparator().length(); assertEquals("Shrunk to actual used size", 474 + 2 * LINESEP, f.length()); String line1, line2, line3; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); final String location1 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:65)"; assertThat(line1, containsString(location1)); assertNotNull(line2); assertThat(line2, containsString("Test log2")); final String location2 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:69)"; assertThat(line2, containsString(location2)); assertNull("only two lines were logged", line3); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); boolean found = false; for (final File file : files) { if (file.getName().endsWith(".gz")) { found = true; break; } } assertTrue("No compressed files found", found); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz")))))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testByName() throws Exception { Configurator.intitalize("-config", null, null); Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator"); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); assertNotNull("No configuration", config); assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(), CONFIG_NAME.equals(config.getName())); Map<String, Appender> map = config.getAppenders(); assertNotNull("No Appenders", map != null && map.size() > 0); assertTrue("Wrong configuration", map.containsKey("List")); Configurator.shutdown(); config = ctx.getConfiguration(); assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " + config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName())); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testByName() throws Exception { LoggerContext ctx = Configurator.intitalize("-config", null, null); Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); assertNotNull("No configuration", config); assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(), CONFIG_NAME.equals(config.getName())); Map<String, Appender> map = config.getAppenders(); assertNotNull("No Appenders", map != null && map.size() > 0); assertTrue("Wrong configuration", map.containsKey("List")); Configurator.shutdown(ctx); config = ctx.getConfiguration(); assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " + config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerFilterOutputStream los = new LoggerFilterOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { final FileInputStream fis = new FileInputStream(source); final FileOutputStream fos = new FileOutputStream(destination); final ZipOutputStream zos = new ZipOutputStream(fos); zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } zos.close(); fis.close(); if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { try (final FileInputStream fis = new FileInputStream(source); final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination))) { zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } } if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void logToFile() throws Exception { final FileOutputStream fos = new FileOutputStream(LOGFILE, false); fos.flush(); fos.close(); final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test"); logger.debug("This is a test"); final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE))); int count = 0; String str = ""; while (is.available() != 0) { str = is.readLine(); ++count; } assertTrue("Incorrect count " + count, count == 1); assertTrue("Bad data", str.endsWith("This is a test")); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void logToFile() throws Exception { final FileOutputStream fos = new FileOutputStream(LOGFILE, false); fos.flush(); fos.close(); final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test"); logger.debug("This is a test"); final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE))); try { int count = 0; String str = ""; while (is.available() != 0) { str = is.readLine(); ++count; } assertTrue("Incorrect count " + count, count == 1); assertTrue("Bad data", str.endsWith("This is a test")); } finally { is.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code EventRoute getEventRoute(final Level logLevel) { final int remainingCapacity = remainingDisruptorCapacity(); if (remainingCapacity < 0) { return EventRoute.DISCARD; } return asyncEventRouter.getRoute(backgroundThreadId, logLevel); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code AsyncLoggerDisruptor(String contextName) { this.contextName = contextName; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRollingFileAppender() throws Exception { StatusLogger.getLogger().setLevel(Level.TRACE); final Configuration configuration = configure("config-1.2/log4j-RollingFileAppender.properties"); final Appender appender = configuration.getAppender("RFA"); assertNotNull(appender); assertEquals("RFA", appender.getName()); assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender); final RollingFileAppender rfa = (RollingFileAppender) appender; assertEquals("./hadoop.log", rfa.getFileName()); assertEquals("./hadoop.log.%i", rfa.getFilePattern()); final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy(); assertNotNull(triggeringPolicy); assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy); final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy; final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies(); assertEquals(1, triggeringPolicies.length); final TriggeringPolicy tp = triggeringPolicies[0]; assertTrue(tp.getClass().getName(), tp instanceof SizeBasedTriggeringPolicy); final SizeBasedTriggeringPolicy sbtp = (SizeBasedTriggeringPolicy) tp; assertEquals(256 * 1024 * 1024, sbtp.getMaxFileSize()); final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy(); assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy); final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy; assertEquals(20, drs.getMaxIndex()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRollingFileAppender() throws Exception { testRollingFileAppender("config-1.2/log4j-RollingFileAppender.properties"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static ConcurrentMap<String, ConcurrentMap<String, PluginType>> decode(final ClassLoader loader) { Enumeration<URL> resources; try { resources = loader.getResources(PATH + FILENAME); } catch (final IOException ioe) { LOGGER.warn("Unable to preload plugins", ioe); return null; } final ConcurrentMap<String, ConcurrentMap<String, PluginType>> map = new ConcurrentHashMap<String, ConcurrentMap<String, PluginType>>(); while (resources.hasMoreElements()) { try { final URL url = resources.nextElement(); LOGGER.debug("Found Plugin Map at {}", url.toExternalForm()); final InputStream is = url.openStream(); final BufferedInputStream bis = new BufferedInputStream(is); final DataInputStream dis = new DataInputStream(bis); final int count = dis.readInt(); for (int j = 0; j < count; ++j) { final String type = dis.readUTF(); final int entries = dis.readInt(); ConcurrentMap<String, PluginType> types = map.get(type); if (types == null) { types = new ConcurrentHashMap<String, PluginType>(count); } for (int i = 0; i < entries; ++i) { final String key = dis.readUTF(); final String className = dis.readUTF(); final String name = dis.readUTF(); final boolean printable = dis.readBoolean(); final boolean defer = dis.readBoolean(); final Class<?> clazz = Class.forName(className); types.put(key, new PluginType(clazz, name, printable, defer)); } map.putIfAbsent(type, types); } dis.close(); } catch (final Exception ex) { LOGGER.warn("Unable to preload plugins", ex); return null; } } return map.size() == 0 ? null : map; } #location 38 #vulnerability type RESOURCE_LEAK
#fixed code private static ConcurrentMap<String, ConcurrentMap<String, PluginType>> decode(final ClassLoader loader) { Enumeration<URL> resources; try { resources = loader.getResources(PATH + FILENAME); } catch (final IOException ioe) { LOGGER.warn("Unable to preload plugins", ioe); return null; } final ConcurrentMap<String, ConcurrentMap<String, PluginType>> map = new ConcurrentHashMap<String, ConcurrentMap<String, PluginType>>(); while (resources.hasMoreElements()) { DataInputStream dis = null; try { final URL url = resources.nextElement(); LOGGER.debug("Found Plugin Map at {}", url.toExternalForm()); final InputStream is = url.openStream(); final BufferedInputStream bis = new BufferedInputStream(is); dis = new DataInputStream(bis); final int count = dis.readInt(); for (int j = 0; j < count; ++j) { final String type = dis.readUTF(); final int entries = dis.readInt(); ConcurrentMap<String, PluginType> types = map.get(type); if (types == null) { types = new ConcurrentHashMap<String, PluginType>(count); } for (int i = 0; i < entries; ++i) { final String key = dis.readUTF(); final String className = dis.readUTF(); final String name = dis.readUTF(); final boolean printable = dis.readBoolean(); final boolean defer = dis.readBoolean(); final Class<?> clazz = Class.forName(className); types.put(key, new PluginType(clazz, name, printable, defer)); } map.putIfAbsent(type, types); } } catch (final Exception ex) { LOGGER.warn("Unable to preload plugins", ex); return null; } finally { try { dis.close(); } catch (Exception ignored) { // nothing we can do here... } } } return map.size() == 0 ? null : map; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static void reportResult(final String file, final String name, final Histogram histogram) throws IOException { final String result = createSamplingReport(name, histogram); println(result); if (file != null) { final FileWriter writer = new FileWriter(file, true); writer.write(result); writer.write(System.getProperty("line.separator")); writer.close(); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code static void reportResult(final String file, final String name, final Histogram histogram) throws IOException { final String result = createSamplingReport(name, histogram); println(result); if (file != null) { final FileWriter writer = new FileWriter(file, true); try { writer.write(result); writer.write(System.getProperty("line.separator")); } finally { writer.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static OutputStream getOutputStream(final boolean follow, final Target target) { final PrintStream printStream = target == Target.SYSTEM_OUT ? follow ? new PrintStream(new SystemOutStream()) : System.out : follow ? new PrintStream(new SystemErrStream()) : System.err; if (!System.getProperty("os.name").startsWith("Windows") || Boolean.getBoolean("log4j.skipJansi")) { return printStream; } else { try { final ClassLoader loader = Loader.getClassLoader(); // We type the parameter as a wildcard to avoid a hard reference to Jansi. final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream"); final Constructor<?> constructor = clazz.getConstructor(OutputStream.class); return (OutputStream) constructor.newInstance(printStream); } catch (final ClassNotFoundException cnfe) { LOGGER.debug("Jansi is not installed"); } catch (final NoSuchMethodException nsme) { LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor"); } catch (final Exception ex) { LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream"); } return printStream; } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code private static OutputStream getOutputStream(final boolean follow, final Target target) { final PrintStream printStream = target == Target.SYSTEM_OUT ? follow ? new PrintStream(new SystemOutStream()) : System.out : follow ? new PrintStream(new SystemErrStream()) : System.err; PropertiesUtil propsUtil = PropertiesUtil.getProperties(); if (!propsUtil.getStringProperty("os.name").startsWith("Windows") || propsUtil.getBooleanProperty("log4j.skipJansi")) { return printStream; } else { try { final ClassLoader loader = Loader.getClassLoader(); // We type the parameter as a wildcard to avoid a hard reference to Jansi. final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream"); final Constructor<?> constructor = clazz.getConstructor(OutputStream.class); return (OutputStream) constructor.newInstance(printStream); } catch (final ClassNotFoundException cnfe) { LOGGER.debug("Jansi is not installed"); } catch (final NoSuchMethodException nsme) { LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor"); } catch (final Exception ex) { LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream"); } return printStream; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testLayout() throws Exception { final Map<String, Appender> appenders = this.rootLogger.getAppenders(); for (final Appender appender : appenders.values()) { this.rootLogger.removeAppender(appender); } // set up appender final XmlLayout layout = XmlLayout.createLayout("true", "true", "true", null, null); final ListAppender appender = new ListAppender("List", null, layout, true, false); appender.start(); // set appender on root and set level to debug this.rootLogger.addAppender(appender); this.rootLogger.setLevel(Level.DEBUG); // output starting message this.rootLogger.debug("starting mdc pattern test"); this.rootLogger.debug("empty mdc"); ThreadContext.put("key1", "value1"); ThreadContext.put("key2", "value2"); this.rootLogger.debug("filled mdc"); ThreadContext.remove("key1"); ThreadContext.remove("key2"); this.rootLogger.error("finished mdc pattern test", new NullPointerException("test")); final Marker marker = MarkerManager.getMarker("EVENT"); this.rootLogger.error(marker, "marker test"); appender.stop(); final List<String> list = appender.getMessages(); final String string = list.get(0); assertTrue("Incorrect header: " + string, string.equals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")); assertTrue("Incorrect footer", list.get(list.size() - 1).equals("</Events>")); this.checkContains("loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLoggerProvider\"", list); this.checkContains("level=\"DEBUG\"", list); this.checkContains(">starting mdc pattern test</Message>", list); // this.checkContains("<Message>starting mdc pattern test</Message>", list); // <Marker xmlns="" _class="org.apache.logging.log4j.MarkerManager..Log4jMarker" name="EVENT"/> this.checkContains("<Marker", list); this.checkContains("name=\"EVENT\"/>", list); for (final Appender app : appenders.values()) { this.rootLogger.addAppender(app); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testLayout() throws Exception { final Map<String, Appender> appenders = this.rootLogger.getAppenders(); for (final Appender appender : appenders.values()) { this.rootLogger.removeAppender(appender); } // set up appender final XmlLayout layout = XmlLayout.createLayout(true, true, true, false, null); final ListAppender appender = new ListAppender("List", null, layout, true, false); appender.start(); // set appender on root and set level to debug this.rootLogger.addAppender(appender); this.rootLogger.setLevel(Level.DEBUG); // output starting message this.rootLogger.debug("starting mdc pattern test"); this.rootLogger.debug("empty mdc"); ThreadContext.put("key1", "value1"); ThreadContext.put("key2", "value2"); this.rootLogger.debug("filled mdc"); ThreadContext.remove("key1"); ThreadContext.remove("key2"); this.rootLogger.error("finished mdc pattern test", new NullPointerException("test")); final Marker marker = MarkerManager.getMarker("EVENT"); this.rootLogger.error(marker, "marker test"); appender.stop(); final List<String> list = appender.getMessages(); final String string = list.get(0); assertTrue("Incorrect header: " + string, string.equals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")); assertTrue("Incorrect footer", list.get(list.size() - 1).equals("</Events>")); this.checkContains("loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLoggerProvider\"", list); this.checkContains("level=\"DEBUG\"", list); this.checkContains(">starting mdc pattern test</Message>", list); // this.checkContains("<Message>starting mdc pattern test</Message>", list); // <Marker xmlns="" _class="org.apache.logging.log4j.MarkerManager..Log4jMarker" name="EVENT"/> this.checkContains("<Marker", list); this.checkContains("name=\"EVENT\"/>", list); for (final Appender app : appenders.values()) { this.rootLogger.addAppender(app); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String readContents(final URI uri, final Charset charset) throws IOException { InputStream in = null; try { in = uri.toURL().openStream(); final Reader reader = new InputStreamReader(in, charset); final StringBuilder result = new StringBuilder(TEXT_BUFFER); final char[] buff = new char[PAGE]; int count = -1; while ((count = reader.read(buff)) >= 0) { result.append(buff, 0, count); } return result.toString(); } finally { try { in.close(); } catch (final Exception ignored) { // ignored } } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private String readContents(final URI uri, final Charset charset) throws IOException { if (charset == null) { throw new IllegalArgumentException("charset must not be null"); } Reader reader = null; try { InputStream in = uri.toURL().openStream(); // The stream is open and charset is not null, we can create the reader safely without a possible NPE. reader = new InputStreamReader(in, charset); final StringBuilder result = new StringBuilder(TEXT_BUFFER); final char[] buff = new char[PAGE]; int count = -1; while ((count = reader.read(buff)) >= 0) { result.append(buff, 0, count); } return result.toString(); } finally { try { if (reader != null) { reader.close(); } } catch (final Exception ignored) { // ignored } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @PluginFactory public static <S extends Serializable> SocketAppender<S> createAppender(@PluginAttr("host") final String host, @PluginAttr("port") final String portNum, @PluginAttr("protocol") final String protocol, @PluginAttr("reconnectionDelay") final String delay, @PluginAttr("immediateFail") final String immediateFail, @PluginAttr("name") final String name, @PluginAttr("immediateFlush") final String immediateFlush, @PluginAttr("suppressExceptions") final String suppress, @PluginElement("layout") Layout<S> layout, @PluginElement("filters") final Filter filter, @PluginAttr("advertise") final String advertise, @PluginConfiguration final Configuration config) { boolean isFlush = immediateFlush == null ? true : Boolean.parseBoolean(immediateFlush); final boolean isAdvertise = advertise == null ? false : Boolean.parseBoolean(advertise); final boolean handleExceptions = suppress == null ? true : Boolean.parseBoolean(suppress); final boolean fail = immediateFail == null ? true : Boolean.parseBoolean(immediateFail); final int reconnectDelay = Integers.parseInt(delay); final int port = Integers.parseInt(portNum); if (layout == null) { @SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" }) final Layout<S> l = (Layout<S>) SerializedLayout.createLayout(); layout = l; } if (name == null) { LOGGER.error("No name provided for SocketAppender"); return null; } final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol != null ? protocol : Protocol.TCP.name()); if (p.equals(Protocol.UDP)) { isFlush = true; } final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout); if (manager == null) { return null; } return new SocketAppender<S>(name, layout, filter, manager, handleExceptions, isFlush, isAdvertise ? config.getAdvertiser() : null); } #location 34 #vulnerability type NULL_DEREFERENCE
#fixed code @PluginFactory public static <S extends Serializable> SocketAppender<S> createAppender(@PluginAttr("host") final String host, @PluginAttr("port") final String portNum, @PluginAttr("protocol") final String protocol, @PluginAttr("reconnectionDelay") final String delay, @PluginAttr("immediateFail") final String immediateFail, @PluginAttr("name") final String name, @PluginAttr("immediateFlush") final String immediateFlush, @PluginAttr("suppressExceptions") final String suppress, @PluginElement("layout") Layout<S> layout, @PluginElement("filters") final Filter filter, @PluginAttr("advertise") final String advertise, @PluginConfiguration final Configuration config) { boolean isFlush = Booleans.parseBoolean(immediateFlush, true); final boolean isAdvertise = Boolean.parseBoolean(advertise); final boolean handleExceptions = Booleans.parseBoolean(suppress, true); final boolean fail = Booleans.parseBoolean(immediateFail, true); final int reconnectDelay = Integers.parseInt(delay); final int port = Integers.parseInt(portNum); if (layout == null) { @SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" }) final Layout<S> l = (Layout<S>) SerializedLayout.createLayout(); layout = l; } if (name == null) { LOGGER.error("No name provided for SocketAppender"); return null; } final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol != null ? protocol : Protocol.TCP.name()); if (p.equals(Protocol.UDP)) { isFlush = true; } final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout); if (manager == null) { return null; } return new SocketAppender<S>(name, layout, filter, manager, handleExceptions, isFlush, isAdvertise ? config.getAdvertiser() : null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void log(final LogEvent event) { counter.incrementAndGet(); try { if (isFiltered(event)) { return; } event.setIncludeLocation(isIncludeLocation()); callAppenders(event); if (additive && parent != null) { parent.log(event); } } finally { if (counter.decrementAndGet() == 0) { shutdownLock.lock(); try { if (shutdown.get()) { noLogEvents.signalAll(); } } finally { shutdownLock.unlock(); } } } } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void log(final LogEvent event) { beforeLogEvent(); try { if (!isFiltered(event)) { processLogEvent(event); } } finally { afterLogEvent(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean execute(final File source, final File destination, final boolean deleteSource) throws IOException { if (source.exists()) { final FileInputStream fis = new FileInputStream(source); final FileOutputStream fos = new FileOutputStream(destination); final GZIPOutputStream gzos = new GZIPOutputStream(fos); final BufferedOutputStream os = new BufferedOutputStream(gzos); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { os.write(inbuf, 0, n); } os.close(); fis.close(); if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code public static boolean execute(final File source, final File destination, final boolean deleteSource) throws IOException { if (source.exists()) { try (final FileInputStream fis = new FileInputStream(source); final BufferedOutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream( destination)))) { final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { os.write(inbuf, 0, n); } } if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); boolean found = false; for (final File file : files) { if (file.getName().endsWith(fileExtension)) { found = true; break; } } assertTrue("No compressed files found", found); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); assertThat(files, hasItemInArray(that(hasName(that(endsWith(fileExtension)))))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerFilterOutputStream los = new LoggerFilterOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void releaseSub() { if (transceiver != null) { try { transceiver.close(); } catch (final IOException ioe) { LOGGER.error("Attempt to clean up Avro transceiver failed", ioe); } } client = null; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void releaseSub() { if (rpcClient != null) { try { rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public byte[] toByteArray(final LogEvent event) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new PrivateObjectOutputStream(baos); oos.writeObject(event); } catch (IOException ioe) { LOGGER.error("Serialization of LogEvent failed.", ioe); } return baos.toByteArray(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public byte[] toByteArray(final LogEvent event) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new PrivateObjectOutputStream(baos); try { oos.writeObject(event); } finally { oos.close(); } } catch (IOException ioe) { LOGGER.error("Serialization of LogEvent failed.", ioe); } return baos.toByteArray(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void appendStructuredElements(final StringBuilder buffer, final LogEvent event) { final Message message = event.getMessage(); final boolean isStructured = message instanceof StructuredDataMessage; if (!isStructured && (fieldFormatters!= null && fieldFormatters.size() == 0) && !includeMDC) { buffer.append("-"); return; } final Map<String, StructuredDataElement> sdElements = new HashMap<String, StructuredDataElement>(); final Map<String, String> contextMap = event.getContextMap(); if (mdcRequired != null) { checkRequired(contextMap); } if (fieldFormatters != null) { for (final Map.Entry<String, FieldFormatter> sdElement: fieldFormatters.entrySet()) { final String sdId = sdElement.getKey(); final StructuredDataElement elem = sdElement.getValue().format(event); sdElements.put(sdId, elem); } } if (includeMDC && contextMap.size() > 0) { if (sdElements.containsKey(mdcSDID.toString())) { final StructuredDataElement union = sdElements.get(mdcSDID.toString()); union.union(contextMap); sdElements.put(mdcSDID.toString(), union); } else { final StructuredDataElement formattedContextMap = new StructuredDataElement(contextMap, false); sdElements.put(mdcSDID.toString(), formattedContextMap); } } if (isStructured) { final StructuredDataMessage data = (StructuredDataMessage) message; final Map<String, String> map = data.getData(); final StructuredDataId id = data.getId(); if (sdElements.containsKey(id.toString())) { final StructuredDataElement union = sdElements.get(id.toString()); union.union(map); sdElements.put(id.toString(), union); } else { final StructuredDataElement formattedData = new StructuredDataElement(map, false); sdElements.put(id.toString(), formattedData); } } if (sdElements.size() == 0) { buffer.append("-"); return; } for (final Map.Entry<String, StructuredDataElement> entry: sdElements.entrySet()) { formatStructuredElement(entry.getKey(), mdcPrefix, entry.getValue(), buffer, checker); } } #location 43 #vulnerability type NULL_DEREFERENCE
#fixed code private void appendStructuredElements(final StringBuilder buffer, final LogEvent event) { final Message message = event.getMessage(); final boolean isStructured = message instanceof StructuredDataMessage; if (!isStructured && (fieldFormatters!= null && fieldFormatters.size() == 0) && !includeMDC) { buffer.append("-"); return; } final Map<String, StructuredDataElement> sdElements = new HashMap<String, StructuredDataElement>(); final Map<String, String> contextMap = event.getContextMap(); if (mdcRequired != null) { checkRequired(contextMap); } if (fieldFormatters != null) { for (final Map.Entry<String, FieldFormatter> sdElement: fieldFormatters.entrySet()) { final String sdId = sdElement.getKey(); final StructuredDataElement elem = sdElement.getValue().format(event); sdElements.put(sdId, elem); } } if (includeMDC && contextMap.size() > 0) { if (sdElements.containsKey(mdcSDID.toString())) { final StructuredDataElement union = sdElements.get(mdcSDID.toString()); union.union(contextMap); sdElements.put(mdcSDID.toString(), union); } else { final StructuredDataElement formattedContextMap = new StructuredDataElement(contextMap, false); sdElements.put(mdcSDID.toString(), formattedContextMap); } } if (isStructured) { final StructuredDataMessage data = (StructuredDataMessage) message; final Map<String, String> map = data.getData(); final StructuredDataId id = data.getId(); final String sdId = getId(id); if (sdElements.containsKey(sdId)) { final StructuredDataElement union = sdElements.get(id.toString()); union.union(map); sdElements.put(sdId, union); } else { final StructuredDataElement formattedData = new StructuredDataElement(map, false); sdElements.put(sdId, formattedData); } } if (sdElements.size() == 0) { buffer.append("-"); return; } for (final Map.Entry<String, StructuredDataElement> entry: sdElements.entrySet()) { formatStructuredElement(entry.getKey(), mdcPrefix, entry.getValue(), buffer, checker); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testJmsTopicAppenderCompatibility() throws Exception { assertEquals(0, topic.size()); final JmsAppender appender = (JmsAppender) ctx.getRequiredAppender("JmsTopicAppender"); final LogEvent expected = createLogEvent(); appender.append(expected); assertEquals(1, topic.size()); final Message message = topic.getMessageAt(0); assertNotNull(message); assertThat(message, instanceOf(ObjectMessage.class)); final ObjectMessage objectMessage = (ObjectMessage) message; final Object o = objectMessage.getObject(); assertThat(o, instanceOf(LogEvent.class)); final LogEvent actual = (LogEvent) o; assertEquals(expected.getMessage().getFormattedMessage(), actual.getMessage().getFormattedMessage()); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testJmsTopicAppenderCompatibility() throws Exception { final JmsAppender appender = (JmsAppender) ctx.getRequiredAppender("JmsTopicAppender"); final LogEvent expected = createLogEvent(); appender.append(expected); then(session).should().createObjectMessage(eq(expected)); then(objectMessage).should().setJMSTimestamp(anyLong()); then(messageProducer).should().send(objectMessage); appender.stop(); then(session).should().close(); then(connection).should().close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(final String[] args) throws Exception { if (args.length != 4) { usage("Wrong number of arguments."); } final String qcfBindingName = args[0]; final String queueBindingName = args[1]; final String username = args[2]; final String password = args[3]; final JmsServer server = new JmsServer(qcfBindingName, queueBindingName, username, password); server.start(); final Charset enc = Charset.defaultCharset(); final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, enc)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JmsQueueReceiver."); while (true) { final String line = stdin.readLine(); if (line == null || line.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); server.stop(); return; } } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(final String[] args) throws Exception { final JmsQueueReceiver receiver = new JmsQueueReceiver(); receiver.doMain(args); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConfig() { final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-mapfilter.xml"); final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No MapFilter", filter); assertTrue("Not a MapFilter", filter instanceof MapFilter); final MapFilter mapFilter = (MapFilter) filter; assertFalse("Should not be And filter", mapFilter.isAnd()); final Map<String, List<String>> map = mapFilter.getMap(); assertNotNull("No Map", map); assertFalse("No elements in Map", map.isEmpty()); assertEquals("Incorrect number of elements in Map", 1, map.size()); assertTrue("Map does not contain key eventId", map.containsKey("eventId")); assertEquals("List does not contain 2 elements", 2, map.get("eventId").size()); final Logger logger = LogManager.getLogger(MapFilterTest.class); final Map<String, String> eventMap = new HashMap<>(); eventMap.put("eventId", "Login"); logger.debug(new MapMessage(eventMap)); final Appender app = config.getAppender("LIST"); assertNotNull("No List appender", app); final List<String> msgs = ((ListAppender) app).getMessages(); assertNotNull("No messages", msgs); assertFalse("No messages", msgs.isEmpty()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testConfig() { final Configuration config = context.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No MapFilter", filter); assertTrue("Not a MapFilter", filter instanceof MapFilter); final MapFilter mapFilter = (MapFilter) filter; assertFalse("Should not be And filter", mapFilter.isAnd()); final Map<String, List<String>> map = mapFilter.getMap(); assertNotNull("No Map", map); assertFalse("No elements in Map", map.isEmpty()); assertEquals("Incorrect number of elements in Map", 1, map.size()); assertTrue("Map does not contain key eventId", map.containsKey("eventId")); assertEquals("List does not contain 2 elements", 2, map.get("eventId").size()); final Logger logger = LogManager.getLogger(MapFilterTest.class); final Map<String, String> eventMap = new HashMap<>(); eventMap.put("eventId", "Login"); logger.debug(new MapMessage(eventMap)); final ListAppender app = context.getListAppender("LIST"); final List<String> msgs = app.getMessages(); assertNotNull("No messages", msgs); assertFalse("No messages", msgs.isEmpty()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMemMapExtendsIfNeeded() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final Logger log = LogManager.getLogger(); final char[] text = new char[200]; Arrays.fill(text, 'A'); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", 256, f.length()); log.warn(new String(text)); assertEquals("grown", 256 * 2, f.length()); log.warn(new String(text)); assertEquals("grown again", 256 * 3, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.getProperty("line.separator").length(); assertEquals("Shrunk to actual used size", 658 + 3 * LINESEP, f.length()); String line1, line2, line3, line4; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); assertNotNull(line2); assertThat(line2, containsString(new String(text))); assertNotNull(line3); assertThat(line3, containsString(new String(text))); assertNull("only three lines were logged", line4); } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMemMapExtendsIfNeeded() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final Logger log = LogManager.getLogger(); final char[] text = new char[200]; Arrays.fill(text, 'A'); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", 256, f.length()); log.warn(new String(text)); assertEquals("grown", 256 * 2, f.length()); log.warn(new String(text)); assertEquals("grown again", 256 * 3, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.lineSeparator().length(); assertEquals("Shrunk to actual used size", 658 + 3 * LINESEP, f.length()); String line1, line2, line3, line4; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); assertNotNull(line2); assertThat(line2, containsString(new String(text))); assertNotNull(line3); assertThat(line3, containsString(new String(text))); assertNull("only three lines were logged", line4); }
Below is the vulnerable code, please generate the patch based on the following information.