instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private int flushFromMemToLimit() { if ((hashScore.size() == 0) && (cache.size() == 0)) { serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty"); return 0; } if ((hashScore.size() == 0) && (cache.size() != 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size()); return 0; } if ((hashScore.size() != 0) && (cache.size() == 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0"); return 0; } //serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size()); int total = 0; synchronized (hashScore) { String key; int count; Long createTime; // flush high-scores while ((total < 100) && (hashScore.size() >= maxWords)) { key = (String) hashScore.getMaxObject(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count < 5) { log.logWarning("flushing of high-key " + key + " not appropriate (too less entries, count=" + count + "): increase cache size"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) { //log.logDebug("high-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); break; } //log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); total += flushFromMem(key, false); } // flush singletons Iterator i = hashScore.scores(true); ArrayList al = new ArrayList(); while ((i.hasNext()) && (total < 200)) { key = (String) i.next(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count > 1) { //log.logDebug("flush of singleton-key " + key + ": count too high (count=" + count + ")"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 90000)) { //log.logDebug("singleton-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); continue; } //log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); al.add(key); total++; } for (int k = 0; k < al.size(); k++) flushFromMem((String) al.get(k), true); } return total; }
#vulnerable code private int flushFromMemToLimit() { if ((hashScore.size() == 0) && (cache.size() == 0)) { serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty"); return 0; } if ((hashScore.size() == 0) && (cache.size() != 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size()); return 0; } if ((hashScore.size() != 0) && (cache.size() == 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0"); return 0; } //serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size()); int total = 0; synchronized (hashScore) { String key; int count; Long createTime; // flush high-scores while ((total < 100) && (hashScore.size() >= maxWords)) { key = (String) hashScore.getMaxObject(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count < 5) { log.logWarning("flushing of high-key " + key + " not appropriate (too less entries, count=" + count + "): increase cache size"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) { //log.logDebug("high-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); break; } //log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); total += flushFromMem(key); } // flush singletons while ((total < 200) && (hashScore.size() >= maxWords)) { key = (String) hashScore.getMinObject(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count > 1) { //log.logDebug("flush of singleton-key " + key + ": count too high (count=" + count + ")"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) { //log.logDebug("singleton-key " + key + " is too fresh, interruptiong flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); break; } //log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); total += flushFromMem(key); } } return total; } #location 36 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean job() throws Exception { // prepare for new connection // idleThreadCheck(); this.switchboard.handleBusyState(this.theSessionPool.getNumActive() /*activeThreads.size() */); log.logDebug( "* waiting for connections, " + this.theSessionPool.getNumActive() + " sessions running, " + this.theSessionPool.getNumIdle() + " sleeping"); // list all connection (debug) /* if (activeThreads.size() > 0) { Enumeration threadEnum = activeThreads.keys(); Session se; long time; while (threadEnum.hasMoreElements()) { se = (Session) threadEnum.nextElement(); time = System.currentTimeMillis() - ((Long) activeThreads.get(se)).longValue(); log.logDebug("* ACTIVE SESSION (" + ((se.isAlive()) ? "alive" : "dead") + ", " + time + "): " + se.request); } } */ // wait for new connection announceThreadBlockApply(); Socket controlSocket = this.socket.accept(); announceThreadBlockRelease(); String clientIP = ""+controlSocket.getInetAddress().getHostAddress(); if (bfHost.get(clientIP) != null) { log.logInfo("SLOWING DOWN ACCESS FOR BRUTE-FORCE PREVENTION FROM " + clientIP); // add a delay to make brute-force harder try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {} } if ((this.denyHost == null) || (this.denyHost.get(clientIP) == null)) { controlSocket.setSoTimeout(this.timeout); Session connection = (Session) this.theSessionPool.borrowObject(); connection.execute(controlSocket); //log.logDebug("* NEW SESSION: " + connection.request + " from " + clientIP); } else { System.out.println("ACCESS FROM " + clientIP + " DENIED"); } // idle until number of maximal threads is (again) reached //synchronized(this) { // while ((maxSessions > 0) && (activeThreads.size() >= maxSessions)) try { // log.logDebug("* Waiting for activeThreads=" + activeThreads.size() + " < maxSessions=" + maxSessions); // Thread.currentThread().sleep(2000); // idleThreadCheck(); // } catch (InterruptedException e) {} return true; }
#vulnerable code public boolean job() throws Exception { // prepare for new connection // idleThreadCheck(); this.switchboard.handleBusyState(this.theSessionPool.getNumActive() /*activeThreads.size() */); log.logDebug( "* waiting for connections, " + this.theSessionPool.getNumActive() + " sessions running, " + this.theSessionPool.getNumIdle() + " sleeping"); // list all connection (debug) /* if (activeThreads.size() > 0) { Enumeration threadEnum = activeThreads.keys(); Session se; long time; while (threadEnum.hasMoreElements()) { se = (Session) threadEnum.nextElement(); time = System.currentTimeMillis() - ((Long) activeThreads.get(se)).longValue(); log.logDebug("* ACTIVE SESSION (" + ((se.isAlive()) ? "alive" : "dead") + ", " + time + "): " + se.request); } } */ // wait for new connection announceThreadBlockApply(); Socket controlSocket = this.socket.accept(); announceThreadBlockRelease(); if ((this.denyHost == null) || (this.denyHost.get((""+controlSocket.getInetAddress().getHostAddress())) == null)) { //log.logDebug("* catched request from " + controlSocket.getInetAddress().getHostAddress()); controlSocket.setSoTimeout(this.timeout); Session connection = (Session) this.theSessionPool.borrowObject(); connection.execute(controlSocket); //try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {} // wait for debug // activeThreads.put(connection, new Long(System.currentTimeMillis())); //log.logDebug("* NEW SESSION: " + connection.request); } else { System.out.println("ACCESS FROM " + controlSocket.getInetAddress().getHostAddress() + " DENIED"); } // idle until number of maximal threads is (again) reached //synchronized(this) { // while ((maxSessions > 0) && (activeThreads.size() >= maxSessions)) try { // log.logDebug("* Waiting for activeThreads=" + activeThreads.size() + " < maxSessions=" + maxSessions); // Thread.currentThread().sleep(2000); // idleThreadCheck(); // } catch (InterruptedException e) {} return true; } #location 40 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int size() { return java.lang.Math.max(assortmentCluster.sizeTotal(), java.lang.Math.max(backend.size(), cache.size())); }
#vulnerable code public int size() { return java.lang.Math.max(singletons.size(), java.lang.Math.max(backend.size(), cache.size())); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void copy(File source, File dest) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); copy(fis, fos); } finally { if (fis != null) try {fis.close();} catch (Exception e) {} if (fos != null) try {fos.close();} catch (Exception e) {} } }
#vulnerable code public static void copy(File source, File dest) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(dest); copy(fis, fos); fis.close(); fos.close(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public serverObjects searchFromRemote(Set hashes, int count, boolean global, long duetime) { if (hashes == null) hashes = new HashSet(); serverObjects prop = new serverObjects(); try { log.logInfo("INIT HASH SEARCH: " + hashes + " - " + count + " links"); long timestamp = System.currentTimeMillis(); plasmaWordIndexEntity idx = searchManager.searchHashes(hashes, duetime * 8 / 10); // a nameless temporary index, not sorted by special order but by hash long remainingTime = duetime - (System.currentTimeMillis() - timestamp); plasmaSearch.result acc = searchManager.order(idx, hashes, stopwords, new char[]{plasmaSearch.O_QUALITY, plasmaSearch.O_AGE}, remainingTime, 10); // result is a List of urlEntry elements if (acc == null) { prop.put("totalcount", "0"); prop.put("linkcount", "0"); prop.put("references", ""); } else { prop.put("totalcount", "" + acc.sizeOrdered()); int i = 0; StringBuffer links = new StringBuffer(); String resource = ""; //plasmaIndexEntry pie; plasmaCrawlLURL.entry urlentry; while ((acc.hasMoreElements()) && (i < count)) { urlentry = acc.nextElement(); resource = urlentry.toString(); if (resource != null) { links.append(resource).append(i).append("=").append(resource).append(serverCore.crlfString); i++; } } prop.put("links", links.toString()); prop.put("linkcount", "" + i); // prepare reference hints Object[] ws = acc.getReferences(16); StringBuffer refstr = new StringBuffer(); for (int j = 0; j < ws.length; j++) refstr.append(",").append((String) ws[j]); prop.put("references", (refstr.length() > 0)?refstr.substring(1):refstr.toString()); } // add information about forward peers prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result prop.put("fwsrc", ""); // peers that helped to construct this result prop.put("fwrec", ""); // peers that would have helped to construct this result (recommendations) // log log.logInfo("EXIT HASH SEARCH: " + hashes + " - " + ((idx == null) ? "0" : (""+idx.size())) + " links, " + ((System.currentTimeMillis() - timestamp) / 1000) + " seconds"); if (idx != null) idx.close(); return prop; } catch (IOException e) { return null; } }
#vulnerable code public serverObjects searchFromRemote(Set hashes, int count, boolean global, long duetime) { if (hashes == null) hashes = new HashSet(); serverObjects prop = new serverObjects(); try { log.logInfo("INIT HASH SEARCH: " + hashes + " - " + count + " links"); long timestamp = System.currentTimeMillis(); plasmaWordIndexEntity idx = searchManager.searchHashes(hashes, duetime * 8 / 10); // a nameless temporary index, not sorted by special order but by hash long remainingTime = duetime - (System.currentTimeMillis() - timestamp); plasmaSearch.result acc = searchManager.order(idx, hashes, stopwords, new char[]{plasmaSearch.O_QUALITY, plasmaSearch.O_AGE}, remainingTime, 10); // result is a List of urlEntry elements if (acc == null) { prop.put("totalcount", "0"); prop.put("linkcount", "0"); prop.put("references", ""); } else { prop.put("totalcount", "" + acc.sizeOrdered()); int i = 0; String links = ""; String resource = ""; //plasmaIndexEntry pie; plasmaCrawlLURL.entry urlentry; while ((acc.hasMoreElements()) && (i < count)) { urlentry = acc.nextElement(); resource = urlentry.toString(); if (resource != null) { links += "resource" + i + "=" + resource + serverCore.crlfString; i++; } } prop.put("links", links); prop.put("linkcount", "" + i); // prepare reference hints Object[] ws = acc.getReferences(16); String refstr = ""; for (int j = 0; j < ws.length; j++) refstr += "," + (String) ws[j]; if (refstr.length() > 0) refstr = refstr.substring(1); prop.put("references", refstr); } // add information about forward peers prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result prop.put("fwsrc", ""); // peers that helped to construct this result prop.put("fwrec", ""); // peers that would have helped to construct this result (recommendations) // log log.logInfo("EXIT HASH SEARCH: " + hashes + " - " + ((idx == null) ? "0" : (""+idx.size())) + " links, " + ((System.currentTimeMillis() - timestamp) / 1000) + " seconds"); if (idx != null) idx.close(); return prop; } catch (IOException e) { return null; } } #location 39 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String readLine() throws IOException { // with these functions, we consider a line as always terminated by CRLF byte[] bb = new byte[80]; int bbsize = 0; int c; while (true) { c = read(); if (c < 0) { if (bbsize == 0) return null; else return new String(bb, 0, bbsize); } if (c == cr) continue; if (c == lf) return new String(bb, 0, bbsize); // append to bb if (bbsize == bb.length) { // extend bb size byte[] newbb = new byte[bb.length * 2]; System.arraycopy(bb, 0, newbb, 0, bb.length); bb = newbb; newbb = null; } bb[bbsize++] = (byte) c; } }
#vulnerable code public String readLine() throws IOException { // with these functions, we consider a line as always terminated by CRLF serverByteBuffer sb = new serverByteBuffer(); int c; while (true) { c = read(); if (c < 0) { if (sb.length() == 0) return null; else return sb.toString(); } if (c == cr) continue; if (c == lf) return sb.toString(); sb.append((byte) c); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void putLastBlockHash(String tipBlockHash) throws Exception { rocksDB.put(SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + "l"), SerializeUtils.serialize(tipBlockHash)); }
#vulnerable code public void putLastBlockHash(String tipBlockHash) throws Exception { rocksDB.put((BLOCKS_BUCKET_PREFIX + "l").getBytes(), tipBlockHash.getBytes()); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Block getBlock(String blockHash) throws Exception { byte[] key = SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + blockHash); return (Block) SerializeUtils.deserialize(rocksDB.get(key)); }
#vulnerable code public Block getBlock(String blockHash) throws Exception { return (Block) SerializeUtils.deserialize(rocksDB.get((BLOCKS_BUCKET_PREFIX + blockHash).getBytes())); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getLastBlockHash() throws Exception { byte[] lastBlockHashBytes = rocksDB.get(SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + "l")); if (lastBlockHashBytes != null) { return (String) SerializeUtils.deserialize(lastBlockHashBytes); } return ""; }
#vulnerable code public String getLastBlockHash() throws Exception { byte[] lastBlockHashBytes = rocksDB.get((BLOCKS_BUCKET_PREFIX + "l").getBytes()); if (lastBlockHashBytes != null) { return new String(lastBlockHashBytes); } return ""; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void informSubVersions(ParserRuleContext ctx, String name, int maxSubStrings) { String text = getSourceText(ctx); if (text==null) { return; } inform(ctx, name, text, false); int startOffsetPrevious = 0; int count = 1; char[] chars = text.toCharArray(); String firstVersions; while((firstVersions = VersionSplitter.getFirstVersions(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstVersions, true); inform(ctx, ctx, name + "%" + count, firstVersions.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = VersionSplitter.findNextVersionStart(chars, firstVersions.length()); } }
#vulnerable code private void informSubVersions(ParserRuleContext ctx, String name, int maxSubStrings) { String text = getSourceText(ctx); inform(ctx, name, text, false); int startOffsetPrevious = 0; int count = 1; char[] chars = text.toCharArray(); String firstVersions; while((firstVersions = VersionSplitter.getFirstVersions(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstVersions, true); inform(ctx, ctx, name + "%" + count, firstVersions.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = VersionSplitter.findNextVersionStart(chars, firstVersions.length()); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadinessCheckFailedHttpCode() { ResponseEntity<String> response = restTemplate.getForEntity("/health/readiness", String.class); Assert.assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode()); }
#vulnerable code @Test public void testReadinessCheckFailedHttpCode() throws IOException { HttpURLConnection huc = (HttpURLConnection) (new URL( "http://localhost:8080/health/readiness").openConnection()); huc.setRequestMethod("HEAD"); huc.connect(); int respCode = huc.getResponseCode(); System.out.println(huc.getResponseMessage()); Assert.assertEquals(503, respCode); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void initialize(ConfigurableApplicationContext applicationContext) { Environment environment = applicationContext.getEnvironment(); if (SOFABootEnvUtils.isSpringCloudBootstrapEnvironment(environment)) { return; } //init logging.level.com.alipay.sofa.runtime argument String runtimeLogLevelKey = Constants.LOG_LEVEL_PREFIX + SofaRuntimeLoggerFactory.SOFA_RUNTIME_LOG_SPACE; SofaBootLogSpaceIsolationInit.initSofaBootLogger(environment, runtimeLogLevelKey); SofaLogger.info("SOFABoot Runtime Starting!"); }
#vulnerable code @Override public void initialize(ConfigurableApplicationContext applicationContext) { Environment environment = applicationContext.getEnvironment(); if (SOFABootEnvUtils.isSpringCloudBootstrapEnvironment(environment)) { return; } //init logging.level.com.alipay.sofa.runtime argument String runtimeLogLevelKey = Constants.LOG_LEVEL_PREFIX + SofaRuntimeLoggerFactory.SOFA_RUNTIME_LOG_SPACE; SofaBootLogSpaceIsolationInit.initSofaBootLogger(environment, runtimeLogLevelKey); SofaRuntimeLoggerFactory.getLogger(SofaRuntimeSpringContextInitializer.class).info( "SOFABoot Runtime Starting!"); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GetMapping("/download/{key:.+}") public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { return ResponseEntity.notFound().build(); } if(key.contains("../")){ return ResponseEntity.badRequest().build(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); }
#vulnerable code @GetMapping("/download/{key:.+}") public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @PostMapping("refund") public Object refund(@LoginAdmin Integer adminId, @RequestBody String body) { if (adminId == null) { return ResponseUtil.unlogin(); } Integer orderId = JacksonUtil.parseInteger(body, "orderId"); String refundMoney = JacksonUtil.parseString(body, "refundMoney"); if (orderId == null) { return ResponseUtil.badArgument(); } LitemallOrder order = orderService.findById(orderId); if (order == null) { return ResponseUtil.badArgument(); } if (order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0) { return ResponseUtil.badArgumentValue(); } // 如果订单不是退款状态,则不能退款 if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) { return ResponseUtil.fail(403, "订单不能确认收货"); } // 开启事务管理 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { // 设置订单取消状态 order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM); orderService.update(order); // 商品货品数量增加 List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId); for (LitemallOrderGoods orderGoods : orderGoodsList) { Integer productId = orderGoods.getProductId(); LitemallProduct product = productService.findById(productId); Integer number = product.getNumber() + orderGoods.getNumber(); product.setNumber(number); productService.updateById(product); } } catch (Exception ex) { txManager.rollback(status); logger.error("系统内部错误", ex); return ResponseUtil.fail(403, "订单退款失败"); } //TODO 发送邮件和短信通知,这里采用异步发送 // 退款成功通知用户 /** * * 您申请的订单退款 [ 单号:{1} ] 已成功,请耐心等待到账。 * 注意订单号只发后6位 * */ litemallNotifyService.notifySMSTemplate(order.getMobile(), ConfigUtil.NotifyType.REFUND, new String[]{order.getOrderSn().substring(8, 14)}); txManager.commit(status); return ResponseUtil.ok(); }
#vulnerable code @PostMapping("refund") public Object refund(@LoginAdmin Integer adminId, @RequestBody String body) { if (adminId == null) { return ResponseUtil.unlogin(); } Integer orderId = JacksonUtil.parseInteger(body, "orderId"); Integer refundMoney = JacksonUtil.parseInteger(body, "refundMoney"); if (orderId == null) { return ResponseUtil.badArgument(); } LitemallOrder order = orderService.findById(orderId); if (order == null) { return ResponseUtil.badArgument(); } if(order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0){ return ResponseUtil.badArgumentValue(); } // 如果订单不是退款状态,则不能退款 if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) { return ResponseUtil.fail(403, "订单不能确认收货"); } // 开启事务管理 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { // 设置订单取消状态 order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM); orderService.update(order); // 商品货品数量增加 List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId); for (LitemallOrderGoods orderGoods : orderGoodsList) { Integer productId = orderGoods.getProductId(); LitemallProduct product = productService.findById(productId); Integer number = product.getNumber() + orderGoods.getNumber(); product.setNumber(number); productService.updateById(product); } } catch (Exception ex) { txManager.rollback(status); logger.error("系统内部错误", ex); return ResponseUtil.fail(403, "订单退款失败"); } txManager.commit(status); return ResponseUtil.ok(); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @PostMapping("comment") public Object comment(@LoginUser Integer userId, @RequestBody String body) { if (userId == null) { return ResponseUtil.unlogin(); } Integer orderGoodsId = JacksonUtil.parseInteger(body, "orderGoodsId"); if(orderGoodsId == null){ return ResponseUtil.badArgument(); } LitemallOrderGoods orderGoods = orderGoodsService.findById(orderGoodsId); if(orderGoods == null){ return ResponseUtil.badArgumentValue(); } Integer orderId = orderGoods.getOrderId(); LitemallOrder order = orderService.findById(orderId); if(order == null){ return ResponseUtil.badArgumentValue(); } Short orderStatus = order.getOrderStatus(); if(!OrderUtil.isConfirmStatus(order) && !OrderUtil.isAutoConfirmStatus(order)) { return ResponseUtil.fail(404, "当前商品不能评价"); } if(!order.getUserId().equals(userId)){ return ResponseUtil.fail(404, "当前商品不属于用户"); } Integer commentId = orderGoods.getComment(); if(commentId == -1){ return ResponseUtil.fail(404, "当前商品评价时间已经过期"); } if(commentId != 0){ return ResponseUtil.fail(404, "订单商品已评价"); } String content = JacksonUtil.parseString(body, "content"); Integer star = JacksonUtil.parseInteger(body, "star"); if(star == null || star < 0 || star > 5){ return ResponseUtil.badArgumentValue(); } Boolean hasPicture = JacksonUtil.parseBoolean(body, "hasPicture"); List<String> picUrls = JacksonUtil.parseStringList(body, "picUrls"); if(hasPicture == null || !hasPicture){ picUrls = new ArrayList<>(0); } // 1. 创建评价 LitemallComment comment = new LitemallComment(); comment.setUserId(userId); comment.setType((byte)0); comment.setValueId(orderGoods.getGoodsId()); comment.setStar(star.shortValue()); comment.setContent(content); comment.setHasPicture(hasPicture); comment.setPicUrls(picUrls.toArray(new String[]{})); commentService.save(comment); // 2. 更新订单商品的评价列表 orderGoods.setComment(comment.getId()); orderGoodsService.updateById(orderGoods); // 3. 更新订单中未评价的订单商品可评价数量 Short commentCount = order.getComments(); if(commentCount > 0){ commentCount--; } order.setComments(commentCount); orderService.updateWithOptimisticLocker(order); return ResponseUtil.ok(); }
#vulnerable code @PostMapping("comment") public Object comment(@LoginUser Integer userId, @RequestBody String body) { if (userId == null) { return ResponseUtil.unlogin(); } Integer orderGoodsId = JacksonUtil.parseInteger(body, "orderGoodsId"); if(orderGoodsId == null){ return ResponseUtil.badArgument(); } LitemallOrderGoods orderGoods = orderGoodsService.findById(orderGoodsId); if(orderGoods == null){ return ResponseUtil.badArgumentValue(); } Integer orderId = orderGoods.getOrderId(); LitemallOrder order = orderService.findById(orderId); if(order == null){ return ResponseUtil.badArgumentValue(); } Short orderStatus = order.getOrderStatus(); if(!OrderUtil.isConfirmStatus(order) && !OrderUtil.isAutoConfirmStatus(order)) { return ResponseUtil.fail(404, "当前商品不能评价"); } if(!order.getUserId().equals(userId)){ return ResponseUtil.fail(404, "当前商品不属于用户"); } Integer commentId = orderGoods.getComment(); if(commentId == -1){ return ResponseUtil.fail(404, "当前商品评价时间已经过期"); } if(commentId != 0){ return ResponseUtil.fail(404, "订单商品已评价"); } String content = JacksonUtil.parseString(body, "content"); Integer star = JacksonUtil.parseInteger(body, "star"); if(star == null || star < 0 || star > 5){ return ResponseUtil.badArgumentValue(); } Boolean hasPicture = JacksonUtil.parseBoolean(body, "hasPicture"); List<String> picUrls = JacksonUtil.parseStringList(body, "picUrls"); if(hasPicture == null || !hasPicture){ picUrls = new ArrayList<>(0); } // 1. 创建评价 LitemallComment comment = new LitemallComment(); comment.setUserId(userId); comment.setValueId(orderGoods.getGoodsId()); comment.setType((byte)1); comment.setContent(content); comment.setHasPicture(hasPicture); comment.setPicUrls(picUrls.toArray(new String[]{})); commentService.save(comment); // 2. 更新订单商品的评价列表 orderGoods.setComment(comment.getId()); orderGoodsService.updateById(orderGoods); // 3. 更新订单中未评价的订单商品可评价数量 Short commentCount = order.getComments(); if(commentCount > 0){ commentCount--; } order.setComments(commentCount); orderService.updateWithOptimisticLocker(order); return ResponseUtil.ok(); } #location 53 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void loadConfigFile(){ JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject) parser.parse(new FileReader(CONFIG_FILE)); JSONArray buttons = (JSONArray) root.get("buttons"); cachedButtonsConfig = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) buttons) { cachedButtonsConfig.put((String) next.get("title"), (String) next.get("value")); } JSONArray framesSetting = (JSONArray) root.get("framesSettings"); cachedFramesSettings = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) framesSetting) { JSONObject location = (JSONObject) next.get("location"); JSONObject size = (JSONObject) next.get("size"); FrameSettings settings = new FrameSettings( new Point(((Long)location.get("frameX")).intValue(), ((Long)location.get("frameY")).intValue()), new Dimension(((Long)size.get("width")).intValue(),((Long)size.get("height")).intValue()) ); cachedFramesSettings.put((String) next.get("frameClassName"), settings); } whisperNotifier = WhisperNotifierStatus.valueOf(loadProperty("whisperNotifier")); decayTime = Long.valueOf(loadProperty("decayTime")).intValue(); minOpacity = Long.valueOf(loadProperty("minOpacity")).intValue(); maxOpacity = Long.valueOf(loadProperty("maxOpacity")).intValue(); showOnStartUp = Boolean.valueOf(loadProperty("showOnStartUp")); showPatchNotes = Boolean.valueOf(loadProperty("showPatchNotes")); gamePath = loadProperty("gamePath"); } catch (Exception e) { logger.error("Error in loadConfigFile: ",e); } }
#vulnerable code private void loadConfigFile(){ JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject) parser.parse(new FileReader(CONFIG_FILE)); JSONArray buttons = (JSONArray) root.get("buttons"); cachedButtonsConfig = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) buttons) { cachedButtonsConfig.put((String) next.get("title"), (String) next.get("value")); } JSONArray framesSetting = (JSONArray) root.get("framesSettings"); cachedFramesSettings = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) framesSetting) { JSONObject location = (JSONObject) next.get("location"); JSONObject size = (JSONObject) next.get("size"); FrameSettings settings = new FrameSettings( new Point(((Long)location.get("frameX")).intValue(), ((Long)location.get("frameY")).intValue()), new Dimension(((Long)size.get("width")).intValue(),((Long)size.get("height")).intValue()) ); cachedFramesSettings.put((String) next.get("frameClassName"), settings); } whisperNotifier = WhisperNotifierStatus.valueOf((String)root.get("whisperNotifier")); decayTime = ((Long)root.get("decayTime")).intValue(); minOpacity = ((Long)root.get("minOpacity")).intValue(); maxOpacity = ((Long)root.get("maxOpacity")).intValue(); showOnStartUp = (boolean) root.get("showOnStartUp"); showPatchNotes = (boolean) root.get("showPatchNotes"); } catch (Exception e) { logger.error("Error in loadConfigFile: ",e); } } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] tryDecompress(byte[] raw) throws Exception { if (!isGzipStream(raw)) { return raw; } GZIPInputStream gis = null; ByteArrayOutputStream out = null; try { gis = new GZIPInputStream(new ByteArrayInputStream(raw)); out = new ByteArrayOutputStream(); IoUtils.copy(gis, out); return out.toByteArray(); } finally { if (out != null) { out.close(); } if (gis != null) { gis.close(); } } }
#vulnerable code public static byte[] tryDecompress(byte[] raw) throws Exception { if (!isGzipStream(raw)) { return raw; } GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(raw)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IoUtils.copy(gis, out); return out.toByteArray(); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); }
#vulnerable code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8")); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); } #location 47 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] tryDecompress(InputStream raw) throws Exception { try { GZIPInputStream gis = new GZIPInputStream(raw); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(gis, out); return out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; }
#vulnerable code public static byte[] tryDecompress(InputStream raw) throws Exception { try { GZIPInputStream gis = new GZIPInputStream(raw); ByteArrayOutputStream out = new ByteArrayOutputStream(); IoUtils.copy(gis, out); return out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void contextPrepared(ConfigurableApplicationContext context) { }
#vulnerable code @Override public void contextPrepared(ConfigurableApplicationContext context) { System.out.printf("Log files: %s/logs/%n", NACOS_HOME); System.out.printf("Conf files: %s/conf/%n", NACOS_HOME); System.out.printf("Data files: %s/data/%n", NACOS_HOME); if (!STANDALONE_MODE) { try { List<String> clusterConf = readClusterConf(); System.out.printf("The server IP list of Nacos is %s%n", clusterConf); } catch (IOException e) { logger.error("read cluster conf fail", e); } } System.out.println(); } #location 5 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); }
#vulnerable code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap = null; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); } #location 34 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = readClusterConf(); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = readClusterConf(); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = readClusterConf(); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); }
#vulnerable code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8")); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); } #location 47 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); Set<String> currentInstanceIds = Sets.newHashSet(); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); currentInstanceIds.add(instance.getInstanceId()); } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instance.setInstanceId(instance.generateInstanceId(currentInstanceIds)); instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); }
#vulnerable code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); Set<Integer> currentInstanceIndexes = Sets.newHashSet(); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); if (instance.getInstanceIndex() != null) { currentInstanceIndexes.add(instance.getInstanceIndex()); } } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { // Generate instance index int instanceIndex = 0; while (currentInstanceIndexes.contains(instanceIndex)) { instanceIndex++; } currentInstanceIndexes.add(instanceIndex); instance.setInstanceIndex(instanceIndex); instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void registerInstance(String namespaceId, String serviceName, String clusterName, Instance instance) throws Exception { Service service = getService(namespaceId, serviceName); boolean serviceUpdated = false; if (service == null) { service = new Service(); service.setName(serviceName); service.setNamespaceId(namespaceId); // now validate the service. if failed, exception will be thrown service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(); cluster.setName(instance.getClusterName()); cluster.setDom(service); cluster.init(); if (service.getClusterMap().containsKey(cluster.getName())) { service.getClusterMap().get(cluster.getName()).update(cluster); } else { service.getClusterMap().put(cluster.getName(), cluster); } service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } // only local memory is updated: if (serviceUpdated) { putService(service); } if (service.allIPs().contains(instance)) { throw new NacosException(NacosException.INVALID_PARAM, "instance already exist: " + instance); } addInstance(namespaceId, serviceName, clusterName, instance.isEphemeral(), instance); }
#vulnerable code public void registerInstance(String namespaceId, String serviceName, String clusterName, Instance instance) throws Exception { Service service = getService(namespaceId, serviceName); boolean serviceUpdated = false; if (service == null) { service = new Service(); service.setName(serviceName); service.setNamespaceId(namespaceId); // now validate the service. if failed, exception will be thrown service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(); cluster.setName(instance.getClusterName()); cluster.setDom(service); cluster.init(); if (service.getClusterMap().containsKey(cluster.getName())) { service.getClusterMap().get(cluster.getName()).update(cluster); } else { service.getClusterMap().put(cluster.getName(), cluster); } service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (serviceUpdated) { Lock lock = addLockIfAbsent(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); Condition condition = addCondtion(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); final Service finalService = service; GlobalExecutor.submit(new Runnable() { @Override public void run() { try { addOrReplaceService(finalService); } catch (Exception e) { Loggers.SRV_LOG.error("register or update service failed, service: {}", finalService, e); } } }); try { lock.lock(); condition.await(5000, TimeUnit.MILLISECONDS); } finally { lock.unlock(); } } if (service.allIPs().contains(instance)) { throw new NacosException(NacosException.INVALID_PARAM, "instance already exist: " + instance); } addInstance(namespaceId, serviceName, clusterName, instance.isEphemeral(), instance); } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void checkLocalConfig(CacheData cacheData) { final String dataId = cacheData.dataId; final String group = cacheData.group; final String tenant = cacheData.tenant; File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant); // 没有 -> 有 if (!cacheData.isUseLocalConfigInfo() && path.exists()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); return; } // 有 -> 没有。不通知业务监听器,从server拿到配置后通知。 if (cacheData.isUseLocalConfigInfo() && !path.exists()) { cacheData.setUseLocalConfigInfo(false); LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(), dataId, group, tenant); return; } // 有变更 if (cacheData.isUseLocalConfigInfo() && path.exists() && cacheData.getLocalConfigInfoVersion() != path.lastModified()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); } }
#vulnerable code private void checkLocalConfig(CacheData cacheData) { final String dataId = cacheData.dataId; final String group = cacheData.group; final String tenant = cacheData.tenant; File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant); // 没有 -> 有 if (!cacheData.isUseLocalConfigInfo() && path.exists()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5.getInstance().getMD5String(content); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); return; } // 有 -> 没有。不通知业务监听器,从server拿到配置后通知。 if (cacheData.isUseLocalConfigInfo() && !path.exists()) { cacheData.setUseLocalConfigInfo(false); LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(), dataId, group, tenant); return; } // 有变更 if (cacheData.isUseLocalConfigInfo() && path.exists() && cacheData.getLocalConfigInfoVersion() != path.lastModified()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5.getInstance().getMD5String(content); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void update(SwitchDomain newSwitchDomain) { switchDomain.setMasters(newSwitchDomain.getMasters()); switchDomain.setAdWeightMap(newSwitchDomain.getAdWeightMap()); switchDomain.setDefaultPushCacheMillis(newSwitchDomain.getDefaultPushCacheMillis()); switchDomain.setClientBeatInterval(newSwitchDomain.getClientBeatInterval()); switchDomain.setDefaultCacheMillis(newSwitchDomain.getDefaultCacheMillis()); switchDomain.setDistroThreshold(newSwitchDomain.getDistroThreshold()); switchDomain.setHealthCheckEnabled(newSwitchDomain.isHealthCheckEnabled()); switchDomain.setDistroEnabled(newSwitchDomain.isDistroEnabled()); switchDomain.setPushEnabled(newSwitchDomain.isPushEnabled()); switchDomain.setEnableStandalone(newSwitchDomain.isEnableStandalone()); switchDomain.setCheckTimes(newSwitchDomain.getCheckTimes()); switchDomain.setHttpHealthParams(newSwitchDomain.getHttpHealthParams()); switchDomain.setTcpHealthParams(newSwitchDomain.getTcpHealthParams()); switchDomain.setMysqlHealthParams(newSwitchDomain.getMysqlHealthParams()); switchDomain.setIncrementalList(newSwitchDomain.getIncrementalList()); switchDomain.setServerStatusSynchronizationPeriodMillis(newSwitchDomain.getServerStatusSynchronizationPeriodMillis()); switchDomain.setServiceStatusSynchronizationPeriodMillis(newSwitchDomain.getServiceStatusSynchronizationPeriodMillis()); switchDomain.setDisableAddIP(newSwitchDomain.isDisableAddIP()); switchDomain.setSendBeatOnly(newSwitchDomain.isSendBeatOnly()); switchDomain.setLimitedUrlMap(newSwitchDomain.getLimitedUrlMap()); switchDomain.setDistroServerExpiredMillis(newSwitchDomain.getDistroServerExpiredMillis()); switchDomain.setPushGoVersion(newSwitchDomain.getPushGoVersion()); switchDomain.setPushJavaVersion(newSwitchDomain.getPushJavaVersion()); switchDomain.setPushPythonVersion(newSwitchDomain.getPushPythonVersion()); switchDomain.setPushCVersion(newSwitchDomain.getPushCVersion()); switchDomain.setEnableAuthentication(newSwitchDomain.isEnableAuthentication()); switchDomain.setOverriddenServerStatus(newSwitchDomain.getOverriddenServerStatus()); switchDomain.setDefaultInstanceEphemeral(newSwitchDomain.isDefaultInstanceEphemeral()); }
#vulnerable code public void update(SwitchDomain newSwitchDomain) { switchDomain.setMasters(newSwitchDomain.getMasters()); switchDomain.setAdWeightMap(newSwitchDomain.getAdWeightMap()); switchDomain.setDefaultPushCacheMillis(newSwitchDomain.getDefaultPushCacheMillis()); switchDomain.setClientBeatInterval(newSwitchDomain.getClientBeatInterval()); switchDomain.setDefaultCacheMillis(newSwitchDomain.getDefaultCacheMillis()); switchDomain.setDistroThreshold(newSwitchDomain.getDistroThreshold()); switchDomain.setHealthCheckEnabled(newSwitchDomain.isHealthCheckEnabled()); switchDomain.setDistroEnabled(newSwitchDomain.isDistroEnabled()); switchDomain.setPushEnabled(newSwitchDomain.isPushEnabled()); switchDomain.setEnableStandalone(newSwitchDomain.isEnableStandalone()); switchDomain.setCheckTimes(newSwitchDomain.getCheckTimes()); switchDomain.setHttpHealthParams(newSwitchDomain.getHttpHealthParams()); switchDomain.setTcpHealthParams(newSwitchDomain.getTcpHealthParams()); switchDomain.setMysqlHealthParams(newSwitchDomain.getMysqlHealthParams()); switchDomain.setIncrementalList(newSwitchDomain.getIncrementalList()); switchDomain.setServerStatusSynchronizationPeriodMillis(newSwitchDomain.getServerStatusSynchronizationPeriodMillis()); switchDomain.setServiceStatusSynchronizationPeriodMillis(newSwitchDomain.getServiceStatusSynchronizationPeriodMillis()); switchDomain.setDisableAddIP(newSwitchDomain.isDisableAddIP()); switchDomain.setSendBeatOnly(newSwitchDomain.isSendBeatOnly()); switchDomain.setLimitedUrlMap(newSwitchDomain.getLimitedUrlMap()); switchDomain.setDistroServerExpiredMillis(newSwitchDomain.getDistroServerExpiredMillis()); switchDomain.setPushGoVersion(newSwitchDomain.getPushGoVersion()); switchDomain.setPushJavaVersion(newSwitchDomain.getPushJavaVersion()); switchDomain.setPushPythonVersion(newSwitchDomain.getPushPythonVersion()); switchDomain.setPushCVersion(newSwitchDomain.getPushCVersion()); switchDomain.setEnableAuthentication(newSwitchDomain.isEnableAuthentication()); switchDomain.setOverriddenServerStatus(newSwitchDomain.getOverriddenServerStatus()); switchDomain.setServerMode(newSwitchDomain.getServerMode()); } #location 29 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @NeedAuth @RequestMapping("/remvIP4Dom") public String remvIP4Dom(HttpServletRequest request) throws Exception { String dom = WebUtils.required(request, "dom"); String ipListString = WebUtils.required(request, "ipList"); Map<String, String> proxyParams = new HashMap<>(16); for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { proxyParams.put(entry.getKey(), entry.getValue()[0]); } if (Loggers.DEBUG_LOG.isDebugEnabled()) { Loggers.DEBUG_LOG.debug("[REMOVE-IP] full arguments: params:" + proxyParams); } List<String> ipList = new ArrayList<>(); List<IpAddress> ipObjList = new ArrayList<>(ipList.size()); if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { ipList = Arrays.asList(ipListString); ipObjList = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() { }); } else { ipList = Arrays.asList(ipListString.split(",")); for (String ip : ipList) { ipObjList.add(IpAddress.fromJSON(ip)); } } if (!RaftCore.isLeader()) { Loggers.RAFT.info("I'm not leader, will proxy to leader."); if (RaftCore.getLeader() == null) { throw new IllegalArgumentException("no leader now."); } RaftPeer leader = RaftCore.getLeader(); String server = leader.ip; if (!server.contains(UtilsAndCommons.CLUSTER_CONF_IP_SPLITER)) { server = server + UtilsAndCommons.CLUSTER_CONF_IP_SPLITER + RunningConfig.getServerPort(); } String url = "http://" + server + RunningConfig.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/api/remvIP4Dom"; HttpClient.HttpResult result1 = HttpClient.httpPost(url, null, proxyParams); if (result1.code != HttpURLConnection.HTTP_OK) { Loggers.SRV_LOG.warn("failed to remove ip for dom, caused " + result1.content); throw new IllegalArgumentException("failed to remove ip for dom, caused " + result1.content); } return "ok"; } VirtualClusterDomain domain = (VirtualClusterDomain) domainsManager.getDomain(dom); if (domain == null) { throw new IllegalStateException("dom doesn't exist: " + dom); } if (CollectionUtils.isEmpty(ipObjList)) { throw new IllegalArgumentException("Empty ip list"); } String key = UtilsAndCommons.getIPListStoreKey(domainsManager.getDomain(dom)); long timestamp = 1; if (RaftCore.getDatum(key) != null) { timestamp = RaftCore.getDatum(key).timestamp.get(); } if (RaftCore.isLeader()) { try { RaftCore.OPERATE_LOCK.lock(); proxyParams.put("clientIP", NetUtils.localServer()); proxyParams.put("notify", "true"); proxyParams.put("term", String.valueOf(RaftCore.getPeerSet().local().term)); proxyParams.put("timestamp", String.valueOf(timestamp)); onRemvIP4Dom(MockHttpRequest.buildRequest2(proxyParams)); if (domain.getEnableHealthCheck() && !domain.getEnableClientBeat()) { syncOnRemvIP4Dom(dom, ipList, proxyParams, WebUtils.optional(request, "clientIP", "unknown")); } else { asyncOnRemvIP4Dom(dom, ipList, proxyParams, WebUtils.optional(request, "clientIP", "unknown")); } } finally { RaftCore.OPERATE_LOCK.unlock(); } Loggers.EVT_LOG.info("{" + dom + "} {POS} {IP-REMV}" + " new: " + ipListString + " operatorIP: " + WebUtils.optional(request, "clientIP", "unknown")); } return "ok"; }
#vulnerable code @NeedAuth @RequestMapping("/remvIP4Dom") public String remvIP4Dom(HttpServletRequest request) throws Exception { String dom = WebUtils.required(request, "dom"); String ipListString = WebUtils.required(request, "ipList"); Loggers.DEBUG_LOG.debug("[REMOVE-IP] full arguments: serviceName:" + dom + ", iplist:" + ipListString); List<IpAddress> newIPs = new ArrayList<>(); List<String> ipList = new ArrayList<>(); if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { newIPs = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() { }); } else { ipList = Arrays.asList(ipListString.split(",")); } List<IpAddress> ipObjList = new ArrayList<>(ipList.size()); if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { ipObjList = newIPs; } else { for (String ip : ipList) { ipObjList.add(IpAddress.fromJSON(ip)); } } domainsManager.easyRemvIP4Dom(dom, ipObjList); Loggers.EVT_LOG.info("{" + dom + "} {POS} {IP-REMV}" + " dead: " + ipList + " operator: " + WebUtils.optional(request, "clientIP", "unknown")); return "ok"; } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = readClusterConf(); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = readClusterConf(); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = readClusterConf(); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); }
#vulnerable code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8")); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); } #location 47 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); }
#vulnerable code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap = null; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void subTypes() throws Exception { VCard vcard = new VCard(); //one sub type AddressType adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); vcard.addAddress(adr); //two types adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); adr.getSubTypes().put("LANGUAGE", "FR"); adr.getSubTypes().put("LANGUAGE", "es"); vcard.addAddress(adr); //three types //make sure it properly escapes sub type values that have special chars adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); adr.getSubTypes().put("LANGUAGE", "FR"); adr.getSubTypes().put("LANGUAGE", "es"); adr.getSubTypes().put("TEXT", "123 \"Main\" St\r\nAustin, ;TX; 12345"); vcard.addAddress(adr); //2.1 StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null, "\r\n"); vcw.setAddProdId(false); vcw.write(vcard); String actual = sw.toString(); StringBuilder sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:2.1\r\n"); sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n"); sb.append("END:VCARD\r\n"); String expected = sb.toString(); assertEquals(expected, actual); //3.0 sw = new StringWriter(); vcw = new VCardWriter(sw, VCardVersion.V3_0, null, "\r\n"); vcw.setAddProdId(false); vcw.write(vcard); actual = sw.toString(); sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:3.0\r\n"); sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR,es;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR,es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n"); sb.append("END:VCARD\r\n"); expected = sb.toString(); assertEquals(expected, actual); }
#vulnerable code @Test public void subTypes() throws Exception { VCard vcard = new VCard(); //one sub type AddressType adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); vcard.addAddress(adr); //two types adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); adr.getSubTypes().put("LANGUAGE", "FR"); adr.getSubTypes().put("LANGUAGE", "es"); vcard.addAddress(adr); //three types //make sure it properly escapes sub type values that have special chars adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); adr.getSubTypes().put("LANGUAGE", "FR"); adr.getSubTypes().put("LANGUAGE", "es"); adr.getSubTypes().put("TEXT", "123 \"Main\" St\r\nAustin, ;TX; 12345"); vcard.addAddress(adr); //2.1 StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null); vcw.setAddProdId(false); vcw.write(vcard); String actual = sw.toString(); StringBuilder sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:2.1\r\n"); sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n"); sb.append("END:VCARD\r\n"); String expected = sb.toString(); assertEquals(expected, actual); //3.0 sw = new StringWriter(); vcw = new VCardWriter(sw, VCardVersion.V3_0, null); vcw.setAddProdId(false); vcw.write(vcard); actual = sw.toString(); sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:3.0\r\n"); sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR,es;X-DOORMAN=true:;;;;;;\r\n"); sb.append("ADR;LANGUAGE=FR,es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n"); sb.append("END:VCARD\r\n"); expected = sb.toString(); assertEquals(expected, actual); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void msOutlookVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MS_OUTLOOK.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("en-us", f.getSubTypes().getLanguage()); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Richter", "James"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Sr."), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. John Richter James Doe Sr.", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Money Counter", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("(905) 555-1234", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(905) 666-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Cresent moon drive", f.getStreetAddress()); assertEquals("Albaney", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("Cresent moon drive\r\nAlbaney, New York 12345", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Silicon Alley 5,", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("Silicon Alley 5,\r\nNew York, New York 12345", f.getLabel()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.ibm.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 22); assertEquals(c.getTime(), f.getDate()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(860, f.getData().length); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 5); c.set(Calendar.HOUR_OF_DAY, 13); c.set(Calendar.MINUTE, 19); c.set(Calendar.SECOND, 33); assertEquals(c.getTime(), f.getTimestamp()); } //extended types { assertEquals(6, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20110113", f.getValue()); f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); assertEquals("X-MS-OL-DESIGN", f.getTypeName()); assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue()); assertEquals("utf-8", f.getSubTypes().getCharset()); f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("Big Blue", f.getValue()); f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("Jenny", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void msOutlookVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MS_OUTLOOK.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("en-us", f.getSubTypes().getLanguage()); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Richter", "James"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Sr."), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. John Richter James Doe Sr.", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Money Counter", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("(905) 555-1234", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(905) 666-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Cresent moon drive", f.getStreetAddress()); assertEquals("Albaney", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("Cresent moon drive\r\nAlbaney, New York 12345", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Silicon Alley 5,", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("Silicon Alley 5,\r\nNew York, New York 12345", f.getLabel()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.ibm.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 22); assertEquals(c.getTime(), f.getDate()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(860, f.getData().length); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 5); c.set(Calendar.HOUR_OF_DAY, 13); c.set(Calendar.MINUTE, 19); c.set(Calendar.SECOND, 33); assertEquals(c.getTime(), f.getTimestamp()); } //extended types { assertEquals(6, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20110113", f.getValue()); f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); assertEquals("X-MS-OL-DESIGN", f.getTypeName()); assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue()); assertEquals("utf-8", f.getSubTypes().getCharset()); f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("Big Blue", f.getValue()); f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("Jenny", f.getValue()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void lotusNotesVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Johny"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("I"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Doe John I Johny", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny,JayJay"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "SUN"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Generic Accountant", f.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("+1 (212) 204-34456", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("00-1-212-555-7777", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("25334" + NEWLINE + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("NYC887", f.getPostalCode()); assertEquals("U.S.A.", f.getCountry()); assertNull(f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + NEWLINE + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + NEWLINE + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + NEWLINE + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + NEWLINE + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + NEWLINE + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + NEWLINE + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + NEWLINE + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + NEWLINE + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + NEWLINE + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + NEWLINE + " POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item2", f.getGroup()); assertEquals("http://www.sun.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MAY); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(7957, f.getData().length); assertFalse(it.hasNext()); } //UID { UidType f = vcard.getUid(); assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue()); } //GEO { GeoType f = vcard.getGeo(); assertEquals(-2.6, f.getLatitude(), .01); assertEquals(3.4, f.getLongitude(), .01); } //CLASS { ClassificationType f = vcard.getClassification(); assertEquals("Public", f.getValue()); } //PROFILE { ProfileType f = vcard.getProfile(); assertEquals("VCard", f.getValue()); } //TZ { TimezoneType f = vcard.getTimezone(); assertIntEquals(1, f.getHourOffset()); assertIntEquals(0, f.getMinuteOffset()); } //LABEL { Iterator<LabelType> it = vcard.getOrphanedLabels().iterator(); LabelType f = it.next(); assertEquals("John Doe" + NEWLINE + "New York, NewYork," + NEWLINE + "South Crecent Drive," + NEWLINE + "Building 5, floor 3," + NEWLINE + "USA", f.getValue()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PARCEL)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //SORT-STRING { SortStringType f = vcard.getSortString(); assertEquals("JOHN", f.getValue()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //SOURCE { Iterator<SourceType> it = vcard.getSources().iterator(); SourceType f = it.next(); assertEquals("Whatever", f.getValue()); assertFalse(it.hasNext()); } //MAILER { MailerType f = vcard.getMailer(); assertEquals("Mozilla Thunderbird", f.getValue()); } //NAME { SourceDisplayTextType f = vcard.getSourceDisplayText(); assertEquals("VCard for John Doe", f.getValue()); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); f = vcard.getExtendedProperties("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue()); f = vcard.getExtendedProperties("X-GENERATOR").get(0); assertEquals("X-GENERATOR", f.getTypeName()); assertEquals("Cardme Generator", f.getValue()); f = vcard.getExtendedProperties("X-LONG-STRING").get(0); assertEquals("X-LONG-STRING", f.getTypeName()); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void lotusNotesVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Johny"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("I"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Doe John I Johny", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny,JayJay"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "SUN"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Generic Accountant", f.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("+1 (212) 204-34456", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("00-1-212-555-7777", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("25334" + NEWLINE + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("NYC887", f.getPostalCode()); assertEquals("U.S.A.", f.getCountry()); assertNull(f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + NEWLINE + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + NEWLINE + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + NEWLINE + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + NEWLINE + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + NEWLINE + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + NEWLINE + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + NEWLINE + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + NEWLINE + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + NEWLINE + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + NEWLINE + " POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item2", f.getGroup()); assertEquals("http://www.sun.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MAY); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(7957, f.getData().length); assertFalse(it.hasNext()); } //UID { UidType f = vcard.getUid(); assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue()); } //GEO { GeoType f = vcard.getGeo(); assertEquals(-2.6, f.getLatitude(), .01); assertEquals(3.4, f.getLongitude(), .01); } //CLASS { ClassificationType f = vcard.getClassification(); assertEquals("Public", f.getValue()); } //PROFILE { ProfileType f = vcard.getProfile(); assertEquals("VCard", f.getValue()); } //TZ { TimezoneType f = vcard.getTimezone(); assertIntEquals(1, f.getHourOffset()); assertIntEquals(0, f.getMinuteOffset()); } //LABEL { Iterator<LabelType> it = vcard.getOrphanedLabels().iterator(); LabelType f = it.next(); assertEquals("John Doe" + NEWLINE + "New York, NewYork," + NEWLINE + "South Crecent Drive," + NEWLINE + "Building 5, floor 3," + NEWLINE + "USA", f.getValue()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PARCEL)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //SORT-STRING { SortStringType f = vcard.getSortString(); assertEquals("JOHN", f.getValue()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //SOURCE { Iterator<SourceType> it = vcard.getSources().iterator(); SourceType f = it.next(); assertEquals("Whatever", f.getValue()); assertFalse(it.hasNext()); } //MAILER { MailerType f = vcard.getMailer(); assertEquals("Mozilla Thunderbird", f.getValue()); } //NAME { SourceDisplayTextType f = vcard.getSourceDisplayText(); assertEquals("VCard for John Doe", f.getValue()); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); f = vcard.getExtendedProperties("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue()); f = vcard.getExtendedProperties("X-GENERATOR").get(0); assertEquals("X-GENERATOR", f.getTypeName()); assertEquals("Cardme Generator", f.getValue()); f = vcard.getExtendedProperties("X-LONG-STRING").get(0); assertEquals("X-LONG-STRING", f.getTypeName()); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void doUnmarshalValue(String value, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) { if (subTypes.getValue() != null) { setUrl(VCardStringUtils.unescape(value)); } else { //instruct the marshaller to look for an embedded vCard throw new EmbeddedVCardException(new EmbeddedVCardException.InjectionCallback() { public void injectVCard(VCard vcard) { setVcard(vcard); } }); } }
#vulnerable code @Override protected void doUnmarshalValue(String value, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) { value = VCardStringUtils.unescape(value); if (subTypes.getValue() != null) { url = value; } else { VCardReader reader = new VCardReader(new StringReader(value)); reader.setCompatibilityMode(compatibilityMode); try { vcard = reader.readNext(); } catch (IOException e) { //reading from a string } for (String w : reader.getWarnings()) { warnings.add("AGENT unmarshal warning: " + w); } } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void outlook2007VCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("en-us", f.getSubTypes().getLanguage()); assertEquals("Angstadt", f.getFamily()); assertEquals("Michael", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Jr."), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Michael Angstadt Jr.", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Mike"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheJobTitle", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue()); assertEquals("us-ascii", f.getSubTypes().getCharset()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("(111) 555-1111", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-2222", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-4444", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-3333", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("222 Broadway", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("99999", f.getPostalCode()); assertEquals("USA", f.getCountry()); assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("HOME")); f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1922); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 10); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(514, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(2324, f.getData().length); assertFalse(it.hasNext()); } //FBURL { //a 4.0 property in a 2.1 vCard... Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); FbUrlType f = it.next(); assertEquals("http://website.com/mycal", f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.AUGUST); c.set(Calendar.DAY_OF_MONTH, 1); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 46); c.set(Calendar.SECOND, 31); assertEquals(c.getTime(), f.getTimestamp()); } //extended types { assertEquals(8, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-MS-TEL").get(0); assertEquals("X-MS-TEL", f.getTypeName()); assertEquals("(111) 555-4444", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(2, types.size()); assertTrue(types.contains("VOICE")); assertTrue(types.contains("CALLBACK")); f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20120801", f.getValue()); f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); assertEquals("X-MS-OL-DESIGN", f.getTypeName()); assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue()); assertEquals("utf-8", f.getSubTypes().getCharset()); f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("TheManagerName", f.getValue()); f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("TheAssistantName", f.getValue()); f = vcard.getExtendedProperties("X-MS-SPOUSE").get(0); assertEquals("X-MS-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void outlook2007VCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("en-us", f.getSubTypes().getLanguage()); assertEquals("Angstadt", f.getFamily()); assertEquals("Michael", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Jr."), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Michael Angstadt Jr.", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Mike"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheJobTitle", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue()); assertEquals("us-ascii", f.getSubTypes().getCharset()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("(111) 555-1111", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-2222", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-4444", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-3333", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("222 Broadway", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("99999", f.getPostalCode()); assertEquals("USA", f.getCountry()); assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("HOME")); f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1922); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 10); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(514, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(2324, f.getData().length); assertFalse(it.hasNext()); } //FBURL { //a 4.0 property in a 2.1 vCard... Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); FbUrlType f = it.next(); assertEquals("http://website.com/mycal", f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.AUGUST); c.set(Calendar.DAY_OF_MONTH, 1); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 46); c.set(Calendar.SECOND, 31); assertEquals(c.getTime(), f.getTimestamp()); } //extended types { assertEquals(8, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-MS-TEL").get(0); assertEquals("X-MS-TEL", f.getTypeName()); assertEquals("(111) 555-4444", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(2, types.size()); assertTrue(types.contains("VOICE")); assertTrue(types.contains("CALLBACK")); f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20120801", f.getValue()); f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); assertEquals("X-MS-OL-DESIGN", f.getTypeName()); assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue()); assertEquals("utf-8", f.getSubTypes().getCharset()); f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("TheManagerName", f.getValue()); f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("TheAssistantName", f.getValue()); f = vcard.getExtendedProperties("X-MS-SPOUSE").get(0); assertEquals("X-MS-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void gmailVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf")); reader.setCompatibilityMode(CompatibilityMode.GMAIL); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. John Richter, James Doe Sr.", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Richter, James"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Sr."), f.getSuffixes()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("home"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("905-555-1234", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-666-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("Crescent moon drive" + newline + "555-asd" + newline + "Nice Area, Albaney, New York12345" + newline + "United States of America", f.getExtendedAddress()); assertEquals(null, f.getStreetAddress()); assertEquals(null, f.getLocality()); assertEquals(null, f.getRegion()); assertEquals(null, f.getPostalCode()); assertEquals(null, f.getCountry()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertFalse(it.hasNext()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Money Counter", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 22); assertEquals(c.getTime(), f.getDate()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.ibm.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + newline + "Favotire Color: Blue", f.getValue()); assertFalse(it.hasNext()); } //extended types { assertEquals(6, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Jon", f.getValue()); f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dow", f.getValue()); f = vcard.getExtendedType("X-ABDATE").get(0); assertEquals("X-ABDATE", f.getTypeName()); assertEquals("1975-03-01", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedType("X-ABLABEL").get(0); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<Anniversary>!$_", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedType("X-ABLABEL").get(1); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<Spouse>!$_", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item2", f.getGroup()); } }
#vulnerable code @Test public void gmailVCard() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf"))); reader.setCompatibilityMode(CompatibilityMode.GMAIL); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. John Richter, James Doe Sr.", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Richter, James"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Sr."), f.getSuffixes()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("home"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("905-555-1234", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-666-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("Crescent moon drive" + newline + "555-asd" + newline + "Nice Area, Albaney, New York12345" + newline + "United States of America", f.getExtendedAddress()); assertEquals(null, f.getStreetAddress()); assertEquals(null, f.getLocality()); assertEquals(null, f.getRegion()); assertEquals(null, f.getPostalCode()); assertEquals(null, f.getCountry()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertFalse(it.hasNext()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Money Counter", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 22); assertEquals(c.getTime(), f.getDate()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.ibm.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + newline + "Favotire Color: Blue", f.getValue()); assertFalse(it.hasNext()); } //extended types { assertEquals(6, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Jon", f.getValue()); f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dow", f.getValue()); f = vcard.getExtendedType("X-ABDATE").get(0); assertEquals("X-ABDATE", f.getTypeName()); assertEquals("1975-03-01", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedType("X-ABLABEL").get(0); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<Anniversary>!$_", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedType("X-ABLABEL").get(1); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<Spouse>!$_", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item2", f.getGroup()); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public T get(V value) { T found = find(value); if (found != null) { return found; } synchronized (runtimeDefined) { for (T obj : runtimeDefined) { if (matches(obj, value)) { return obj; } } T created = create(value); runtimeDefined.add(created); return created; } }
#vulnerable code public T get(V value) { return find(value, true, true); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void lotusNotesVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf")); reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Johny"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("I"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Doe John I Johny", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny,JayJay"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "SUN"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Generic Accountant", f.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("+1 (212) 204-34456", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("00-1-212-555-7777", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("25334" + newline + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("NYC887", f.getPostalCode()); assertEquals("U.S.A.", f.getCountry()); assertNull(f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + newline + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + newline + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + newline + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + newline + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + newline + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + newline + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + newline + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + newline + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + newline + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + newline + " POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item2", f.getGroup()); assertEquals("http://www.sun.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MAY); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(7957, f.getData().length); assertFalse(it.hasNext()); } //UID { UidType f = vcard.getUid(); assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue()); } //GEO { GeoType f = vcard.getGeo(); assertEquals(-2.6, f.getLatitude(), .01); assertEquals(3.4, f.getLongitude(), .01); } //CLASS { ClassificationType f = vcard.getClassification(); assertEquals("Public", f.getValue()); } //PROFILE { ProfileType f = vcard.getProfile(); assertEquals("VCard", f.getValue()); } //TZ { TimezoneType f = vcard.getTimezone(); assertEquals(Integer.valueOf(1), f.getHourOffset()); assertEquals(Integer.valueOf(0), f.getMinuteOffset()); } //LABEL { Iterator<LabelType> it = vcard.getOrphanedLabels().iterator(); LabelType f = it.next(); assertEquals("John Doe" + newline + "New York, NewYork," + newline + "South Crecent Drive," + newline + "Building 5, floor 3," + newline + "USA", f.getValue()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PARCEL)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //SORT-STRING { SortStringType f = vcard.getSortString(); assertEquals("JOHN", f.getValue()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //SOURCE { Iterator<SourceType> it = vcard.getSources().iterator(); SourceType f = it.next(); assertEquals("Whatever", f.getValue()); assertFalse(it.hasNext()); } //MAILER { MailerType f = vcard.getMailer(); assertEquals("Mozilla Thunderbird", f.getValue()); } //NAME { SourceDisplayTextType f = vcard.getSourceDisplayText(); assertEquals("VCard for John Doe", f.getValue()); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); f = vcard.getExtendedType("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue()); f = vcard.getExtendedType("X-GENERATOR").get(0); assertEquals("X-GENERATOR", f.getTypeName()); assertEquals("Cardme Generator", f.getValue()); f = vcard.getExtendedType("X-LONG-STRING").get(0); assertEquals("X-LONG-STRING", f.getTypeName()); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue()); } }
#vulnerable code @Test public void lotusNotesVCard() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf"))); reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Johny"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("I"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Doe John I Johny", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny,JayJay"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "SUN"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Generic Accountant", f.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("+1 (212) 204-34456", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("00-1-212-555-7777", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("25334" + newline + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("NYC887", f.getPostalCode()); assertEquals("U.S.A.", f.getCountry()); assertNull(f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + newline + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + newline + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + newline + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + newline + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + newline + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + newline + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + newline + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + newline + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + newline + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + newline + " POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item2", f.getGroup()); assertEquals("http://www.sun.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MAY); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(7957, f.getData().length); assertFalse(it.hasNext()); } //UID { UidType f = vcard.getUid(); assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue()); } //GEO { GeoType f = vcard.getGeo(); assertEquals(-2.6, f.getLatitude(), .01); assertEquals(3.4, f.getLongitude(), .01); } //CLASS { ClassificationType f = vcard.getClassification(); assertEquals("Public", f.getValue()); } //PROFILE { ProfileType f = vcard.getProfile(); assertEquals("VCard", f.getValue()); } //TZ { TimezoneType f = vcard.getTimezone(); assertEquals(Integer.valueOf(1), f.getHourOffset()); assertEquals(Integer.valueOf(0), f.getMinuteOffset()); } //LABEL { Iterator<LabelType> it = vcard.getOrphanedLabels().iterator(); LabelType f = it.next(); assertEquals("John Doe" + newline + "New York, NewYork," + newline + "South Crecent Drive," + newline + "Building 5, floor 3," + newline + "USA", f.getValue()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PARCEL)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //SORT-STRING { SortStringType f = vcard.getSortString(); assertEquals("JOHN", f.getValue()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //SOURCE { Iterator<SourceType> it = vcard.getSources().iterator(); SourceType f = it.next(); assertEquals("Whatever", f.getValue()); assertFalse(it.hasNext()); } //MAILER { MailerType f = vcard.getMailer(); assertEquals("Mozilla Thunderbird", f.getValue()); } //NAME { SourceDisplayTextType f = vcard.getSourceDisplayText(); assertEquals("VCard for John Doe", f.getValue()); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); f = vcard.getExtendedType("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue()); f = vcard.getExtendedType("X-GENERATOR").get(0); assertEquals("X-GENERATOR", f.getTypeName()); assertEquals("Cardme Generator", f.getValue()); f = vcard.getExtendedType("X-LONG-STRING").get(0); assertEquals("X-LONG-STRING", f.getTypeName()); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue()); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { VCard vcard = new VCard(); StructuredNameType n = new StructuredNameType(); n.setFamily("Angstadt"); n.setGiven("Michael"); n.addPrefix("Mr"); vcard.setStructuredName(n); vcard.setFormattedName(new FormattedNameType("Michael Angstadt")); NicknameType nickname = new NicknameType(); nickname.addValue("Mike"); vcard.setNickname(nickname); vcard.addTitle(new TitleType("Software Engineer")); EmailType email = new EmailType("[email protected]"); vcard.addEmail(email); UrlType url = new UrlType("http://mikeangstadt.name"); vcard.addUrl(url); CategoriesType categories = new CategoriesType(); categories.addValue("Java software engineer"); categories.addValue("vCard expert"); categories.addValue("Nice guy!!"); vcard.setCategories(categories); vcard.setGeo(new GeoType(39.95, -75.1667)); vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York")); byte portrait[] = getFileBytes("portrait.jpg"); PhotoType photo = new PhotoType(portrait, ImageTypeParameter.JPEG); vcard.addPhoto(photo); byte pronunciation[] = getFileBytes("pronunciation.ogg"); SoundType sound = new SoundType(pronunciation, SoundTypeParameter.OGG); vcard.addSound(sound); //vcard.setUid(UidType.random()); vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b")); vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf")); vcard.setRevision(new RevisionType(new Date())); //write vCard to file File file = new File("mike-angstadt.vcf"); System.out.println("Writing " + file.getName() + "..."); Writer writer = new FileWriter(file); VCardWriter vcw = new VCardWriter(writer, VCardVersion.V3_0); vcw.write(vcard); List<String> warnings = vcw.getWarnings(); System.out.println("Completed with " + warnings.size() + " warnings."); for (String warning : warnings) { System.out.println("* " + warning); } writer.close(); System.out.println(); file = new File("mike-angstadt.xml"); System.out.println("Writing " + file.getName() + "..."); writer = new FileWriter(file); XCardMarshaller xcm = new XCardMarshaller(); xcm.addVCard(vcard); xcm.write(writer); warnings = xcm.getWarnings(); System.out.println("Completed with " + warnings.size() + " warnings."); for (String warning : warnings) { System.out.println("* " + warning); } writer.close(); }
#vulnerable code public static void main(String[] args) throws Exception { VCard vcard = new VCard(); StructuredNameType n = new StructuredNameType(); n.setFamily("Angstadt"); n.setGiven("Michael"); n.addPrefix("Mr"); vcard.setStructuredName(n); vcard.setFormattedName(new FormattedNameType("Michael Angstadt")); NicknameType nickname = new NicknameType(); nickname.addValue("Mike"); vcard.setNickname(nickname); vcard.addTitle(new TitleType("Software Engineer")); EmailType email = new EmailType("[email protected]"); vcard.addEmail(email); UrlType url = new UrlType("http://mikeangstadt.name"); vcard.addUrl(url); CategoriesType categories = new CategoriesType(); categories.addValue("Java software engineer"); categories.addValue("vCard expert"); categories.addValue("Nice guy!!"); vcard.setCategories(categories); vcard.setGeo(new GeoType(39.95, -75.1667)); vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York")); byte portrait[] = getFileBytes("portrait.jpg"); PhotoType photo = new PhotoType(portrait, ImageTypeParameter.JPEG); vcard.addPhoto(photo); byte pronunciation[] = getFileBytes("pronunciation.ogg"); SoundType sound = new SoundType(pronunciation, SoundTypeParameter.OGG); vcard.addSound(sound); //vcard.setUid(UidType.random()); vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b")); vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf")); vcard.setRevision(new RevisionType(new Date())); //write vCard to file Writer writer = new FileWriter("mike-angstadt.vcf"); VCardWriter vcw = new VCardWriter(writer, VCardVersion.V3_0); vcw.write(vcard); List<String> warnings = vcw.getWarnings(); System.out.println("Completed with " + warnings.size() + " warnings."); for (String warning : warnings) { System.out.println("* " + warning); } writer.close(); } #location 53 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void evolutionVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType t = it.next(); assertEquals("http://www.ibm.com", t.getValue()); assertEquals("0abc9b8d-0845-47d0-9a91-3db5bb74620d", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType t = it.next(); assertEquals("905-666-1234", t.getText()); Set<TelephoneTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().first("X-COUCHDB-UUID")); t = it.next(); assertEquals("905-555-1234", t.getText()); types = t.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertEquals("fbfb2722-4fd8-4dbf-9abd-eeb24072fd8e", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //UID { UidType t = vcard.getUid(); assertEquals("477343c8e6bf375a9bac1f96a5000837", t.getValue()); } //N { StructuredNameType t = vcard.getStructuredName(); assertEquals("Doe", t.getFamily()); assertEquals("John", t.getGiven()); List<String> list = t.getAdditional(); assertEquals(Arrays.asList("Richter, James"), list); list = t.getPrefixes(); assertEquals(Arrays.asList("Mr."), list); list = t.getSuffixes(); assertEquals(Arrays.asList("Sr."), list); } //FN { FormattedNameType t = vcard.getFormattedName(); assertEquals("Mr. John Richter, James Doe Sr.", t.getValue()); } //NICKNAME { NicknameType t = vcard.getNickname(); assertEquals(Arrays.asList("Johny"), t.getValues()); } //ORG { OrganizationType t = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "Accounting", "Dungeon"), t.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType t = it.next(); assertEquals("Money Counter", t.getValue()); assertFalse(it.hasNext()); } //CATEGORIES { CategoriesType t = vcard.getCategories(); assertEquals(Arrays.asList("VIP"), t.getValues()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType t = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", t.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType t = it.next(); assertEquals("[email protected]", t.getValue()); Set<EmailTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(new EmailTypeParameter("work"))); //non-standard type assertEquals("83a75a5d-2777-45aa-bab5-76a4bd972490", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType t = it.next(); assertEquals("ASB-123", t.getPoBox()); assertEquals(null, t.getExtendedAddress()); assertEquals("15 Crescent moon drive", t.getStreetAddress()); assertEquals("Albaney", t.getLocality()); assertEquals("New York", t.getRegion()); assertEquals("12345", t.getPostalCode()); //the space between "United" and "States" is lost because it was included with the folding character and ignored (see .vcf file) assertEquals("UnitedStates of America", t.getCountry()); Set<AddressTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertFalse(it.hasNext()); } //BDAY { BirthdayType t = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 22); Date expected = c.getTime(); assertEquals(expected, t.getDate()); } //REV { RevisionType t = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 5); c.set(Calendar.HOUR_OF_DAY, 13); c.set(Calendar.MINUTE, 32); c.set(Calendar.SECOND, 54); assertEquals(c.getTime(), t.getTimestamp()); } //extended types { assertEquals(7, countExtTypes(vcard)); Iterator<RawType> it = vcard.getExtendedProperties("X-COUCHDB-APPLICATION-ANNOTATIONS").iterator(); RawType t = it.next(); assertEquals("X-COUCHDB-APPLICATION-ANNOTATIONS", t.getTypeName()); assertEquals("{\"Evolution\":{\"revision\":\"2012-03-05T13:32:54Z\"}}", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-AIM").iterator(); t = it.next(); assertEquals("X-AIM", t.getTypeName()); assertEquals("[email protected]", t.getValue()); assertEquals("HOME", t.getSubTypes().getType()); assertEquals("cb9e11fc-bb97-4222-9cd8-99820c1de454", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-FILE-AS").iterator(); t = it.next(); assertEquals("X-EVOLUTION-FILE-AS", t.getTypeName()); assertEquals("Doe\\, John", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-SPOUSE").iterator(); t = it.next(); assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName()); assertEquals("Maria", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-MANAGER").iterator(); t = it.next(); assertEquals("X-EVOLUTION-MANAGER", t.getTypeName()); assertEquals("Big Blue", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-ASSISTANT").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName()); assertEquals("Little Red", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-ANNIVERSARY").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName()); assertEquals("1980-03-22", t.getValue()); assertFalse(it.hasNext()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void evolutionVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType t = it.next(); assertEquals("http://www.ibm.com", t.getValue()); assertEquals("0abc9b8d-0845-47d0-9a91-3db5bb74620d", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType t = it.next(); assertEquals("905-666-1234", t.getText()); Set<TelephoneTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().first("X-COUCHDB-UUID")); t = it.next(); assertEquals("905-555-1234", t.getText()); types = t.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertEquals("fbfb2722-4fd8-4dbf-9abd-eeb24072fd8e", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //UID { UidType t = vcard.getUid(); assertEquals("477343c8e6bf375a9bac1f96a5000837", t.getValue()); } //N { StructuredNameType t = vcard.getStructuredName(); assertEquals("Doe", t.getFamily()); assertEquals("John", t.getGiven()); List<String> list = t.getAdditional(); assertEquals(Arrays.asList("Richter, James"), list); list = t.getPrefixes(); assertEquals(Arrays.asList("Mr."), list); list = t.getSuffixes(); assertEquals(Arrays.asList("Sr."), list); } //FN { FormattedNameType t = vcard.getFormattedName(); assertEquals("Mr. John Richter, James Doe Sr.", t.getValue()); } //NICKNAME { NicknameType t = vcard.getNickname(); assertEquals(Arrays.asList("Johny"), t.getValues()); } //ORG { OrganizationType t = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "Accounting", "Dungeon"), t.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType t = it.next(); assertEquals("Money Counter", t.getValue()); assertFalse(it.hasNext()); } //CATEGORIES { CategoriesType t = vcard.getCategories(); assertEquals(Arrays.asList("VIP"), t.getValues()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType t = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", t.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType t = it.next(); assertEquals("[email protected]", t.getValue()); Set<EmailTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(new EmailTypeParameter("work"))); //non-standard type assertEquals("83a75a5d-2777-45aa-bab5-76a4bd972490", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType t = it.next(); assertEquals("ASB-123", t.getPoBox()); assertEquals(null, t.getExtendedAddress()); assertEquals("15 Crescent moon drive", t.getStreetAddress()); assertEquals("Albaney", t.getLocality()); assertEquals("New York", t.getRegion()); assertEquals("12345", t.getPostalCode()); //the space between "United" and "States" is lost because it was included with the folding character and ignored (see .vcf file) assertEquals("UnitedStates of America", t.getCountry()); Set<AddressTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertFalse(it.hasNext()); } //BDAY { BirthdayType t = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 22); Date expected = c.getTime(); assertEquals(expected, t.getDate()); } //REV { RevisionType t = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 5); c.set(Calendar.HOUR_OF_DAY, 13); c.set(Calendar.MINUTE, 32); c.set(Calendar.SECOND, 54); assertEquals(c.getTime(), t.getTimestamp()); } //extended types { assertEquals(7, countExtTypes(vcard)); Iterator<RawType> it = vcard.getExtendedProperties("X-COUCHDB-APPLICATION-ANNOTATIONS").iterator(); RawType t = it.next(); assertEquals("X-COUCHDB-APPLICATION-ANNOTATIONS", t.getTypeName()); assertEquals("{\"Evolution\":{\"revision\":\"2012-03-05T13:32:54Z\"}}", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-AIM").iterator(); t = it.next(); assertEquals("X-AIM", t.getTypeName()); assertEquals("[email protected]", t.getValue()); assertEquals("HOME", t.getSubTypes().getType()); assertEquals("cb9e11fc-bb97-4222-9cd8-99820c1de454", t.getSubTypes().first("X-COUCHDB-UUID")); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-FILE-AS").iterator(); t = it.next(); assertEquals("X-EVOLUTION-FILE-AS", t.getTypeName()); assertEquals("Doe\\, John", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-SPOUSE").iterator(); t = it.next(); assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName()); assertEquals("Maria", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-MANAGER").iterator(); t = it.next(); assertEquals("X-EVOLUTION-MANAGER", t.getTypeName()); assertEquals("Big Blue", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-ASSISTANT").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName()); assertEquals("Little Red", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedProperties("X-EVOLUTION-ANNIVERSARY").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName()); assertEquals("1980-03-22", t.getValue()); assertFalse(it.hasNext()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void thunderbird() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf")); reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertTrue(f.getPrefixes().isEmpty()); assertTrue(f.getSuffixes().isEmpty()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe", f.getValue()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johnny"), f.getValues()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("222 Broadway", f.getExtendedAddress()); assertEquals("Suite 100", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("98765", f.getPostalCode()); assertEquals("USA", f.getCountry()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("123 Main St", f.getExtendedAddress()); assertEquals("Apt 10", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("555-555-1111", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-2222", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-5555", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-3333", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("555-555-4444", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.private-webpage.com", f.getValue()); assertEquals("HOME", f.getType()); f = it.next(); assertEquals("http://www.work-webpage.com", f.getValue()); assertEquals("WORK", f.getType()); assertFalse(it.hasNext()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheTitle", f.getValue()); assertFalse(it.hasNext()); } //CATEGORIES { //commas are incorrectly escaped, so there is only 1 item CategoriesType f = vcard.getCategories(); assertEquals(Arrays.asList("category1, category2, category3"), f.getValues()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1970); c.set(Calendar.MONTH, Calendar.SEPTEMBER); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the notes field." + newline + "Second Line" + newline + newline + "Fourth Line" + newline + "You can put anything in the \"note\" field; even curse words.", f.getValue()); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(8940, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(2, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-SPOUSE").get(0); assertEquals("X-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); f = vcard.getExtendedType("X-ANNIVERSARY").get(0); assertEquals("X-ANNIVERSARY", f.getTypeName()); assertEquals("1990-04-30", f.getValue()); } }
#vulnerable code @Test public void thunderbird() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf"))); reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertTrue(f.getPrefixes().isEmpty()); assertTrue(f.getSuffixes().isEmpty()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe", f.getValue()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johnny"), f.getValues()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("222 Broadway", f.getExtendedAddress()); assertEquals("Suite 100", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("98765", f.getPostalCode()); assertEquals("USA", f.getCountry()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("123 Main St", f.getExtendedAddress()); assertEquals("Apt 10", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("555-555-1111", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-2222", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-5555", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-3333", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("555-555-4444", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.private-webpage.com", f.getValue()); assertEquals("HOME", f.getType()); f = it.next(); assertEquals("http://www.work-webpage.com", f.getValue()); assertEquals("WORK", f.getType()); assertFalse(it.hasNext()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheTitle", f.getValue()); assertFalse(it.hasNext()); } //CATEGORIES { //commas are incorrectly escaped, so there is only 1 item CategoriesType f = vcard.getCategories(); assertEquals(Arrays.asList("category1, category2, category3"), f.getValues()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1970); c.set(Calendar.MONTH, Calendar.SEPTEMBER); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the notes field." + newline + "Second Line" + newline + newline + "Fourth Line" + newline + "You can put anything in the \"note\" field; even curse words.", f.getValue()); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(8940, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(2, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-SPOUSE").get(0); assertEquals("X-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); f = vcard.getExtendedType("X-ANNIVERSARY").get(0); assertEquals("X-ANNIVERSARY", f.getTypeName()); assertEquals("1990-04-30", f.getValue()); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void thunderbird() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertTrue(f.getPrefixes().isEmpty()); assertTrue(f.getSuffixes().isEmpty()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe", f.getValue()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johnny"), f.getValues()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("222 Broadway", f.getExtendedAddress()); assertEquals("Suite 100", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("98765", f.getPostalCode()); assertEquals("USA", f.getCountry()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("123 Main St", f.getExtendedAddress()); assertEquals("Apt 10", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("555-555-1111", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-2222", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-5555", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-3333", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("555-555-4444", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.private-webpage.com", f.getValue()); assertEquals("HOME", f.getType()); f = it.next(); assertEquals("http://www.work-webpage.com", f.getValue()); assertEquals("WORK", f.getType()); assertFalse(it.hasNext()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheTitle", f.getValue()); assertFalse(it.hasNext()); } //CATEGORIES { //commas are incorrectly escaped, so there is only 1 item CategoriesType f = vcard.getCategories(); assertEquals(Arrays.asList("category1, category2, category3"), f.getValues()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1970); c.set(Calendar.MONTH, Calendar.SEPTEMBER); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the notes field." + NEWLINE + "Second Line" + NEWLINE + NEWLINE + "Fourth Line" + NEWLINE + "You can put anything in the \"note\" field; even curse words.", f.getValue()); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(8940, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(2, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-SPOUSE").get(0); assertEquals("X-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); f = vcard.getExtendedProperties("X-ANNIVERSARY").get(0); assertEquals("X-ANNIVERSARY", f.getTypeName()); assertEquals("1990-04-30", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void thunderbird() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertTrue(f.getPrefixes().isEmpty()); assertTrue(f.getSuffixes().isEmpty()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe", f.getValue()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johnny"), f.getValues()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("222 Broadway", f.getExtendedAddress()); assertEquals("Suite 100", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("98765", f.getPostalCode()); assertEquals("USA", f.getCountry()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("123 Main St", f.getExtendedAddress()); assertEquals("Apt 10", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.POSTAL)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("555-555-1111", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-2222", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-5555", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("555-555-3333", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("555-555-4444", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://www.private-webpage.com", f.getValue()); assertEquals("HOME", f.getType()); f = it.next(); assertEquals("http://www.work-webpage.com", f.getValue()); assertEquals("WORK", f.getType()); assertFalse(it.hasNext()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheTitle", f.getValue()); assertFalse(it.hasNext()); } //CATEGORIES { //commas are incorrectly escaped, so there is only 1 item CategoriesType f = vcard.getCategories(); assertEquals(Arrays.asList("category1, category2, category3"), f.getValues()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1970); c.set(Calendar.MONTH, Calendar.SEPTEMBER); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the notes field." + NEWLINE + "Second Line" + NEWLINE + NEWLINE + "Fourth Line" + NEWLINE + "You can put anything in the \"note\" field; even curse words.", f.getValue()); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(8940, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(2, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-SPOUSE").get(0); assertEquals("X-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); f = vcard.getExtendedProperties("X-ANNIVERSARY").get(0); assertEquals("X-ANNIVERSARY", f.getTypeName()); assertEquals("1990-04-30", f.getValue()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void doUnmarshalValue(Element element, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) throws VCardException { String value = XCardUtils.getFirstChildText(element, "text", "uri"); if (value != null) { parseValue(value); } }
#vulnerable code @Override protected void doUnmarshalValue(Element element, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) throws VCardException { Element ele = XCardUtils.getFirstElement(element.getChildNodes()); value = ele.getTextContent(); if (value.matches("(?i)tel:.*")) { //remove "tel:" value = (value.length() > 4) ? value.substring(4) : ""; } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void outlook2003VCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2003.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("III"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe III", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Joey"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("The Job Title", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("BusinessPhone", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("HomePhone", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("MobilePhone", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("BusinessFaxPhone", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("123 Main St", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://web-page-address.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(805, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //FBURL { Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); //Outlook 2003 apparently doesn't output FBURL correctly: //http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html FbUrlType f = it.next(); assertEquals("????????????????s????????????" + (char) 12, f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.OCTOBER); c.set(Calendar.DAY_OF_MONTH, 12); c.set(Calendar.HOUR_OF_DAY, 21); c.set(Calendar.MINUTE, 5); c.set(Calendar.SECOND, 25); assertEquals(c.getTime(), f.getTimestamp()); } }
#vulnerable code @Test public void outlook2003VCard() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("outlook-2003.vcf"))); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("III"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe III", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Joey"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("The Job Title", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("BusinessPhone", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("HomePhone", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("MobilePhone", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("BusinessFaxPhone", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("123 Main St", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://web-page-address.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(805, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //FBURL { Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); //Outlook 2003 apparently doesn't output FBURL correctly: //http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html FbUrlType f = it.next(); assertEquals("????????????????s????????????" + (char) 12, f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.OCTOBER); c.set(Calendar.DAY_OF_MONTH, 12); c.set(Calendar.HOUR_OF_DAY, 21); c.set(Calendar.MINUTE, 5); c.set(Calendar.SECOND, 25); assertEquals(c.getTime(), f.getTimestamp()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void outlook2003VCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2003.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("III"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe III", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Joey"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("The Job Title", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("BusinessPhone", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("HomePhone", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("MobilePhone", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("BusinessFaxPhone", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("123 Main St", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://web-page-address.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(805, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //FBURL { Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); //Outlook 2003 apparently doesn't output FBURL correctly: //http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html FbUrlType f = it.next(); assertEquals("????????????????s????????????" + (char) 12, f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.OCTOBER); c.set(Calendar.DAY_OF_MONTH, 12); c.set(Calendar.HOUR_OF_DAY, 21); c.set(Calendar.MINUTE, 5); c.set(Calendar.SECOND, 25); assertEquals(c.getTime(), f.getTimestamp()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void outlook2003VCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2003.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("III"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("John Doe III", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Joey"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("The Job Title", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("BusinessPhone", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("HomePhone", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("MobilePhone", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("BusinessFaxPhone", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("123 Main St", f.getStreetAddress()); assertEquals("Austin", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("United States of America", f.getCountry()); assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://web-page-address.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(805, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //FBURL { Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); //Outlook 2003 apparently doesn't output FBURL correctly: //http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html FbUrlType f = it.next(); assertEquals("????????????????s????????????" + (char) 12, f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.OCTOBER); c.set(Calendar.DAY_OF_MONTH, 12); c.set(Calendar.HOUR_OF_DAY, 21); c.set(Calendar.MINUTE, 5); c.set(Calendar.SECOND, 25); assertEquals(c.getTime(), f.getTimestamp()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) { LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine()); // Timeout is specified per file, not per batch (which can vary a lot) // so multiply it up this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs); return getFileContent(tslintOutputFile); }
#vulnerable code private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) { LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine()); // Timeout is specified per file, not per batch (which can vary a lot) // so multiply it up this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs); StringBuilder outputBuilder = new StringBuilder(); try { BufferedReader reader = this.getBufferedReaderForFile(tslintOutputFile); String str; while ((str = reader.readLine()) != null) { outputBuilder.append(str); } reader.close(); return outputBuilder.toString(); } catch (IOException ex) { LOG.error("Failed to re-read TsLint output", ex); } return ""; } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @RedisCache(flush = true) public Comment comment(Comment comment) throws ZhydCommentException { if (StringUtils.isEmpty(comment.getNickname())) { throw new ZhydCommentException("必须输入昵称哦~~"); } String content = comment.getContent(); if (!XssKillerUtil.isValid(content)) { throw new ZhydCommentException("内容不合法,请不要使用特殊标签哦~~"); } content = XssKillerUtil.clean(content.trim()).replaceAll("(<p><br></p>)|(<p></p>)", ""); if (StringUtils.isEmpty(content) || "\n".equals(content)) { throw new ZhydCommentException("不说话可不行,必须说点什么哦~~"); } // 过滤非法属性和无用的空标签 comment.setContent(content); comment.setNickname(HtmlUtil.html2Text(comment.getNickname())); comment.setQq(HtmlUtil.html2Text(comment.getQq())); comment.setAvatar(HtmlUtil.html2Text(comment.getAvatar())); comment.setEmail(HtmlUtil.html2Text(comment.getEmail())); comment.setUrl(HtmlUtil.html2Text(comment.getUrl())); HttpServletRequest request = RequestHolder.getRequest(); String ua = request.getHeader("User-Agent"); UserAgent agent = UserAgent.parseUserAgentString(ua); // 浏览器 Browser browser = agent.getBrowser(); String browserInfo = browser.getName(); // comment.setBrowserShortName(browser.getShortName());// 此处需开发者自己处理 // 浏览器版本 Version version = agent.getBrowserVersion(); if (version != null) { browserInfo += " " + version.getVersion(); } comment.setBrowser(browserInfo); // 操作系统 OperatingSystem os = agent.getOperatingSystem(); comment.setOs(os.getName()); // comment.setOsShortName(os.getShortName());// 此处需开发者自己处理 comment.setIp(IpUtil.getRealIp(request)); String address = "定位失败"; Config config = configService.get(); try { String locationJson = RestClientUtil.get(UrlBuildUtil.getLocationByIp(comment.getIp(), config.getBaiduApiAk())); JSONObject localtionContent = JSONObject.parseObject(locationJson).getJSONObject("content"); // 地址详情 JSONObject addressDetail = localtionContent.getJSONObject("address_detail"); // 省 String province = addressDetail.getString("province"); // 市 String city = addressDetail.getString("city"); // 区 String district = addressDetail.getString("district"); // 街道 String street = addressDetail.getString("street"); // 街道编号 // String street_number = addressDetail.getString("street_number"); StringBuffer sb = new StringBuffer(province); if (!StringUtils.isEmpty(city)) { sb.append(city); } if (!StringUtils.isEmpty(district)) { sb.append(district); } if (!StringUtils.isEmpty(street)) { sb.append(street); } address = sb.toString(); // 经纬度 JSONObject point = localtionContent.getJSONObject("point"); // 纬度 String lat = point.getString("y"); // 经度 String lng = point.getString("x"); comment.setLat(lat); comment.setLng(lng); comment.setAddress(address); } catch (Exception e) { comment.setAddress("未知"); log.error("获取地址失败", e); } if (StringUtils.isEmpty(comment.getStatus())) { comment.setStatus(CommentStatusEnum.VERIFYING.toString()); } this.insert(comment); this.sendEmail(comment); return comment; }
#vulnerable code @Override @RedisCache(flush = true) public Comment comment(Comment comment) throws ZhydCommentException { if (StringUtils.isEmpty(comment.getNickname())) { throw new ZhydCommentException("必须输入昵称哦~~"); } String content = comment.getContent(); if (StringUtils.isEmpty(content)) { throw new ZhydCommentException("不说话可不行,必须说点什么哦~~"); } if (!XssKillerUtil.isValid(content)) { throw new ZhydCommentException("内容不合法,请不要使用特殊标签哦~~"); } content = XssKillerUtil.clean(content.trim()); if (content.endsWith("<p><br></p>")) { comment.setContent(content.substring(0, content.length() - "<p><br></p>".length())); } comment.setNickname(HtmlUtil.html2Text(comment.getNickname())); comment.setQq(HtmlUtil.html2Text(comment.getQq())); comment.setAvatar(HtmlUtil.html2Text(comment.getAvatar())); comment.setEmail(HtmlUtil.html2Text(comment.getEmail())); comment.setUrl(HtmlUtil.html2Text(comment.getUrl())); HttpServletRequest request = RequestHolder.getRequest(); String ua = request.getHeader("User-Agent"); UserAgent agent = UserAgent.parseUserAgentString(ua); // 浏览器 Browser browser = agent.getBrowser(); String browserInfo = browser.getName(); // comment.setBrowserShortName(browser.getShortName());// 此处需开发者自己处理 // 浏览器版本 Version version = agent.getBrowserVersion(); if (version != null) { browserInfo += " " + version.getVersion(); } comment.setBrowser(browserInfo); // 操作系统 OperatingSystem os = agent.getOperatingSystem(); comment.setOs(os.getName()); // comment.setOsShortName(os.getShortName());// 此处需开发者自己处理 comment.setIp(IpUtil.getRealIp(request)); String address = "定位失败"; Config config = configService.get(); try { String locationJson = RestClientUtil.get(UrlBuildUtil.getLocationByIp(comment.getIp(), config.getBaiduApiAk())); JSONObject localtionContent = JSONObject.parseObject(locationJson).getJSONObject("content"); // 地址详情 JSONObject addressDetail = localtionContent.getJSONObject("address_detail"); // 省 String province = addressDetail.getString("province"); // 市 String city = addressDetail.getString("city"); // 区 String district = addressDetail.getString("district"); // 街道 String street = addressDetail.getString("street"); // 街道编号 // String street_number = addressDetail.getString("street_number"); StringBuffer sb = new StringBuffer(province); if (!StringUtils.isEmpty(city)) { sb.append(city); } if (!StringUtils.isEmpty(district)) { sb.append(district); } if (!StringUtils.isEmpty(street)) { sb.append(street); } address = sb.toString(); // 经纬度 JSONObject point = localtionContent.getJSONObject("point"); // 纬度 String lat = point.getString("y"); // 经度 String lng = point.getString("x"); comment.setLat(lat); comment.setLng(lng); comment.setAddress(address); } catch (Exception e) { comment.setAddress("未知"); log.error("获取地址失败", e); } if (StringUtils.isEmpty(comment.getStatus())) { comment.setStatus(CommentStatusEnum.VERIFYING.toString()); } this.insert(comment); this.sendEmail(comment); return comment; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String template2String(String templateContent, Map<String, Object> map, boolean isNeedFilter) { if (StringUtils.isEmpty(templateContent)) { return null; } if (map == null) { map = new HashMap<>(); } Map<String, Object> newMap = new HashMap<>(1); Set<String> keySet = map.keySet(); if (keySet.size() > 0) { for (String key : keySet) { Object o = map.get(key); if (o != null) { if (o instanceof String) { String value = o.toString(); value = value.trim(); if (isNeedFilter) { value = filterXmlString(value); } newMap.put(key, value); } else { newMap.put(key, o); } } } } Template t = null; try { t = new Template("", new StringReader(templateContent), new Configuration()); StringWriter writer = new StringWriter(); t.process(newMap, writer); return writer.toString(); } catch (IOException e) { log.error("TemplateUtil -> template2String IOException.", e); } catch (TemplateException e) { log.error("TemplateUtil -> template2String TemplateException.", e); } finally { newMap.clear(); newMap = null; } return null; }
#vulnerable code public static String template2String(String templateContent, Map<String, Object> map, boolean isNeedFilter) { if (StringUtils.isEmpty(templateContent)) { return null; } if (map == null) { map = new HashMap<>(); } Map<String, Object> newMap = new HashMap<>(1); Set<String> keySet = map.keySet(); if (keySet.size() > 0) { for (String key : keySet) { Object o = map.get(key); if (o != null) { if (o instanceof String) { String value = o.toString(); if (value != null) { value = value.trim(); } if (isNeedFilter) { value = filterXmlString(value); } newMap.put(key, value); } else { newMap.put(key, o); } } } } Template t = null; try { t = new Template("", new StringReader(templateContent), new Configuration()); StringWriter writer = new StringWriter(); t.process(newMap, writer); return writer.toString(); } catch (IOException e) { log.error("TemplateUtil -> template2String IOException.", e); } catch (TemplateException e) { log.error("TemplateUtil -> template2String TemplateException.", e); } finally { if (newMap != null) { newMap.clear(); newMap = null; } } return null; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException { LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body); for (String emailTarget : emailTargets) { String[] command = {"/bin/mail", "-s", "Hank-Notification", emailTarget}; Process process = Runtime.getRuntime().exec(command); OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream()); writer.write(body); writer.close(); process.getOutputStream().close(); process.waitFor(); } }
#vulnerable code private void sendEmails(Set<String> emailTargets, String body) throws IOException { File temporaryEmailBody = File.createTempFile("_tmp_" + getClass().getSimpleName(), null); BufferedWriter writer = new BufferedWriter(new FileWriter(temporaryEmailBody, false)); writer.write(body); LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body); for (String emailTarget : emailTargets) { Runtime.getRuntime().exec("cat " + temporaryEmailBody.getAbsolutePath() + " | mail -s 'Hank Notification' " + emailTarget); } if (!temporaryEmailBody.delete()) { throw new IOException("Could not delete " + temporaryEmailBody.getAbsolutePath()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting."); boolean claimedDataDeployer = false; try { ringGroup = coord.getRingGroup(ringGroupName); // attempt to claim the data deployer title if (ringGroup.claimDataDeployer()) { claimedDataDeployer = true; // we are now *the* data deployer for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); Thread.sleep(config.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim data deployer status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedDataDeployer) { ringGroup.releaseDataDeployer(); } } LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down."); }
#vulnerable code public void run() throws IOException { LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting."); boolean claimedDataDeployer = false; try { ringGroupConfig = coord.getRingGroup(ringGroupName); // attempt to claim the data deployer title if (ringGroupConfig.claimDataDeployer()) { claimedDataDeployer = true; // we are now *the* data deployer for this ring group. domainGroup = ringGroupConfig.getDomainGroup(); // set a watch on the ring group ringGroupConfig.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroupConfig; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroupConfig = ringGroupConfig; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroupConfig, snapshotDomainGroup); Thread.sleep(config.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim data deployer status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedDataDeployer) { ringGroupConfig.releaseDataDeployer(); } } LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down."); } #location 29 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException { ring = ringGroup.getRing(ringNum); domainGroup = ringGroup.getDomainGroup(); domainId = domainGroup.getDomainId(domain.getName()); version = domainGroup.getLatestVersion().getVersionNumber(); random = new Random(); for (Integer partNum : ring.getUnassignedPartitions(domain)) { getMinHostDomain().addPartition(partNum, version); } while (!isDone()) { HostDomain maxHostDomain = getMaxHostDomain(); HostDomain minHostDomain = getMinHostDomain(); ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>(); partitions.addAll(maxHostDomain.getPartitions()); int partNum = partitions.get(random.nextInt(partitions.size())).getPartNum(); HostDomainPartition partition = maxHostDomain.getPartitionByNumber(partNum); try { if (partition.getCurrentDomainGroupVersion() == null) partition.delete(); else partition.setDeletable(true); } catch (Exception e) { partition.setDeletable(true); } minHostDomain.addPartition(partNum, version); } }
#vulnerable code @Override public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException { ring = ringGroup.getRing(ringNum); domainGroup = ringGroup.getDomainGroup(); domainId = domainGroup.getDomainId(domain.getName()); version = domainGroup.getLatestVersion().getVersionNumber(); random = new Random(); for (Integer partNum : ring.getUnassignedPartitions(domain)) { HostDomain minHostDomain = getMinHostDomain(); minHostDomain.addPartition(partNum, version); } while (!isDone()) { HostDomain maxHostDomain = getMaxHostDomain(); HostDomain minHostDomain = getMinHostDomain(); ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>(); partitions.addAll(maxHostDomain.getPartitions()); int partNum = partitions.get(random.nextInt(partitions.size())).getPartNum(); HostDomainPartition partition = maxHostDomain.getPartitionByNumber(partNum); try { if (partition.getCurrentDomainGroupVersion() == null) partition.delete(); else partition.setDeletable(true); } catch (Exception e) { partition.setDeletable(true); } minHostDomain.addPartition(partNum, version); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBlockCompressionSnappy() throws Exception { doTestBlockCompression(BlockCompressionCodec.SNAPPY, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY); }
#vulnerable code public void testBlockCompressionSnappy() throws Exception { new File(TMP_TEST_CURLY_READER).mkdirs(); OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly"); s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY); s.flush(); s.close(); MapReader keyfileReader = new MapReader(0, KEY1.array(), new byte[]{0, 0, 0, 0, 0}, KEY2.array(), new byte[]{0, 0, 0, 5, 0}, KEY3.array(), new byte[]{0, 0, 0, 10, 0} ); CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1, BlockCompressionCodec.SNAPPY, 3, 2, true); ReaderResult result = new ReaderResult(); reader.get(KEY1, result); assertTrue(result.isFound()); assertEquals(VALUE1, result.getBuffer()); result.clear(); reader.get(KEY4, result); assertFalse(result.isFound()); result.clear(); reader.get(KEY3, result); assertTrue(result.isFound()); assertEquals(VALUE3, result.getBuffer()); result.clear(); reader.get(KEY2, result); assertTrue(result.isFound()); assertEquals(VALUE2, result.getBuffer()); result.clear(); } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting."); boolean claimedDataDeployer = false; try { ringGroup = coord.getRingGroup(ringGroupName); // attempt to claim the data deployer title if (ringGroup.claimDataDeployer()) { claimedDataDeployer = true; // we are now *the* data deployer for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); Thread.sleep(config.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim data deployer status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedDataDeployer) { ringGroup.releaseDataDeployer(); } } LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down."); }
#vulnerable code public void run() throws IOException { LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting."); boolean claimedDataDeployer = false; try { ringGroupConfig = coord.getRingGroup(ringGroupName); // attempt to claim the data deployer title if (ringGroupConfig.claimDataDeployer()) { claimedDataDeployer = true; // we are now *the* data deployer for this ring group. domainGroup = ringGroupConfig.getDomainGroup(); // set a watch on the ring group ringGroupConfig.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroupConfig; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroupConfig = ringGroupConfig; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroupConfig, snapshotDomainGroup); Thread.sleep(config.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim data deployer status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedDataDeployer) { ringGroupConfig.releaseDataDeployer(); } } LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down."); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) { try { client.getBulk(domainId, keys, resultHandler); } catch (TException e) { resultHandler.onError(e); } }
#vulnerable code public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) throws TException { client.getBulk(domainId, keys, resultHandler); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private ByteBuffer decompressBlock(ByteBuffer block) throws IOException { Local local = threadLocal.get(); local.reset(); local.getBlockDecompressor().decompress( block.array(), block.arrayOffset() + block.position(), block.remaining(), local.getDecompressionOutputStream()); return local.getDecompressionOutputStream().getByteBuffer(); }
#vulnerable code private ByteBuffer decompressBlock(ByteBuffer block) throws IOException { Buffers buffers = threadLocalBuffers.get(); buffers.reset(); // Decompress the block InputStream blockInputStream = new ByteArrayInputStream(block.array(), block.arrayOffset() + block.position(), block.remaining()); // Build an InputStream corresponding to the compression codec InputStream decompressedBlockInputStream = getBlockCompressionInputStream(blockInputStream); // Decompress into the specialized result buffer IOStreamUtils.copy(decompressedBlockInputStream, buffers.getDecompressionOutputStream(), buffers.getCopyBuffer()); decompressedBlockInputStream.close(); return buffers.getDecompressionOutputStream().getByteBuffer(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void aggregate(DoublePopulationStatisticsAggregator other) { if (other.maximum > this.maximum) { this.maximum = other.maximum; } if (other.minimum < this.minimum) { this.minimum = other.minimum; } this.numValues += other.numValues; this.total += other.total; this.reservoirSample.sample(other.reservoirSample, random); }
#vulnerable code public void aggregate(DoublePopulationStatisticsAggregator other) { if (numValues == 0) { // Copy deciles directly System.arraycopy(other.deciles, 0, deciles, 0, 9); } else if (other.numValues == 0) { // Keep this deciles unchanged } else { // Aggregate both deciles aggregateDeciles(this.deciles, this.numValues, this.getMaximum(), other.deciles, other.numValues, other.getMaximum(), this.deciles); } if (other.maximum > this.maximum) { this.maximum = other.maximum; } if (other.minimum < this.minimum) { this.minimum = other.minimum; } this.numValues += other.numValues; this.total += other.total; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addTask(GetTask task) { try { // TODO: remove trace //LOG.trace("Adding task with state " + task.state); if (task.startNanoTime == null) { task.startNanoTime = System.nanoTime(); } getTasks.put(task); //LOG.trace("Get Task is now " + getTasks.size()); } catch (InterruptedException e) { // Someone is trying to stop Dispatcher } }
#vulnerable code public void addTask(GetTask task) { synchronized (getTasks) { task.startNanoTime = System.nanoTime(); getTasks.addLast(task); } dispatcherThread.interrupt(); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBlockCompressionGzip() throws Exception { doTestBlockCompression(BlockCompressionCodec.GZIP, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP); }
#vulnerable code public void testBlockCompressionGzip() throws Exception { new File(TMP_TEST_CURLY_READER).mkdirs(); OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly"); s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP); s.flush(); s.close(); MapReader keyfileReader = new MapReader(0, KEY1.array(), new byte[]{0, 0, 0, 0, 0}, KEY2.array(), new byte[]{0, 0, 0, 5, 0}, KEY3.array(), new byte[]{0, 0, 0, 10, 0} ); CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1, BlockCompressionCodec.GZIP, 3, 2, true); ReaderResult result = new ReaderResult(); reader.get(KEY1, result); assertTrue(result.isFound()); assertEquals(VALUE1, result.getBuffer()); result.clear(); reader.get(KEY4, result); assertFalse(result.isFound()); result.clear(); reader.get(KEY3, result); assertTrue(result.isFound()); assertEquals(VALUE3, result.getBuffer()); result.clear(); reader.get(KEY2, result); assertTrue(result.isFound()); assertEquals(VALUE2, result.getBuffer()); result.clear(); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void commitFiles(File sourceRoot, String destinationRoot) throws IOException { File[] files = sourceRoot.listFiles(); if (files == null) { throw new IOException("Failed to commit files from " + sourceRoot + " to " + destinationRoot + " since source is not a valid directory."); } for (File file : files) { // Skip non files if (!file.isFile()) { continue; } File targetFile = new File(destinationRoot + "/" + file.getName()); // If target file already exists, delete it if (targetFile.exists()) { if (!targetFile.delete()) { throw new IOException("Failed to overwrite file in destination root: " + targetFile.getAbsolutePath()); } } // Move file to destination if (!file.renameTo(targetFile)) { LOG.info("Committing " + file.getAbsolutePath() + " to " + targetFile.getAbsolutePath()); throw new IOException("Failed to rename source file: " + file.getAbsolutePath() + " to destination file: " + targetFile.getAbsolutePath()); } } }
#vulnerable code protected void commitFiles(File sourceRoot, String destinationRoot) throws IOException { for (File file : sourceRoot.listFiles()) { // Skip non files if (!file.isFile()) { continue; } File targetFile = new File(destinationRoot + "/" + file.getName()); // If target file already exists, delete it if (targetFile.exists()) { if (!targetFile.delete()) { throw new IOException("Failed to overwrite file in destination root: " + targetFile.getAbsolutePath()); } } // Move file to destination if (!file.renameTo(targetFile)) { LOG.info("Committing " + file.getAbsolutePath() + " to " + targetFile.getAbsolutePath()); throw new IOException("Failed to rename source file: " + file.getAbsolutePath() + " to destination file: " + targetFile.getAbsolutePath()); } } } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Ring addRing(int ringNum) throws IOException { try { Ring rc = ZkRing.create(zk, ringGroupPath, ringNum, this, isUpdating() ? getUpdatingToVersion() : getCurrentVersion()); ringsByNumber.put(rc.getRingNumber(), rc); return rc; } catch (Exception e) { throw new IOException(e); } }
#vulnerable code @Override public Ring addRing(int ringNum) throws IOException { try { Ring rc = ZkRing.create(zk, ringGroupPath, ringNum, this, isUpdating() ? getUpdatingToVersion() : getCurrentVersion()); ringsByNumber.put(rc.getRingNumber(), rc); return rc; } catch (Exception e) { throw new IOException(e); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) { try { client.get(domainId, key, resultHandler); } catch (TException e) { resultHandler.onError(e); } }
#vulnerable code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) throws TException { client.get(domainId, key, resultHandler); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; synchronized (lock) { snapshotRingGroup = ringGroup; } // Only process updates if ring group conductor is configured to be active if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE) { processUpdates(snapshotRingGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); claimedRingGroupConductor = false; } } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); }
#vulnerable code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } // Only process updates if ring group conductor is configured to be active if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE) { processUpdates(snapshotRingGroup, snapshotDomainGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); claimedRingGroupConductor = false; } } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException { Session session = Session.getDefaultInstance(emailSessionProperties); Message message = new MimeMessage(session); try { message.setSubject("Hank: " + name); for (String emailTarget : emailTargets) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTarget)); } message.setText(body); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException("Failed to send notification email.", e); } }
#vulnerable code private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException { for (String emailTarget : emailTargets) { String[] command = {"/bin/mail", "-s", "Hank: " + name, emailTarget}; Process process = Runtime.getRuntime().exec(command); OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream()); writer.write(body); writer.close(); process.getOutputStream().close(); process.waitFor(); } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException { LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body); for (String emailTarget : emailTargets) { String[] command = {"/bin/mail", "-s", "Hank-Notification", emailTarget}; Process process = Runtime.getRuntime().exec(command); OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream()); writer.write(body); writer.close(); process.getOutputStream().close(); process.waitFor(); } }
#vulnerable code private void sendEmails(Set<String> emailTargets, String body) throws IOException { File temporaryEmailBody = File.createTempFile("_tmp_" + getClass().getSimpleName(), null); BufferedWriter writer = new BufferedWriter(new FileWriter(temporaryEmailBody, false)); writer.write(body); LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body); for (String emailTarget : emailTargets) { Runtime.getRuntime().exec("cat " + temporaryEmailBody.getAbsolutePath() + " | mail -s 'Hank Notification' " + emailTarget); } if (!temporaryEmailBody.delete()) { throw new IOException("Could not delete " + temporaryEmailBody.getAbsolutePath()); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException { ring = ringGroup.getRing(ringNum); domainGroup = ringGroup.getDomainGroup(); domainId = domainGroup.getDomainId(domain.getName()); version = domainGroup.getLatestVersion().getVersionNumber(); random = new Random(); for (Host host : ring.getHosts()) { if (host.getDomainById(domainId) == null) host.addDomain(domainId); } // make random assignments for any of the currently unassigned parts for (Integer partNum : ring.getUnassignedPartitions(domain)) { getMinHostDomain().addPartition(partNum, version); } while (!assignmentsBalanced()) { HostDomain maxHostDomain = getMaxHostDomain(); HostDomain minHostDomain = getMinHostDomain(); // pick a random partition from the maxHost ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>(); partitions.addAll(maxHostDomain.getPartitions()); final HostDomainPartition toMove = partitions.get(random.nextInt(partitions.size())); // assign it to the min host. note that we assign it before we unassign it // to ensure that if we fail at this point, we haven't left any parts // unassigned. minHostDomain.addPartition(toMove.getPartNum(), version); // unassign it from the max host unassign(toMove); } }
#vulnerable code @Override public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException { ring = ringGroup.getRing(ringNum); domainGroup = ringGroup.getDomainGroup(); domainId = domainGroup.getDomainId(domain.getName()); version = domainGroup.getLatestVersion().getVersionNumber(); random = new Random(); // make random assignments for any of the currently unassigned parts for (Integer partNum : ring.getUnassignedPartitions(domain)) { getMinHostDomain().addPartition(partNum, version); } while (!assignmentsBalanced()) { HostDomain maxHostDomain = getMaxHostDomain(); HostDomain minHostDomain = getMinHostDomain(); // pick a random partition from the maxHost ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>(); partitions.addAll(maxHostDomain.getPartitions()); final HostDomainPartition toMove = partitions.get(random.nextInt(partitions.size())); // assign it to the min host. note that we assign it before we unassign it // to ensure that if we fail at this point, we haven't left any parts // unassigned. minHostDomain.addPartition(toMove.getPartNum(), version); // unassign it from the max host unassign(toMove); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean isDeletable() throws IOException { Boolean result; if (deletable != null) { result = deletable.get(); } else { try { result = WatchedBoolean.get(zk, ZkPath.append(path, DELETABLE_PATH_SEGMENT)); } catch (Exception e) { throw new IOException(e); } } if (result == null) { return false; } else { return result; } }
#vulnerable code @Override public boolean isDeletable() throws IOException { if (deletable != null) { return deletable.get(); } else { try { return WatchedBoolean.get(zk, ZkPath.append(path, DELETABLE_PATH_SEGMENT)); } catch (Exception e) { throw new IOException(e); } } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Host getHost() { return host; }
#vulnerable code boolean isAvailable() { return state != HostConnectionState.STANDBY; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting."); boolean claimedRingGroupConductor = false; try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor()) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); } } LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down."); }
#vulnerable code public void run() throws IOException { LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting."); boolean claimedRingGroupConductor = false; try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor()) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); } } LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down."); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void merge(final CueballFilePath base, final List<CueballFilePath> deltas, final String newBasePath, final int keyHashSize, final int valueSize, ValueTransformer transformer, int hashIndexBits, CompressionCodec compressionCodec) throws IOException { CueballStreamBufferMergeSort cueballStreamBufferMergeSort = new CueballStreamBufferMergeSort(base, deltas, keyHashSize, hashIndexBits, valueSize, compressionCodec, transformer); // Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own. OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath); // Note that we intentionally omit the hasher here, since it will *not* be used CueballWriter newCueballBaseWriter = new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits); while (true) { CueballStreamBufferMergeSort.KeyHashValuePair keyValuePair = cueballStreamBufferMergeSort.nextKeyValuePair(); if (keyValuePair == null) { break; } // Write next key hash and value newCueballBaseWriter.writeHash(keyValuePair.keyHash, keyValuePair.value); } // Close all buffers and the base writer cueballStreamBufferMergeSort.close(); newCueballBaseWriter.close(); }
#vulnerable code public void merge(final CueballFilePath base, final List<CueballFilePath> deltas, final String newBasePath, final int keyHashSize, final int valueSize, ValueTransformer transformer, int hashIndexBits, CompressionCodec compressionCodec) throws IOException { // Array of stream buffers for the base and all deltas in order CueballStreamBuffer[] cueballStreamBuffers = new CueballStreamBuffer[deltas.size() + 1]; // Open the current base CueballStreamBuffer cueballBaseStreamBuffer = new CueballStreamBuffer(base.getPath(), 0, keyHashSize, valueSize, hashIndexBits, compressionCodec); cueballStreamBuffers[0] = cueballBaseStreamBuffer; // Open all the deltas int i = 1; for (CueballFilePath delta : deltas) { CueballStreamBuffer cueballStreamBuffer = new CueballStreamBuffer(delta.getPath(), i, keyHashSize, valueSize, hashIndexBits, compressionCodec); cueballStreamBuffers[i++] = cueballStreamBuffer; } // Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own. OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath); // Note that we intentionally omit the hasher here, since it will *not* be used CueballWriter newCueballBaseWriter = new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits); while (true) { // Find the stream buffer with the next smallest key hash CueballStreamBuffer cueballStreamBufferToUse = null; for (i = 0; i < cueballStreamBuffers.length; i++) { if (cueballStreamBuffers[i].anyRemaining()) { if (cueballStreamBufferToUse == null) { cueballStreamBufferToUse = cueballStreamBuffers[i]; } else { int comparison = cueballStreamBufferToUse.compareTo(cueballStreamBuffers[i]); if (comparison == 0) { // If two equal key hashes are found, use the most recent value (i.e. the one from the lastest delta) // and skip (consume) the older ones cueballStreamBufferToUse.consume(); cueballStreamBufferToUse = cueballStreamBuffers[i]; } else if (comparison == 1) { // Found a stream buffer with a smaller key hash cueballStreamBufferToUse = cueballStreamBuffers[i]; } } } } if (cueballStreamBufferToUse == null) { // Nothing more to write break; } // Transform if necessary if (transformer != null) { transformer.transform(cueballStreamBufferToUse.getBuffer(), cueballStreamBufferToUse.getCurrentOffset() + keyHashSize, cueballStreamBufferToUse.getIndex()); } // Get next key hash and value final ByteBuffer keyHash = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(), cueballStreamBufferToUse.getCurrentOffset(), keyHashSize); final ByteBuffer valueBytes = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(), cueballStreamBufferToUse.getCurrentOffset() + keyHashSize, valueSize); // Write next key hash and value newCueballBaseWriter.writeHash(keyHash, valueBytes); cueballStreamBufferToUse.consume(); } // Close all buffers and the base writer for (CueballStreamBuffer cueballStreamBuffer : cueballStreamBuffers) { cueballStreamBuffer.close(); } newCueballBaseWriter.close(); } #location 81 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring, since it might get changed // while we're processing the current update. RingGroup snapshotRingGroup; synchronized (lock) { snapshotRingGroup = ringGroup; } // Only process updates if ring group conductor is configured to be active/proactive if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE || snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) { processUpdates(snapshotRingGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { releaseIfClaimed(); } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); }
#vulnerable code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring, since // it might get changed while we're processing the current update. RingGroup snapshotRingGroup; synchronized (lock) { snapshotRingGroup = ringGroup; } // Only process updates if ring group conductor is configured to be active/proactive if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE || snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) { processUpdates(snapshotRingGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); claimedRingGroupConductor = false; } } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void runUpdateCore(DomainVersion currentVersion, DomainVersion updatingToVersion, IncrementalUpdatePlan updatePlan, String updateWorkRoot) throws IOException { // Prepare Curly // Determine files from versions CurlyFilePath curlyBasePath = getCurlyFilePathForVersion(updatePlan.getBase(), currentVersion, true); List<CurlyFilePath> curlyDeltas = new ArrayList<CurlyFilePath>(); for (DomainVersion curlyDeltaVersion : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!isEmptyVersion(curlyDeltaVersion)) { curlyDeltas.add(getCurlyFilePathForVersion(curlyDeltaVersion, currentVersion, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(curlyBasePath.getPath()); for (CurlyFilePath curlyDelta : curlyDeltas) { CueballPartitionUpdater.checkRequiredFileExists(curlyDelta.getPath()); } // Prepare Cueball // Determine files from versions CueballFilePath cueballBasePath = CueballPartitionUpdater.getCueballFilePathForVersion(updatePlan.getBase(), currentVersion, localPartitionRoot, localPartitionRootCache, true); List<CueballFilePath> cueballDeltas = new ArrayList<CueballFilePath>(); for (DomainVersion cueballDelta : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!CueballPartitionUpdater.isEmptyVersion(cueballDelta, partitionRemoteFileOps)) { cueballDeltas.add(CueballPartitionUpdater.getCueballFilePathForVersion(cueballDelta, currentVersion, localPartitionRoot, localPartitionRootCache, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(cueballBasePath.getPath()); for (CueballFilePath cueballDelta : cueballDeltas) { CueballPartitionUpdater.checkRequiredFileExists(cueballDelta.getPath()); } // Determine new Curly base path CurlyFilePath newCurlyBasePath = new CurlyFilePath(updateWorkRoot + "/" + Curly.getName(updatingToVersion.getVersionNumber(), true)); // Determine new Cueball base path CueballFilePath newCueballBasePath = new CueballFilePath(updateWorkRoot + "/" + Cueball.getName(updatingToVersion.getVersionNumber(), true)); OutputStream newCurlyBaseOutputStream = new FileOutputStream(newCurlyBasePath.getPath()); OutputStream newCueballBaseOutputStream = new FileOutputStream(newCueballBasePath.getPath()); // Note: the Curly writer used to perform the compaction must not hash the passed-in key because // it will directly receive key hashes. This is because the actual key is unknown when compacting. CurlyWriter curlyWriter = curlyWriterFactory.getCurlyWriter(newCueballBaseOutputStream, newCurlyBaseOutputStream); IKeyFileStreamBufferMergeSort cueballStreamBufferMergeSort = cueballStreamBufferMergeSortFactory.getInstance(cueballBasePath, cueballDeltas); merger.merge(curlyBasePath, curlyDeltas, cueballStreamBufferMergeSort, curlyWriter); }
#vulnerable code @Override protected void runUpdateCore(DomainVersion currentVersion, DomainVersion updatingToVersion, IncrementalUpdatePlan updatePlan, String updateWorkRoot) throws IOException { // Prepare Curly // Determine files from versions CurlyFilePath curlyBasePath = getCurlyFilePathForVersion(updatePlan.getBase(), currentVersion, true); List<CurlyFilePath> curlyDeltas = new ArrayList<CurlyFilePath>(); for (DomainVersion curlyDeltaVersion : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!isEmptyVersion(curlyDeltaVersion)) { curlyDeltas.add(getCurlyFilePathForVersion(curlyDeltaVersion, currentVersion, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(curlyBasePath.getPath()); for (CurlyFilePath curlyDelta : curlyDeltas) { CueballPartitionUpdater.checkRequiredFileExists(curlyDelta.getPath()); } // Prepare Cueball // Determine files from versions CueballFilePath cueballBasePath = CueballPartitionUpdater.getCueballFilePathForVersion(updatePlan.getBase(), currentVersion, localPartitionRoot, localPartitionRootCache, true); List<CueballFilePath> cueballDeltas = new ArrayList<CueballFilePath>(); for (DomainVersion cueballDelta : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!CueballPartitionUpdater.isEmptyVersion(cueballDelta, partitionRemoteFileOps)) { cueballDeltas.add(CueballPartitionUpdater.getCueballFilePathForVersion(cueballDelta, currentVersion, localPartitionRoot, localPartitionRootCache, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(cueballBasePath.getPath()); for (CueballFilePath cueballDelta : cueballDeltas) { CueballPartitionUpdater.checkRequiredFileExists(cueballDelta.getPath()); } // Determine new Curly base path CurlyFilePath newCurlyBasePath = new CurlyFilePath(updateWorkRoot + "/" + Curly.getName(updatingToVersion.getVersionNumber(), true)); // Determine new Cueball base path CueballFilePath newCueballBasePath = new CueballFilePath(updateWorkRoot + "/" + Cueball.getName(updatingToVersion.getVersionNumber(), true)); OutputStream newCurlyBaseOutputStream = new FileOutputStream(newCurlyBasePath.getPath()); OutputStream newCueballBaseOutputStream = new FileOutputStream(newCueballBasePath.getPath()); // Note: the Cueball writer used to perform the compaction must not hash the passed-in key because // it will directly receive key hashes. This is because the actual key is unknown when compacting. // TODO: Using an identity hasher and actually copying the bytes is unnecessary and inefficient. // TODO: (continued) Adding the logic of writing directly a hash could be added to Cueball. CueballWriter cueballWriter = new CueballWriter(newCueballBaseOutputStream, keyHashSize, new IdentityHasher(), offsetSize, compressionCodec, hashIndexBits); CurlyWriter curlyWriter = new CurlyWriter(newCurlyBaseOutputStream, cueballWriter, offsetSize); merger.merge(curlyBasePath, curlyDeltas, cueballBasePath, cueballDeltas, curlyWriter); } #location 65 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Flow build(Properties cascasdingProperties, TapOrTapMap sources) throws IOException { pipe = new DomainBuilderAssembly(properties.getDomainName(), pipe, keyFieldName, valueFieldName); // Open new version and check for success openNewVersion(); Flow flow = null; try { // Build flow flow = getFlow(cascasdingProperties, sources); // Set up job DomainBuilderOutputCommitter.setupJob(properties.getDomainName(), flow.getJobConf()); // Complete flow flow.complete(); // Commit job DomainBuilderOutputCommitter.commitJob(properties.getDomainName(), flow.getJobConf()); } catch (Exception e) { String exceptionMessage = "Failed at building version " + domainVersion.getVersionNumber() + " of domain " + properties.getDomainName() + ". Cancelling version."; // In case of failure, cancel this new version cancelNewVersion(); // Clean up job if (flow != null) { DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); } e.printStackTrace(); throw new IOException(exceptionMessage, e); } // Close the new version closeNewVersion(); // Clean up job DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); return flow; }
#vulnerable code private Flow build(Properties cascasdingProperties, TapOrTapMap sources) throws IOException { pipe = new DomainBuilderAssembly(properties.getDomainName(), pipe, keyFieldName, valueFieldName); // Open new version and check for success openNewVersion(); Flow flow = null; try { // Build flow flow = getFlow(cascasdingProperties, sources); // Set up job DomainBuilderOutputCommitter.setupJob(properties.getDomainName(), flow.getJobConf()); // Complete flow flow.complete(); // Commit job DomainBuilderOutputCommitter.commitJob(properties.getDomainName(), flow.getJobConf()); } catch (Exception e) { // In case of failure, cancel this new version cancelNewVersion(); // Clean up job if (flow != null) { DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); } e.printStackTrace(); throw new IOException("Failed at building version " + domainVersion.getVersionNumber() + " of domain " + properties.getDomainName() + ". Cancelling version.", e); } // Close the new version closeNewVersion(); // Clean up job DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); return flow; } #location 32 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void merge(final CueballFilePath base, final List<CueballFilePath> deltas, final String newBasePath, final int keyHashSize, final int valueSize, ValueTransformer transformer, int hashIndexBits, CompressionCodec compressionCodec) throws IOException { // Perform merging CueballStreamBuffer[] sbs = new CueballStreamBuffer[deltas.size() + 1]; // open the current base CueballStreamBuffer baseBuffer = new CueballStreamBuffer(base.getPath(), 0, keyHashSize, valueSize, hashIndexBits, compressionCodec); sbs[0] = baseBuffer; // open all the deltas int i = 1; for (CueballFilePath delta : deltas) { CueballStreamBuffer db = new CueballStreamBuffer(delta.getPath(), i, keyHashSize, valueSize, hashIndexBits, compressionCodec); sbs[i++] = db; } // output stream for the new base to be written. intentionally unbuffered - // the writer below will do that on its own. OutputStream newBaseStream = new FileOutputStream(newBasePath); // note that we intentionally omit the hasher here, since it will *not* be // used CueballWriter writer = new CueballWriter(newBaseStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits); while (true) { CueballStreamBuffer least = null; for (i = 0; i < sbs.length; i++) { boolean remaining = sbs[i].anyRemaining(); if (remaining) { if (least == null) { least = sbs[i]; } else { int comparison = least.compareTo(sbs[i]); if (comparison == 0) { least.consume(); least = sbs[i]; } else if (comparison == 1) { least = sbs[i]; } } } } if (least == null) { break; } if (transformer != null) { transformer.transform(least.getBuffer(), least.getCurrentOffset() + keyHashSize, least.getIndex()); } final ByteBuffer keyHash = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset(), keyHashSize); final ByteBuffer valueBytes = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset() + keyHashSize, valueSize); writer.writeHash(keyHash, valueBytes); least.consume(); } for (CueballStreamBuffer sb : sbs) { sb.close(); } writer.close(); }
#vulnerable code public void merge(final CueballFilePath base, final List<CueballFilePath> deltas, final String newBasePath, final int keyHashSize, final int valueSize, ValueTransformer transformer, int hashIndexBits, CompressionCodec compressionCodec) throws IOException { // Perform merging StreamBuffer[] sbs = new StreamBuffer[deltas.size() + 1]; // open the current base StreamBuffer baseBuffer = new StreamBuffer(base.getPath(), 0, keyHashSize, valueSize, hashIndexBits, compressionCodec); sbs[0] = baseBuffer; // open all the deltas int i = 1; for (CueballFilePath delta : deltas) { StreamBuffer db = new StreamBuffer(delta.getPath(), i, keyHashSize, valueSize, hashIndexBits, compressionCodec); sbs[i++] = db; } // output stream for the new base to be written. intentionally unbuffered - // the writer below will do that on its own. OutputStream newBaseStream = new FileOutputStream(newBasePath); // note that we intentionally omit the hasher here, since it will *not* be // used CueballWriter writer = new CueballWriter(newBaseStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits); while (true) { StreamBuffer least = null; for (i = 0; i < sbs.length; i++) { boolean remaining = sbs[i].anyRemaining(); if (remaining) { if (least == null) { least = sbs[i]; } else { int comparison = least.compareTo(sbs[i]); if (comparison == 0) { least.consume(); least = sbs[i]; } else if (comparison == 1) { least = sbs[i]; } } } } if (least == null) { break; } if (transformer != null) { transformer.transform(least.getBuffer(), least.getCurrentOffset() + keyHashSize, least.getIndex()); } final ByteBuffer keyHash = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset(), keyHashSize); final ByteBuffer valueBytes = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset() + keyHashSize, valueSize); writer.writeHash(keyHash, valueBytes); least.consume(); } for (StreamBuffer sb : sbs) { sb.close(); } writer.close(); } #location 70 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring, since it might get changed // while we're processing the current update. RingGroup snapshotRingGroup; synchronized (lock) { snapshotRingGroup = ringGroup; } // Only process updates if ring group conductor is configured to be active/proactive if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE || snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) { processUpdates(snapshotRingGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { releaseIfClaimed(); } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); }
#vulnerable code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring, since it might get changed // while we're processing the current update. RingGroup snapshotRingGroup; synchronized (lock) { snapshotRingGroup = ringGroup; } // Only process updates if ring group conductor is configured to be active/proactive if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE || snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) { processUpdates(snapshotRingGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { releaseIfClaimed(); } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private ByteBuffer decompressBlock(ByteBuffer block) throws IOException { Local local = threadLocal.get(); local.reset(); local.getBlockDecompressor().decompress( block.array(), block.arrayOffset() + block.position(), block.remaining(), local.getDecompressionOutputStream()); return local.getDecompressionOutputStream().getByteBuffer(); }
#vulnerable code private ByteBuffer decompressBlock(ByteBuffer block) throws IOException { Buffers buffers = threadLocalBuffers.get(); buffers.reset(); // Decompress the block InputStream blockInputStream = new ByteArrayInputStream(block.array(), block.arrayOffset() + block.position(), block.remaining()); // Build an InputStream corresponding to the compression codec InputStream decompressedBlockInputStream = getBlockCompressionInputStream(blockInputStream); // Decompress into the specialized result buffer IOStreamUtils.copy(decompressedBlockInputStream, buffers.getDecompressionOutputStream(), buffers.getCopyBuffer()); decompressedBlockInputStream.close(); return buffers.getDecompressionOutputStream().getByteBuffer(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring, since it might get changed // while we're processing the current update. RingGroup snapshotRingGroup; synchronized (lock) { snapshotRingGroup = ringGroup; } // Only process updates if ring group conductor is configured to be active/proactive if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE || snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) { processUpdates(snapshotRingGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { releaseIfClaimed(); } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); }
#vulnerable code public void run() throws IOException { // Add shutdown hook addShutdownHook(); claimedRingGroupConductor = false; LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { claimedRingGroupConductor = true; // we are now *the* ring group conductor for this ring group. domainGroup = ringGroup.getDomainGroup(); // set a watch on the ring group ringGroup.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down stopping = false; try { while (!stopping) { // take a snapshot of the current ring, since it might get changed // while we're processing the current update. RingGroup snapshotRingGroup; synchronized (lock) { snapshotRingGroup = ringGroup; } // Only process updates if ring group conductor is configured to be active/proactive if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE || snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) { processUpdates(snapshotRingGroup); } Thread.sleep(configurator.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { releaseIfClaimed(); } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testGzipBlockCompression() throws Exception { ByteArrayOutputStream s = new ByteArrayOutputStream(); MapWriter keyfileWriter = new MapWriter(); CurlyWriter writer = new CurlyWriter(s, keyfileWriter, 3, -1, BlockCompressionCodec.GZIP, 1024, 2); writer.write(KEY1, VALUE1); writer.write(KEY2, VALUE2); writer.write(KEY3, VALUE3); writer.close(); assertTrue(writer.getNumBytesWritten() > 0); assertEquals(3, writer.getNumRecordsWritten()); // verify the keyfile looks as expected assertTrue(keyfileWriter.entries.containsKey(KEY1)); assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 0, 0}), keyfileWriter.entries.get(KEY1)); assertTrue(keyfileWriter.entries.containsKey(KEY2)); assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 5, 0}), keyfileWriter.entries.get(KEY2)); assertTrue(keyfileWriter.entries.containsKey(KEY3)); assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 10, 0}), keyfileWriter.entries.get(KEY3)); assertFalse(keyfileWriter.entries.containsKey(KEY4)); // verify that the record stream looks as expected assertEquals(ByteBuffer.wrap(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP), ByteBuffer.wrap(s.toByteArray())); }
#vulnerable code public void testGzipBlockCompression() throws Exception { ByteArrayOutputStream s = new ByteArrayOutputStream(); MapWriter keyfileWriter = new MapWriter(); CurlyWriter writer = new CurlyWriter(s, keyfileWriter, 3, -1, BlockCompressionCodec.GZIP, 1024, 2); writer.write(KEY1, VALUE1); writer.write(KEY2, VALUE2); writer.write(KEY3, VALUE3); writer.close(); assertTrue(writer.getNumBytesWritten() > 0); assertEquals(3, writer.getNumRecordsWritten()); // verify the keyfile looks as expected assertTrue(keyfileWriter.entries.containsKey(KEY1)); System.out.println("k1=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY1))); //TODO: remove System.out.println("k2=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY2))); //TODO: remove System.out.println("k3=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY3))); //TODO: remove assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 0, 0}), keyfileWriter.entries.get(KEY1)); assertTrue(keyfileWriter.entries.containsKey(KEY2)); assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 5, 0}), keyfileWriter.entries.get(KEY2)); assertTrue(keyfileWriter.entries.containsKey(KEY3)); assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 10, 0}), keyfileWriter.entries.get(KEY3)); assertFalse(keyfileWriter.entries.containsKey(KEY4)); // verify that the record stream looks as expected System.out.println(Bytes.bytesToHexString(ByteBuffer.wrap(s.toByteArray()))); //TODO: remove assertEquals(ByteBuffer.wrap(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP), ByteBuffer.wrap(s.toByteArray())); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void aggregate(DoublePopulationStatisticsAggregator other) { if (other.maximum > this.maximum) { this.maximum = other.maximum; } if (other.minimum < this.minimum) { this.minimum = other.minimum; } this.numValues += other.numValues; this.total += other.total; this.reservoirSample.sample(other.reservoirSample, random); }
#vulnerable code public void aggregate(DoublePopulationStatisticsAggregator other) { if (numValues == 0) { // Copy deciles directly System.arraycopy(other.deciles, 0, deciles, 0, 9); } else if (other.numValues == 0) { // Keep this deciles unchanged } else { // Aggregate both deciles aggregateDeciles(this.deciles, this.numValues, this.getMaximum(), other.deciles, other.numValues, other.getMaximum(), this.deciles); } if (other.maximum > this.maximum) { this.maximum = other.maximum; } if (other.minimum < this.minimum) { this.minimum = other.minimum; } this.numValues += other.numValues; this.total += other.total; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean isBalanced(Ring ring, Domain domain) throws IOException { HostDomain maxHostDomain = getMaxHostDomain(ring, domain); HostDomain minHostDomain = getMinHostDomain(ring, domain); if (maxHostDomain == null || minHostDomain == null) { // If either maxHostDomain or minHostDomain is null, the domain is not balanced return false; } int maxDistance = Math.abs(maxHostDomain.getPartitions().size() - minHostDomain.getPartitions().size()); return maxDistance <= 1; }
#vulnerable code private boolean isBalanced(Ring ring, Domain domain) throws IOException { HostDomain maxHostDomain = getMaxHostDomain(ring, domain); HostDomain minHostDomain = getMinHostDomain(ring, domain); int maxDistance = Math.abs(maxHostDomain.getPartitions().size() - minHostDomain.getPartitions().size()); return maxDistance <= 1; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException { Session session = Session.getDefaultInstance(emailSessionProperties); Message message = new MimeMessage(session); try { message.setSubject("Hank: " + name); for (String emailTarget : emailTargets) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTarget)); } message.setText(body); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException("Failed to send notification email.", e); } }
#vulnerable code private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException { for (String emailTarget : emailTargets) { String[] command = {"/bin/mail", "-s", "Hank: " + name, emailTarget}; Process process = Runtime.getRuntime().exec(command); OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream()); writer.write(body); writer.close(); process.getOutputStream().close(); process.waitFor(); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addTask(GetTask task) { synchronized (getTasks) { task.startNanoTime = System.nanoTime(); getTasks.addLast(task); } //dispatcherThread.interrupt(); }
#vulnerable code public void addTask(GetTask task) { synchronized (getTasks) { task.startNanoTime = System.nanoTime(); getTasks.addLast(task); } dispatcherThread.interrupt(); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void filterActions(AccessKeyAction allowedAction, Set<AccessKeyPermission> permissions) { Set<AccessKeyPermission> permissionsToRemove = new HashSet<>(); for (AccessKeyPermission currentPermission : permissions) { boolean isCurrentPermissionAllowed = false; Set<String> actions = currentPermission.getActionsAsSet(); if (actions != null) { if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) { actions.removeAll(AvailableActions.getAdminActions()); } for (String accessKeyAction : actions) { isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue()); if (isCurrentPermissionAllowed) { break; } } if (!isCurrentPermissionAllowed) { permissionsToRemove.add(currentPermission); } } } permissions.removeAll(permissionsToRemove); }
#vulnerable code public static void filterActions(AccessKeyAction allowedAction, Set<AccessKeyPermission> permissions) { Set<AccessKeyPermission> permissionsToRemove = new HashSet<>(); for (AccessKeyPermission currentPermission : permissions) { boolean isCurrentPermissionAllowed = false; Set<String> actions = currentPermission.getActionsAsSet(); if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) { actions.removeAll(AvailableActions.getAdminActions()); } if (actions != null) { if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) { actions.removeAll(AvailableActions.getAdminActions()); } for (String accessKeyAction : actions) { isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue()); if (isCurrentPermissionAllowed) { break; } } if (!isCurrentPermissionAllowed) { permissionsToRemove.add(currentPermission); } } } permissions.removeAll(permissionsToRemove); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Network getWithDevicesAndDeviceClasses(@NotNull Long networkId, @NotNull HivePrincipal principal) { if (principal.getUser() != null) { List<Network> found = networkDAO.getNetworkList(principal.getUser(), null, Arrays.asList(networkId)); if (found.isEmpty()) { return null; } List<Device> devices = deviceService.getList(networkId, principal); Network result = found.get(0); result.setDevices(new HashSet<>(devices)); return result; } else { AccessKey key = principal.getKey(); User user = userService.findUserWithNetworks(key.getUser().getId()); List<Network> found = networkDAO.getNetworkList(user, key.getPermissions(), Arrays.asList(networkId)); Network result = found.isEmpty() ? null : found.get(0); if (result == null) { return result; } //to get proper devices 1) get access key with all permissions 2) get devices for required network AccessKey currentKey = accessKeyDAO.getWithoutUser(user.getId(), key.getId()); Set<AccessKeyPermission> filtered = CheckPermissionsHelper.filterPermissions(key.getPermissions(), AllowedKeyAction.Action.GET_DEVICE, ThreadLocalVariablesKeeper.getClientIP(), ThreadLocalVariablesKeeper.getHostName()); if (filtered.isEmpty()) { result.setDevices(null); return result; } Set<Device> devices = new HashSet<>(deviceService.getList(result.getId(), principal)); result.setDevices(devices); return result; } }
#vulnerable code @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Network getWithDevicesAndDeviceClasses(@NotNull Long networkId, @NotNull HivePrincipal principal) { if (principal.getUser() != null) { List<Network> found = networkDAO.getNetworkList(principal.getUser(), null, Arrays.asList(networkId)); if (found.isEmpty()) { return null; } List<Device> devices = deviceService.getList(networkId, principal); Network result = found.get(0); result.setDevices(new HashSet<>(devices)); return result; } else { AccessKey key = principal.getKey(); User user = userService.findUserWithNetworks(key.getUser().getId()); List<Network> found = networkDAO.getNetworkList(user, key.getPermissions(), Arrays.asList(networkId)); Network result = found.isEmpty() ? null : found.get(0); if (result == null) { return result; } //to get proper devices 1) get access key with all permissions 2) get devices for required network key = accessKeyService.find(key.getId(), principal.getKey().getUser().getId()); if (!CheckPermissionsHelper.checkAllPermissions(key, AllowedKeyAction.Action.GET_DEVICE)) { result.setDevices(null); return result; } Set<Device> devices = new HashSet<>(deviceService.getList(result.getId(), principal)); result.setDevices(devices); return result; } } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Action("notification/insert") @RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.DEVICE, HiveRoles.KEY}) @AllowedKeyAction(action = CREATE_DEVICE_NOTIFICATION) public WebSocketResponse processNotificationInsert(@WsParam(DEVICE_GUID) String deviceGuid, @WsParam(NOTIFICATION) @JsonPolicyApply(NOTIFICATION_FROM_DEVICE) DeviceNotification notification, Session session) { logger.debug("notification/insert requested. Session {}. Guid {}", session, deviceGuid); HivePrincipal principal = hiveSecurityContext.getHivePrincipal(); if (notification == null || notification.getNotification() == null) { logger.debug( "notification/insert proceed with error. Bad notification: notification is required."); throw new HiveException(Messages.NOTIFICATION_REQUIRED, SC_BAD_REQUEST); } Device device; if (deviceGuid == null) { device = principal.getDevice(); } else { device = deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal); } if (device == null){ logger.debug("notification/insert canceled for session: {}. Guid is not provided", session); throw new HiveException(Messages.DEVICE_GUID_REQUIRED, SC_FORBIDDEN); } if (device.getNetwork() == null) { logger.debug( "notification/insert. No network specified for device with guid = {}", deviceGuid); throw new HiveException(Messages.DEVICE_IS_NOT_CONNECTED_TO_NETWORK, SC_FORBIDDEN); } deviceNotificationService.submitDeviceNotification(notification, device); logger.debug("notification/insert proceed successfully. Session {}. Guid {}", session, deviceGuid); WebSocketResponse response = new WebSocketResponse(); response.addValue(NOTIFICATION, notification, NOTIFICATION_TO_DEVICE); return response; }
#vulnerable code @Action("notification/insert") @RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.DEVICE, HiveRoles.KEY}) @AllowedKeyAction(action = CREATE_DEVICE_NOTIFICATION) public WebSocketResponse processNotificationInsert(@WsParam(DEVICE_GUID) String deviceGuid, @WsParam(NOTIFICATION) @JsonPolicyApply(NOTIFICATION_FROM_DEVICE) DeviceNotification notification, Session session) { logger.debug("notification/insert requested. Session {}. Guid {}", session, deviceGuid); HivePrincipal principal = hiveSecurityContext.getHivePrincipal(); if (notification == null || notification.getNotification() == null) { logger.debug( "notification/insert proceed with error. Bad notification: notification is required."); throw new HiveException(Messages.NOTIFICATION_REQUIRED, SC_BAD_REQUEST); } Device device; if (deviceGuid == null) { device = principal.getDevice(); } else { device = deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal); } if (device.getNetwork() == null) { logger.debug( "notification/insert. No network specified for device with guid = {}", deviceGuid); throw new HiveException(Messages.DEVICE_IS_NOT_CONNECTED_TO_NETWORK, SC_FORBIDDEN); } deviceNotificationService.submitDeviceNotification(notification, device); logger.debug("notification/insert proceed successfully. Session {}. Guid {}", session, deviceGuid); WebSocketResponse response = new WebSocketResponse(); response.addValue(NOTIFICATION, notification, NOTIFICATION_TO_DEVICE); return response; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Action(value = "notification/unsubscribe") public JsonObject processNotificationUnsubscribe(JsonObject message, Session session) { logger.debug("notification/unsubscribe action. Session " + session.getId()); Gson gson = GsonFactory.createGson(); List<UUID> list = gson.fromJson(message.get(JsonMessageBuilder.DEVICE_GUIDS), new TypeToken<List<UUID>>() { }.getType()); try { WebsocketSession.getNotificationSubscriptionsLock(session).lock(); List<Device> devices = null; if (list != null && !list.isEmpty()) { devices = deviceDAO.findByUUID(list); logger.debug("notification/unsubscribe. found " + devices.size() + " devices. " + "Session " + session.getId()); } logger.debug("notification/unsubscribe. performing unsubscribing action"); localMessageBus.unsubscribeFromNotifications(session.getId(), devices); } finally { WebsocketSession.getNotificationSubscriptionsLock(session).unlock(); } JsonObject jsonObject = JsonMessageBuilder.createSuccessResponseBuilder().build(); logger.debug("notification/unsubscribe completed for session " + session.getId()); return jsonObject; }
#vulnerable code @Action(value = "notification/unsubscribe") public JsonObject processNotificationUnsubscribe(JsonObject message, Session session) { logger.debug("notification/unsubscribe action. Session " + session.getId()); Gson gson = GsonFactory.createGson(); List<UUID> list = gson.fromJson(message.get(JsonMessageBuilder.DEVICE_GUIDS), new TypeToken<List<UUID>>() { }.getType()); try { WebsocketSession.getNotificationSubscriptionsLock(session).lock(); List<Device> devices = null; if (list != null && !list.isEmpty()) { devices = deviceDAO.findByUUID(list); } logger.debug("notification/unsubscribe. found " + devices.size() + " devices. " + "Session " + session.getId()); logger.debug("notification/unsubscribe. performing unsubscribing action"); localMessageBus.unsubscribeFromNotifications(session.getId(), devices); } finally { WebsocketSession.getNotificationSubscriptionsLock(session).unlock(); } JsonObject jsonObject = JsonMessageBuilder.createSuccessResponseBuilder().build(); logger.debug("notification/unsubscribe completed for session " + session.getId()); return jsonObject; } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public DeviceNotification deviceSave(DeviceUpdate deviceUpdate, Set<Equipment> equipmentSet) { Network network = networkService.createOrVeriryNetwork(deviceUpdate.getNetwork()); DeviceClass deviceClass = deviceClassService .createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet); Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue()); if (existingDevice == null) { Device device = deviceUpdate.convertTo(); if (deviceClass != null) { device.setDeviceClass(deviceClass); } if (network != null) { device.setNetwork(network); } existingDevice = deviceDAO.createDevice(device); final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_ADD); deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid()); return addDeviceNotification; } else { if (deviceUpdate.getKey() == null || !existingDevice.getKey().equals(deviceUpdate.getKey().getValue())) { LOGGER.error("Device update key is null or doesn't equal to the authenticated device key {}", existingDevice.getKey()); throw new HiveException(Messages.INCORRECT_CREDENTIALS, UNAUTHORIZED.getStatusCode()); } if (deviceUpdate.getDeviceClass() != null) { existingDevice.setDeviceClass(deviceClass); } if (deviceUpdate.getStatus() != null) { existingDevice.setStatus(deviceUpdate.getStatus().getValue()); } if (deviceUpdate.getData() != null) { existingDevice.setData(deviceUpdate.getData().getValue()); } if (deviceUpdate.getNetwork() != null) { existingDevice.setNetwork(network); } final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_UPDATE); deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid()); return addDeviceNotification; } }
#vulnerable code public DeviceNotification deviceSave(DeviceUpdate deviceUpdate, Set<Equipment> equipmentSet) { Network network = networkService.createOrVeriryNetwork(deviceUpdate.getNetwork()); DeviceClass deviceClass = deviceClassService .createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet); Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue()); if (existingDevice == null) { Device device = deviceUpdate.convertTo(); if (deviceClass != null) { device.setDeviceClass(deviceClass); } if (network != null) { device.setNetwork(network); } existingDevice = deviceDAO.createDevice(device); final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_ADD); deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid()); return addDeviceNotification; } else { if (deviceUpdate.getKey() == null || !existingDevice.getKey().equals(deviceUpdate.getKey().getValue())) { LOGGER.error("Device update key {} doesn't equal to the authenticated device key {}", deviceUpdate.getKey().getValue(), existingDevice.getKey()); throw new HiveException(Messages.INCORRECT_CREDENTIALS, UNAUTHORIZED.getStatusCode()); } if (deviceUpdate.getDeviceClass() != null) { existingDevice.setDeviceClass(deviceClass); } if (deviceUpdate.getStatus() != null) { existingDevice.setStatus(deviceUpdate.getStatus().getValue()); } if (deviceUpdate.getData() != null) { existingDevice.setData(deviceUpdate.getData().getValue()); } if (deviceUpdate.getNetwork() != null) { existingDevice.setNetwork(network); } final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_UPDATE); deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid()); return addDeviceNotification; } } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Response get(String guid) { logger.debug("Device get requested. Guid {}", guid); HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Device device = deviceService.getDeviceWithNetworkAndDeviceClass(guid, principal); logger.debug("Device get proceed successfully. Guid {}", guid); return ResponseFactory.response(Response.Status.OK, device, DEVICE_PUBLISHED); }
#vulnerable code @Override public Response get(String guid) { logger.debug("Device get requested. Guid {}", guid); HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Device device = deviceService.getDeviceWithNetworkAndDeviceClass(guid, principal); if (principal.getRole().equals(HiveRoles.DEVICE)) { logger.debug("Device get proceed successfully. Guid {}", guid); return ResponseFactory.response(Response.Status.OK, device, DEVICE_PUBLISHED_DEVICE_AUTH); } logger.debug("Device get proceed successfully. Guid {}", guid); return ResponseFactory.response(Response.Status.OK, device, DEVICE_PUBLISHED); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldSendRequestToServer() throws Exception { CompletableFuture<Request> future = new CompletableFuture<>(); RequestHandler handler = request -> { future.complete(request); return Response.newBuilder() .withCorrelationId(request.getCorrelationId()) .withBody("Response".getBytes()) .withLast(true) .buildSuccess(); }; handlerWrapper.setDelegate(handler); Request request = Request.newBuilder() .withCorrelationId(UUID.randomUUID().toString()) .withSingleReply(true) .withBody("RequestResponseTest".getBytes()) .build(); client.push(request); Request receivedRequest = future.get(10, TimeUnit.SECONDS); assertEquals(request, receivedRequest); }
#vulnerable code @Test public void shouldSendRequestToServer() throws Exception { CompletableFuture<Request> future = new CompletableFuture<>(); RequestHandler mockedHandler = request -> { future.complete(request); return Response.newBuilder() .withCorrelationId(request.getCorrelationId()) .withBody("Response".getBytes()) .withLast(true) .buildSuccess(); }; RpcServer server = buildServer(mockedHandler); server.start(); RpcClient client = buildClient(); client.start(); Request request = Request.newBuilder() .withCorrelationId(UUID.randomUUID().toString()) .withSingleReply(true) .withBody("RequestResponseTest".getBytes()) .build(); TimeUnit.SECONDS.sleep(10); client.push(request); Request receivedRequest = future.get(20, TimeUnit.SECONDS); assertEquals(request, receivedRequest); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<Device> getDeviceList(List<String> guids, HivePrincipal principal) { List<Device> deviceList = new ArrayList<>(); for (String guid : guids) { Device device = findByUUID(guid); if (device != null) { deviceList.add(device); } } if (principal != null && principal.getUser() != null && !principal.getRole().equals(HiveRoles.ADMIN)) { Set<Long> networks = userNetworkDao.findNetworksForUser(principal.getUser().getId()); deviceList = deviceList .stream() .filter(d -> networks.contains(d.getNetwork().getId())) .collect(Collectors.toList()); } else if (principal != null && principal.getKey() != null && principal.getKey().getUser() != null) { Set<Long> networks = userNetworkDao.findNetworksForUser(principal.getKey().getUser().getId()); deviceList = deviceList .stream() .filter(d -> networks.contains(d.getNetwork().getId())) .collect(Collectors.toList()); } return deviceList; }
#vulnerable code @Override public List<Device> getDeviceList(List<String> guids, HivePrincipal principal) { List<Device> deviceList = new ArrayList<>(); if (principal == null || principal.getRole().equals(HiveRoles.ADMIN)) { for (String guid : guids) { Device device = findByUUID(guid); if (device != null) { deviceList.add(device); } } } else { try { BucketMapReduce.Builder builder = new BucketMapReduce.Builder() .withNamespace(DEVICE_NS) .withMapPhase(Function.newNamedJsFunction("Riak.mapValuesJson")); String functionString = "function(values, arg) {" + "return values.filter(function(v) {" + "var guid = v.guid;" + "return arg.indexOf(guid) > -1;" + "})" + "}"; Function reduceFunction = Function.newAnonymousJsFunction(functionString); builder.withReducePhase(reduceFunction, guids.toArray()); BucketMapReduce bmr = builder.build(); RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr); future.await(); MapReduce.Response response = future.get(); deviceList.addAll(response.getResultsFromAllPhases(Device.class)); if (principal.getUser() != null) { Set<Long> networks = userNetworkDao.findNetworksForUser(principal.getUser().getId()); deviceList = deviceList .stream() .filter(d -> networks.contains(d.getNetwork().getId())) .collect(Collectors.toList()); } } catch (InterruptedException | ExecutionException e) { logger.error("Exception accessing Riak Storage.", e); throw new HivePersistenceLayerException("Cannot get list of devices for list of UUIDs and principal.", e); } } return deviceList; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<NetworkVO> list(String name, String namePattern, String sortField, boolean sortOrderAsc, Integer take, Integer skip, Optional<HivePrincipal> principalOptional) { String sortFunc = sortMap.get(sortField); if (sortFunc == null) { sortFunc = sortMap.get("name"); } BucketMapReduce.Builder builder = new BucketMapReduce.Builder() .withNamespace(NETWORK_NS) .withMapPhase(Function.newAnonymousJsFunction("function(riakObject, keyData, arg) { " + " if(riakObject.values[0].metadata['X-Riak-Deleted']){ return []; } " + " else { return Riak.mapValuesJson(riakObject, keyData, arg); }}")) .withReducePhase(Function.newAnonymousJsFunction("function(values, arg) {" + "return values.filter(function(v) {" + "if (v === [] || v.name === null) { return false; }" + "return true;" + "})" + "}")); if (name != null) { String func = String.format( "function(values, arg) {" + "return values.filter(function(v) {" + "var name = v.name;" + "return name == '%s';" + "})" + "}", name); Function function = Function.newAnonymousJsFunction(func); builder.withReducePhase(function); } else if (namePattern != null) { namePattern = namePattern.replace("%", ""); String func = String.format( "function(values, arg) {" + "return values.filter(function(v) {" + "var name = v.name;" + "if (name === null) { return false; }" + "return name.indexOf('%s') > -1;" + "})" + "}", namePattern); Function function = Function.newAnonymousJsFunction(func); builder.withReducePhase(function); } if (principalOptional.isPresent()) { HivePrincipal principal = principalOptional.get(); if (principal != null && !principal.getRole().equals(HiveRoles.ADMIN)) { User user = principal.getUser(); if (user == null && principal.getKey() != null) { user = principal.getKey().getUser(); } if (user != null && !user.isAdmin()) { Set<Long> networks = userNetworkDao.findNetworksForUser(user.getId()); String functionString = "function(values, arg) {" + "return values.filter(function(v) {" + "var networkId = v.id;" + "return arg.indexOf(networkId) > -1;" + "})" + "}"; Function reduceFunction = Function.newAnonymousJsFunction(functionString); builder.withReducePhase(reduceFunction, networks); } if (principal.getKey() != null && principal.getKey().getPermissions() != null) { Set<AccessKeyPermission> permissions = principal.getKey().getPermissions(); Set<Long> ids = new HashSet<>(); for (AccessKeyPermission permission : permissions) { Set<Long> id = permission.getNetworkIdsAsSet(); if (id != null) { ids.addAll(id); } } String functionString = "function(values, arg) {" + "return values.filter(function(v) {" + "return arg.indexOf(v.id) > -1;" + "})" + "}"; Function reduceFunction = Function.newAnonymousJsFunction(functionString); if (!ids.isEmpty()) builder.withReducePhase(reduceFunction, ids); } else if (principal.getDevice() != null) { String functionString = "function(values, arg) {" + "return values.filter(function(v) {" + "var devices = v.devices;" + "if (devices == null) return false;" + "return devices.indexOf(arg) > -1;" + "})" + "}"; Function reduceFunction = Function.newAnonymousJsFunction(functionString); builder.withReducePhase(reduceFunction, principal.getDevice()); } } } builder.withReducePhase(Function.newNamedJsFunction("Riak.reduceSort"), String.format(sortFunc, sortOrderAsc ? ">" : "<"), true); if (take == null) take = Constants.DEFAULT_TAKE; if (skip == null) skip = 0; BucketMapReduce bmr = builder.build(); RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr); try { MapReduce.Response response = future.get(); List<RiakNetwork> result = response.getResultsFromAllPhases(RiakNetwork.class).stream() .skip(skip) .limit(take) .collect(Collectors.toList()); return result.stream().map(RiakNetwork::convert).collect(Collectors.toList()); } catch (InterruptedException | ExecutionException e) { throw new HivePersistenceLayerException("Cannot get list of networks.", e); } }
#vulnerable code @Override public List<NetworkVO> list(String name, String namePattern, String sortField, boolean sortOrderAsc, Integer take, Integer skip, Optional<HivePrincipal> principalOptional) { String sortFunc = sortMap.get(sortField); if (sortFunc == null) { sortFunc = sortMap.get("name"); } BucketMapReduce.Builder builder = new BucketMapReduce.Builder() .withNamespace(NETWORK_NS) .withMapPhase(Function.newAnonymousJsFunction("function(riakObject, keyData, arg) { " + " if(riakObject.values[0].metadata['X-Riak-Deleted']){ return []; } " + " else { return Riak.mapValuesJson(riakObject, keyData, arg); }}")) .withReducePhase(Function.newAnonymousJsFunction("function(values, arg) {" + "return values.filter(function(v) {" + "if (v === [] || v.name === null) { return false; }" + "return true;" + "})" + "}")); if (name != null) { String func = String.format( "function(values, arg) {" + "return values.filter(function(v) {" + "var name = v.name;" + "return name == '%s';" + "})" + "}", name); Function function = Function.newAnonymousJsFunction(func); builder.withReducePhase(function); } else if (namePattern != null) { namePattern = namePattern.replace("%", ""); String func = String.format( "function(values, arg) {" + "return values.filter(function(v) {" + "var name = v.name;" + "if (name === null) { return false; }" + "return name.indexOf('%s') > -1;" + "})" + "}", namePattern); Function function = Function.newAnonymousJsFunction(func); builder.withReducePhase(function); } if (principalOptional.isPresent()) { HivePrincipal principal = principalOptional.get(); if (principal != null && !principal.getRole().equals(HiveRoles.ADMIN)) { User user = principal.getUser(); if (user == null && principal.getKey() != null) { user = principal.getKey().getUser(); } if (user != null && !user.isAdmin()) { Set<Long> networks = userNetworkDao.findNetworksForUser(user.getId()); String functionString = "function(values, arg) {" + "return values.filter(function(v) {" + "var networkId = v.id;" + "return arg.indexOf(networkId) > -1;" + "})" + "}"; Function reduceFunction = Function.newAnonymousJsFunction(functionString); builder.withReducePhase(reduceFunction, networks); } if (principal.getKey() != null && principal.getKey().getPermissions() != null) { Set<AccessKeyPermission> permissions = principal.getKey().getPermissions(); Set<Long> ids = new HashSet<>(); for (AccessKeyPermission permission : permissions) { Set<Long> id = permission.getNetworkIdsAsSet(); if (id != null) { ids.addAll(id); } } String functionString = "function(values, arg) {" + "return values.filter(function(v) {" + "return arg.indexOf(v.id) > -1;" + "})" + "}"; Function reduceFunction = Function.newAnonymousJsFunction(functionString); if (!ids.isEmpty()) builder.withReducePhase(reduceFunction, ids); } else if (principal.getDevice() != null) { String functionString = "function(values, arg) {" + "return values.filter(function(v) {" + "var devices = v.devices;" + "if (devices == null) return false;" + "return devices.indexOf(arg) > -1;" + "})" + "}"; Function reduceFunction = Function.newAnonymousJsFunction(functionString); builder.withReducePhase(reduceFunction, principal.getDevice()); } } } builder.withReducePhase(Function.newNamedJsFunction("Riak.reduceSort"), String.format(sortFunc, sortOrderAsc ? ">" : "<"), true); if (take == null) take = Constants.DEFAULT_TAKE; if (skip == null) skip = 0; BucketMapReduce bmr = builder.build(); RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr); try { MapReduce.Response response = future.get(); return response.getResultsFromAllPhases(NetworkVO.class).stream() .skip(skip) .limit(take) .collect(Collectors.toList()); } catch (InterruptedException | ExecutionException e) { throw new HivePersistenceLayerException("Cannot get list of networks.", e); } } #location 47 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { ProtobufRPC protobufPRC = method.getAnnotation(ProtobufRPC.class); if (protobufPRC == null) { throw new IllegalAccessError("Target method is not marked annotation @ProtobufPRC. method name :" + method.getDeclaringClass().getName() + "." + method.getName()); } String serviceName = protobufPRC.serviceName(); String methodName = protobufPRC.methodName(); if (StringUtils.isEmpty(methodName)) { methodName = method.getName(); } String methodSignature = serviceName + '!' + methodName; RpcMethodInfo rpcMethodInfo = cachedRpcMethods.get(methodSignature); if (rpcMethodInfo == null) { throw new IllegalAccessError("Can not invoke method '" + method.getName() + "' due to not a protbufRpc method."); } long onceTalkTimeout = rpcMethodInfo.getOnceTalkTimeout(); if (onceTalkTimeout <= 0) { // use default once talk timeout onceTalkTimeout = rpcClient.getRpcClientOptions().getOnceTalkTimeout(); } BlockingRpcCallback callback = new BlockingRpcCallback(); RpcDataPackage rpcDataPackage = buildRequestDataPackage(rpcMethodInfo, args); // set correlationId rpcDataPackage.getRpcMeta().setCorrelationId(rpcClient.getNextCorrelationId()); RpcChannel rpcChannel = rpcChannelMap.get(methodSignature); if (rpcChannel == null) { throw new RuntimeException("No rpcChannel bind with serviceSignature '" + methodSignature + "'"); } rpcChannel.doTransport(rpcDataPackage, callback, onceTalkTimeout); if (!callback.isDone()) { synchronized (callback) { while (!callback.isDone()) { try { callback.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } RpcDataPackage message = callback.getMessage(); RpcResponseMeta response = message.getRpcMeta().getResponse(); if (response != null) { Integer errorCode = response.getErrorCode(); if (!ErrorCodes.isSuccess(errorCode)) { String error = message.getRpcMeta().getResponse().getErrorText(); throw new Throwable("A error occurred: errorCode=" + errorCode + " errorMessage:" + error); } } byte[] attachment = message.getAttachment(); if (attachment != null) { ClientAttachmentHandler attachmentHandler = rpcMethodInfo.getClientAttachmentHandler(); if (attachmentHandler != null) { attachmentHandler.handleResponse(attachment, serviceName, methodName, args); } } // handle response data byte[] data = message.getData(); if (data == null) { return null; } return rpcMethodInfo.outputDecode(data); }
#vulnerable code public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { ProtobufRPC protobufPRC = method.getAnnotation(ProtobufRPC.class); if (protobufPRC == null) { throw new IllegalAccessError("Target method is not marked annotation @ProtobufPRC. method name :" + method.getDeclaringClass().getName() + "." + method.getName()); } String serviceName = protobufPRC.serviceName(); String methodName = protobufPRC.methodName(); if (StringUtils.isEmpty(methodName)) { methodName = method.getName(); } String methodSignature = serviceName + '!' + methodName; RpcMethodInfo rpcMethodInfo = cachedRpcMethods.get(methodSignature); if (rpcMethodInfo == null) { throw new IllegalAccessError("Can not invoke method '" + method.getName() + "' due to not a protbufRpc method."); } long onceTalkTimeout = rpcMethodInfo.getOnceTalkTimeout(); if (onceTalkTimeout <= 0) { // use default once talk timeout onceTalkTimeout = rpcClient.getRpcClientOptions().getOnceTalkTimeout(); } BlockingRpcCallback callback = new BlockingRpcCallback(); RpcDataPackage rpcDataPackage = buildRequestDataPackage(rpcMethodInfo, args); // set correlationId rpcDataPackage.getRpcMeta().setCorrelationId(rpcClient.getNextCorrelationId()); rpcChannel.doTransport(rpcDataPackage, callback, onceTalkTimeout); if (!callback.isDone()) { synchronized (callback) { while (!callback.isDone()) { try { callback.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } RpcDataPackage message = callback.getMessage(); RpcResponseMeta response = message.getRpcMeta().getResponse(); if (response != null) { Integer errorCode = response.getErrorCode(); if (!ErrorCodes.isSuccess(errorCode)) { String error = message.getRpcMeta().getResponse().getErrorText(); throw new Throwable("A error occurred: errorCode=" + errorCode + " errorMessage:" + error); } } byte[] attachment = message.getAttachment(); if (attachment != null) { ClientAttachmentHandler attachmentHandler = rpcMethodInfo.getClientAttachmentHandler(); if (attachmentHandler != null) { attachmentHandler.handleResponse(attachment, serviceName, methodName, args); } } // handle response data byte[] data = message.getData(); if (data == null) { return null; } return rpcMethodInfo.outputDecode(data); } #location 31 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); ProtobufRPC protobufPRC = method.getAnnotation(ProtobufRPC.class); if (protobufPRC == null) { throw new IllegalAccessError("Target method is not marked annotation @ProtobufPRC. method name :" + method.getDeclaringClass().getName() + "." + method.getName()); } String serviceName = protobufPRC.serviceName(); String methodName = protobufPRC.methodName(); if (StringUtils.isEmpty(methodName)) { methodName = method.getName(); } String methodSignature = serviceName + '!' + methodName; Object instance = instancesMap.get(methodSignature); if (instance == null) { throw new NullPointerException("target instance is null may be not initial correct."); } Object result = invocation.getMethod().invoke(instance, invocation.getArguments()); return result; }
#vulnerable code @Override public Object invoke(MethodInvocation invocation) throws Throwable { if (instance == null) { throw new NullPointerException("target instance is null may be not initial correct."); } Object result = invocation.getMethod().invoke(instance, invocation.getArguments()); return result; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void reInit(final String service, final List<InetSocketAddress> list) throws Exception { // store old LoadBalanceProxyFactoryBean oldLbProxyBean = lbMap.get(service); List<ProtobufRpcProxy<T>> oldProtobufRpcProxyList = new ArrayList<ProtobufRpcProxy<T>>(protobufRpcProxyListMap.get(service)); // create a new instance doProxy(service, list); try { // try to close old doClose(oldLbProxyBean, oldProtobufRpcProxyList); } catch (Exception e) { LOGGER.fatal(e.getMessage(), e); } }
#vulnerable code @Override protected void reInit(final String service, final List<InetSocketAddress> list) throws Exception { // store old LoadBalanceProxyFactoryBean oldLbProxyBean = lbMap.get(service); List<ProtobufRpcProxy<T>> oldProtobufRpcProxyList = new ArrayList<ProtobufRpcProxy<T>>(protobufRpcProxyListMap.get(service)); // reinit naming service loadBalanceStrategy.doReInit(service, new NamingService() { @Override public Map<String, List<InetSocketAddress>> list(Set<String> serviceSignatures) throws Exception { Map<String, List<InetSocketAddress>> ret = new HashMap<String, List<InetSocketAddress>>(); ret.put(service, list); return ret; } }); // create a new instance doProxy(service, list); try { // try to close old doClose(oldLbProxyBean, oldProtobufRpcProxyList); } catch (Exception e) { LOGGER.fatal(e.getMessage(), e); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExecuteAndFetchWithNulls(){ String sql = "create table testExecWithNullsTbl (" + "id int identity primary key, " + "text varchar(255), " + "aNumber int, " + "aLongNumber bigint)"; try (Connection con = sql2o.open()) { con.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate(); Connection connection = sql2o.beginTransaction(); Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)"); insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", (Integer) null).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", (String) null).addParameter("number", 21).addParameter("lnum", (Long) null).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate(); connection.commit(); List<Entity> fetched = con.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class); assertTrue(fetched.size() == 5); assertNull(fetched.get(2).text); assertNotNull(fetched.get(3).text); assertNull(fetched.get(1).aNumber); assertNotNull(fetched.get(2).aNumber); assertNull(fetched.get(2).aLongNumber); assertNotNull(fetched.get(3).aLongNumber); } }
#vulnerable code @Test public void testExecuteAndFetchWithNulls(){ String sql = "create table testExecWithNullsTbl (" + "id int identity primary key, " + "text varchar(255), " + "aNumber int, " + "aLongNumber bigint)"; sql2o.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate(); Connection connection = sql2o.beginTransaction(); Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)"); insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", (Integer)null).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", (String)null).addParameter("number", 21).addParameter("lnum", (Long)null).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate(); connection.commit(); List<Entity> fetched = sql2o.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class); assertTrue(fetched.size() == 5); assertNull(fetched.get(2).text); assertNotNull(fetched.get(3).text); assertNull(fetched.get(1).aNumber); assertNotNull(fetched.get(2).aNumber); assertNull(fetched.get(2).aLongNumber); assertNotNull(fetched.get(3).aLongNumber); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExecuteAndFetch(){ createAndFillUserTable(); try (Connection con = sql2o.open()) { Date before = new Date(); List<User> allUsers = con.createQuery("select * from User").executeAndFetch(User.class); assertNotNull(allUsers); Date after = new Date(); long span = after.getTime() - before.getTime(); System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span)); // repeat this before = new Date(); allUsers = con.createQuery("select * from User").executeAndFetch(User.class); after = new Date(); span = after.getTime() - before.getTime(); System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span)); assertTrue(allUsers.size() == insertIntoUsers); } deleteUserTable(); }
#vulnerable code @Test public void testExecuteAndFetch(){ createAndFillUserTable(); Date before = new Date(); List<User> allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class); Date after = new Date(); long span = after.getTime() - before.getTime(); System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span)); // repeat this before = new Date(); allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class); after = new Date(); span = after.getTime() - before.getTime(); System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span)); assertTrue(allUsers.size() == insertIntoUsers); deleteUserTable(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testUpdateWithParameter() { try (Database db = db()) { db.update("update person set score=20 where name=?") // .parameter("FRED").counts() // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(1) // .assertComplete(); } }
#vulnerable code @Test public void testUpdateWithParameter() { db().update("update person set score=20 where name=?") // .parameter("FRED").counts() // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(1) // .assertComplete(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { try (Database db = db()) { db // .select("select name, score from person order by name") // .autoMap(Person4.class) // .firstOrError() // .map(Person4::examScore) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoValues() // .assertError(ColumnNotFoundException.class); } }
#vulnerable code @Test public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { db() // .select("select name, score from person order by name") // .autoMap(Person4.class) // .firstOrError() // .map(Person4::examScore) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoValues() // .assertError(ColumnNotFoundException.class); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testUpdateTimeParameter() { try (Database db = db()) { Time t = new Time(1234); db.update("update person set registered=?") // .parameter(t) // .counts() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(3) // .assertComplete(); db.select("select registered from person") // .getAs(Long.class) // .firstOrError() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(1234L) // .assertComplete(); } }
#vulnerable code @Test public void testUpdateTimeParameter() { Database db = db(); Time t = new Time(1234); db.update("update person set registered=?") // .parameter(t) // .counts() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(3) // .assertComplete(); db.select("select registered from person") // .getAs(Long.class) // .firstOrError() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(1234L) // .assertComplete(); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testInsertNullClobAndReadClobAsTuple2() { try (Database db = db()) { insertNullClob(db); db.select("select document, document from person_clob where name='FRED'") // .getAs(String.class, String.class) // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(Tuple2.create(null, null)) // .assertComplete(); } }
#vulnerable code @Test public void testInsertNullClobAndReadClobAsTuple2() { Database db = db(); insertNullClob(db); db.select("select document, document from person_clob where name='FRED'") // .getAs(String.class, String.class) // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(Tuple2.create(null, null)) // .assertComplete(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Ignore public void testCallableApi() { Database db = DatabaseCreator.createDerbyWithStoredProcs(1); db // .call("call getPersonCount(?,?)") // .in() // .out(Type.INTEGER, Integer.class) // .build() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(2) // .assertComplete(); }
#vulnerable code @Test @Ignore public void testCallableApi() { Database db = DatabaseCreator.createDerbyWithStoredProcs(1); db // .call("call getPersonCount(?,?)") // .in(0) // .out(Integer.class) // .build() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(2) // .assertComplete(); ; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCountsInTransaction() { try (Database db = db()) { db.update("update person set score = -3") // .transacted() // .counts() // .doOnNext(System.out::println) // .toList() // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 && list.get(1).isComplete() && list.size() == 2) // .assertComplete(); } }
#vulnerable code @Test public void testCountsInTransaction() { db().update("update person set score = -3") // .transacted() // .counts() // .doOnNext(System.out::println) // .toList() // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 && list.get(1).isComplete() && list.size() == 2) // .assertComplete(); } #location 5 #vulnerability type RESOURCE_LEAK