output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#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 private static HashSet loadSet(String setname, String filename) { HashSet set = new HashSet(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase()); } br.close(); serverLog.logInfo("PROXY", "read " + setname + " set from file " + filename); } catch (IOException e) { } finally { if (br != null) try { br.close(); } catch (Exception e) {} } return set; }
#vulnerable code private static HashSet loadSet(String setname, String filename) { HashSet set = new HashSet(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase()); } br.close(); serverLog.logInfo("PROXY", "read " + setname + " set from file " + filename); } catch (IOException e) {} return set; } #location 12 #vulnerability type RESOURCE_LEAK
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 int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException { // make space for new words int flushc = 0; //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size()); synchronized (hashScore) { while (hashScore.size() > maxWords) flushc += flushSpecific(true); } //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries"); // put new words into cache synchronized (cache) { Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null if (v == null) v = new Vector(); v.add(entry); cache.put(wordHash, v); hashScore.incScore(wordHash); } return flushc; }
#vulnerable code public int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException { // make space for new words int flushc = 0; //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size()); synchronized (hashScore) { while (hashScore.size() > maxWords) flushc += flushSpecific(true); } //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries"); // put new words into cache Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null if (v == null) v = new Vector(); v.add(entry); cache.put(wordHash, v); hashScore.incScore(wordHash); return flushc; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
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 protected void initDataComposer(IDataComposer dataComposer, HttpServletRequest request) { String paramName = (String) request.getSession().getAttribute(Constants.MODIFY_STATE_HDIV_PARAMETER); String preState = paramName != null ? request.getParameter(paramName) : null; if (preState != null && preState.length() > 0) { // We are modifying an existing state, preload dataComposer with it IState state = this.stateUtil.restoreState(preState); if (state.getPageId() > 0) { IPage page = this.session.getPage(state.getPageId() + ""); if (page != null) { dataComposer.startPage(page); } } if (state != null) { dataComposer.beginRequest(state); } } else if (this.config.isReuseExistingPageInAjaxRequest() && isAjaxRequest(request)) { String hdivStateParamName = (String) request.getSession().getAttribute(Constants.HDIV_PARAMETER); String hdivState = request.getParameter(hdivStateParamName); if (hdivState != null) { IState state = this.stateUtil.restoreState(hdivState); if (state.getPageId() > 0) { IPage page = this.session.getPage(Integer.toString(state.getPageId())); dataComposer.startPage(page); } else { dataComposer.startPage(); } } else { dataComposer.startPage(); } } else { dataComposer.startPage(); } // Detect if request url is configured as a long living page String url = request.getRequestURI().substring(request.getContextPath().length()); String scope = this.config.isLongLivingPages(url); if (scope != null) { dataComposer.startScope(scope); } }
#vulnerable code protected void initDataComposer(IDataComposer dataComposer, HttpServletRequest request) { String paramName = (String) request.getSession().getAttribute(Constants.MODIFY_STATE_HDIV_PARAMETER); String preState = paramName != null ? request.getParameter(paramName) : null; if (preState != null && preState.length() > 0) { // We are modifying an existing state, preload dataComposer with it IState state = this.stateUtil.restoreState(preState); if (state.getPageId() > 0) { IPage page = this.session.getPage(state.getPageId() + ""); if (page != null) { dataComposer.startPage(page); } } if (state != null) { dataComposer.beginRequest(state); } } else if (this.config.isReuseExistingPageInAjaxRequest() && isAjaxRequest(request)) { String hdivStateParamName = (String) request.getSession().getAttribute(Constants.HDIV_PARAMETER); String hdivState = request.getParameter(hdivStateParamName); IState state = this.stateUtil.restoreState(hdivState); IPage page = this.session.getPage(Integer.toString(state.getPageId())); dataComposer.startPage(page); } else { dataComposer.startPage(); } // Detect if request url is configured as a long living page String url = request.getRequestURI().substring(request.getContextPath().length()); String scope = this.config.isLongLivingPages(url); if (scope != null) { dataComposer.startScope(scope); } } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public StatusEnum process(String optType, String optId, StatusEnum initStatus, long expireMs) { if (Dew.cluster.cache.setnx(CACHE_KEY + optType + ":" + optId, initStatus.toString(), expireMs / 1000)) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { // 设置不成功,表示之前存在,返回存在的值 String status = Dew.cluster.cache.get(CACHE_KEY + optType + ":" + optId); if (status == null || status.isEmpty()) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { return StatusEnum.valueOf(status); } } }
#vulnerable code @Override public StatusEnum process(String optType, String optId, StatusEnum initStatus, long expireMs) { if (Dew.cluster.cache.setnx(CACHE_KEY + optType + ":" + optId, initStatus.toString(), expireMs / 1000)) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { // 设置不成功,表示之前存在,返回存在的值 String status = Dew.cluster.cache.get(CACHE_KEY + optType + ":" + optId); if (status == null && status.isEmpty()) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { return StatusEnum.valueOf(status); } } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void register(final DynamicConfig config) { BrokerRole role = BrokerConfig.getBrokerRole(); if(role != BrokerRole.BACKUP) throw new RuntimeException("Only support backup"); final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); IndexLog log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); FixedExecOrderEventBus.Listener<MessageQueryIndex> indexProcessor = getConstructIndexListener(keyGenerator , messageQueryIndex -> log.commit(messageQueryIndex.getCurrentOffset())); bus.subscribe(MessageQueryIndex.class, indexProcessor); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); LogIterateService<MessageQueryIndex> iterateService = new LogIterateService<>("index", new StorageConfigImpl(config), log, checkpointManager.getIndexIterateCheckpoint(), bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, masterSlaveSyncManager); }
#vulnerable code private void register(final DynamicConfig config) { final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); BrokerRole role = BrokerConfig.getBrokerRole(); IndexLog log; if (role == BrokerRole.BACKUP) { final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); bus.subscribe(MessageQueryIndex.class, getConstructIndexListener(keyGenerator , messageQueryIndex -> log.setDeleteTo(messageQueryIndex.getCurrentOffset()))); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); } else if (role == BrokerRole.DELAY_BACKUP) { throw new RuntimeException("check the role is correct, only backup is allowed."); } else { throw new RuntimeException("check the role is correct, only backup is allowed."); } IndexLogIterateService iterateService = new IndexLogIterateService(config, log, checkpointManager, bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, iterateService, masterSlaveSyncManager); } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void recover() { if (segments.isEmpty()) { return; } LOG.info("Recovering logs."); final List<Long> baseOffsets = new ArrayList<>(segments.navigableKeySet()); final int offsetCount = baseOffsets.size(); long offset = -1; for (int i = offsetCount - 2; i < offsetCount; i++) { if (i < 0) continue; final LogSegment segment = segments.get(baseOffsets.get(i)); offset = segment.getBaseOffset(); final LogSegmentValidator.ValidateResult result = segmentValidator.validate(segment); offset += result.getValidatedSize(); if (result.getStatus() == LogSegmentValidator.ValidateStatus.COMPLETE) { segment.setWrotePosition(segment.getFileSize()); } else { break; } } flushedOffset = offset; final LogSegment latestSegment = latestSegment(); final long maxOffset = latestSegment.getBaseOffset() + latestSegment.getFileSize(); final int relativeOffset = (int) (offset % fileSize); final LogSegment segment = locateSegment(offset); if (segment != null && maxOffset != offset) { segment.setWrotePosition(relativeOffset); LOG.info("recover wrote offset to {}:{}", segment, segment.getWrotePosition()); if (segment.getBaseOffset() != latestSegment.getBaseOffset()) { LOG.info("will remove all segment after max wrote position. current base offset: {}, max base offset: {}", segment.getBaseOffset(), latestSegment.getBaseOffset()); deleteSegmentsAfterOffset(offset); } } LOG.info("Recover done."); }
#vulnerable code private void recover() { if (segments.isEmpty()) { return; } LOG.info("Recovering logs."); final List<Long> baseOffsets = new ArrayList<>(segments.navigableKeySet()); final int offsetCount = baseOffsets.size(); long offset = -1; for (int i = offsetCount - 2; i < offsetCount; i++) { if (i < 0) continue; final LogSegment segment = segments.get(baseOffsets.get(i)); offset = segment.getBaseOffset(); final LogSegmentValidator.ValidateResult result = segmentValidator.validate(segment); offset += result.getValidatedSize(); if (result.getStatus() == LogSegmentValidator.ValidateStatus.COMPLETE) { segment.setWrotePosition(segment.getFileSize()); } else { break; } } flushedOffset = offset; final long maxOffset = latestSegment().getBaseOffset() + latestSegment().getFileSize(); final int relativeOffset = (int) (offset % fileSize); final LogSegment segment = locateSegment(offset); if (segment != null && maxOffset != offset) { segment.setWrotePosition(relativeOffset); LOG.info("recover wrote offset to {}:{}", segment, segment.getWrotePosition()); // TODO(keli.wang): should delete crash file } LOG.info("Recover done."); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void register(final DynamicConfig config) { BrokerRole role = BrokerConfig.getBrokerRole(); if(role != BrokerRole.BACKUP) throw new RuntimeException("Only support backup"); final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); IndexLog log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); FixedExecOrderEventBus.Listener<MessageQueryIndex> indexProcessor = getConstructIndexListener(keyGenerator , messageQueryIndex -> log.commit(messageQueryIndex.getCurrentOffset())); bus.subscribe(MessageQueryIndex.class, indexProcessor); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); LogIterateService<MessageQueryIndex> iterateService = new LogIterateService<>("index", new StorageConfigImpl(config), log, checkpointManager.getIndexIterateCheckpoint(), bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, masterSlaveSyncManager); }
#vulnerable code private void register(final DynamicConfig config) { final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); BrokerRole role = BrokerConfig.getBrokerRole(); IndexLog log; if (role == BrokerRole.BACKUP) { final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); bus.subscribe(MessageQueryIndex.class, getConstructIndexListener(keyGenerator , messageQueryIndex -> log.setDeleteTo(messageQueryIndex.getCurrentOffset()))); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); } else if (role == BrokerRole.DELAY_BACKUP) { throw new RuntimeException("check the role is correct, only backup is allowed."); } else { throw new RuntimeException("check the role is correct, only backup is allowed."); } IndexLogIterateService iterateService = new IndexLogIterateService(config, log, checkpointManager, bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, iterateService, masterSlaveSyncManager); } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void initRocksDB() { try { Options options = new Options(); options.setCreateIfMissing(true); rocksDB = RocksDB.open(options, DB_FILE); } catch (RocksDBException e) { e.printStackTrace(); } }
#vulnerable code private void initRocksDB() { try { rocksDB = RocksDB.open(new Options().setCreateIfMissing(true), DB_FILE); } catch (RocksDBException e) { e.printStackTrace(); } } #location 3 #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 loadResource(Yaml yaml, InputStream yamlStream, String filename) { Node loadedYaml = yaml.compose(new UnicodeReader(yamlStream)); if (loadedYaml == null) { throw new InvalidParserConfigurationException("The file " + filename + " is empty"); } // Get and check top level config if (!(loadedYaml instanceof MappingNode)) { fail(loadedYaml, filename, "File must be a Map"); } MappingNode rootNode = (MappingNode) loadedYaml; NodeTuple configNodeTuple = null; for (NodeTuple tuple : rootNode.getValue()) { String name = getKeyAsString(tuple, filename); if ("config".equals(name)) { configNodeTuple = tuple; break; } } if (configNodeTuple == null) { fail(loadedYaml, filename, "The top level entry MUST be 'config'."); } SequenceNode configNode = getValueAsSequenceNode(configNodeTuple, filename); List<Node> configList = configNode.getValue(); for (Node configEntry : configList) { if (!(configEntry instanceof MappingNode)) { fail(loadedYaml, filename, "The entry MUST be a mapping"); } NodeTuple entry = getExactlyOneNodeTuple((MappingNode) configEntry, filename); MappingNode actualEntry = getValueAsMappingNode(entry, filename); String entryType = getKeyAsString(entry, filename); switch (entryType) { case "lookup": loadYamlLookup(actualEntry, filename); break; case "matcher": loadYamlMatcher(actualEntry, filename); break; case "test": loadYamlTestcase(actualEntry, filename); break; default: throw new InvalidParserConfigurationException( "Yaml config.(" + filename + ":" + actualEntry.getStartMark().getLine() + "): " + "Found unexpected config entry: " + entryType + ", allowed are 'lookup, 'matcher' and 'test'"); } } }
#vulnerable code private void loadResource(Yaml yaml, InputStream yamlStream, String filename) { Node loadedYaml = yaml.compose(new UnicodeReader(yamlStream)); if (loadedYaml == null) { LOG.error("The file {} is empty", filename); return; } // Get and check top level config if (!(loadedYaml instanceof MappingNode)) { fail(loadedYaml, filename, "File must be a Map"); } MappingNode rootNode = (MappingNode) loadedYaml; NodeTuple configNodeTuple = null; for (NodeTuple tuple : rootNode.getValue()) { String name = getKeyAsString(tuple, filename); if ("config".equals(name)) { configNodeTuple = tuple; break; } } String configKeyName = getKeyAsString(configNodeTuple, filename); if (!configKeyName.equals("config")) { fail(loadedYaml, filename, "The top level entry MUST be 'config'."); } SequenceNode configNode = getValueAsSequenceNode(configNodeTuple, filename); List<Node> configList = configNode.getValue(); for (Node configEntry : configList) { if (!(configEntry instanceof MappingNode)) { fail(loadedYaml, filename, "The entry MUST be a mapping"); } NodeTuple entry = getExactlyOneNodeTuple((MappingNode) configEntry, filename); MappingNode actualEntry = getValueAsMappingNode(entry, filename); String entryType = getKeyAsString(entry, filename); switch (entryType) { case "lookup": loadYamlLookup(actualEntry, filename); break; case "matcher": loadYamlMatcher(actualEntry, filename); break; case "test": loadYamlTestcase(actualEntry, filename); break; default: throw new InvalidParserConfigurationException( "Yaml config.(" + filename + ":" + actualEntry.getStartMark().getLine() + "): " + "Found unexpected config entry: " + entryType + ", allowed are 'lookup, 'matcher' and 'test'"); } } } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void informSubstrings(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 firstWords; while((firstWords = WordSplitter.getFirstWords(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstWords, true); inform(ctx, ctx, name + "%" + count, firstWords.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = WordSplitter.findNextWordStart(chars, firstWords.length()); } }
#vulnerable code private void informSubstrings(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 firstWords; while((firstWords = WordSplitter.getFirstWords(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstWords, true); // inform(ctx, ctx, name + "%" + count, WordSplitter.getSingleWord(text, count), true); inform(ctx, ctx, name + "%" + count, firstWords.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = WordSplitter.findNextWordStart(chars, firstWords.length()); } } #location 7 #vulnerability type NULL_DEREFERENCE
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 @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { Biz biz = DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager); if (biz == null) { continue; } if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "failed"); } else { builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } }
#vulnerable code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "failed"); } else { builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } } #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 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 Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { Biz biz = DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager); if (biz == null) { continue; } if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "failed"); } else { builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } }
#vulnerable code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "failed"); } else { builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } } #location 10 #vulnerability type NULL_DEREFERENCE
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 @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 initCollapseAnimations(String state){ collapseAnim = new Timeline(this); switch (state){ case "expand":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),MAX_WIDTH); break; } case "collapse":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),configManager.getFrameSettings(this.getClass().getSimpleName()).getFrameSize().width); } } collapseAnim.setEase(new Spline(1f)); collapseAnim.setDuration(300); }
#vulnerable code private void initCollapseAnimations(String state){ collapseAnim = new Timeline(this); switch (state){ case "expand":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),250); break; } case "collapse":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),configManager.getFrameSettings(this.getClass().getSimpleName()).getFrameSize().width); } } collapseAnim.setEase(new Spline(1f)); collapseAnim.setDuration(300); } #location 9 #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 private JPanel getFormattedMessagePanel(String message){ JPanel labelsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); labelsPanel.setBackground(AppThemeColor.TRANSPARENT); String itemName = StringUtils.substringBetween(message, "to buy your ", " listed for"); if(itemName == null){ itemName = StringUtils.substringBetween(message, "to buy your ", " for my"); } itemLabel = new ExLabel(itemName); itemLabel.setForeground(AppThemeColor.TEXT_IMPORTANT); labelsPanel.add(itemLabel); ExLabel secondPart = new ExLabel("listed for "); secondPart.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(secondPart); String price = StringUtils.substringBetween(message, "listed for ", " in "); if(price == null){ price = StringUtils.substringBetween(message, "for my ", " in "); } if(price != null) { String[] split = price.split(" "); ExLabel currencyLabel = null; BufferedImage buttonIcon = null; try { switch (split[1]) { case "chaos": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Chaos_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "exalted": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Exalted_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "fusing": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Orb_of_Fusing.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "vaal": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Vaal_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } default: currencyLabel = new ExLabel(split[1]); currencyLabel.setForeground(AppThemeColor.TEXT_MESSAGE); break; } } catch (IOException e) { e.printStackTrace(); } ExLabel priceLabel = new ExLabel(split[0]); priceLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(priceLabel); labelsPanel.add(currencyLabel); } String offer = StringUtils.substringAfterLast(message, "in Breach"); //todo String tabName = StringUtils.substringBetween(message, "(stash tab ", "; position:"); if(tabName !=null ){ offer = StringUtils.substringAfter(message, ")"); } ExLabel offerLabel = new ExLabel(offer); offerLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(offerLabel); if(offer.length() > 1){ Dimension rectSize = new Dimension(); rectSize.setSize(350, 130); this.setMaximumSize(rectSize); this.setMinimumSize(rectSize); this.setPreferredSize(rectSize); } return labelsPanel; }
#vulnerable code private JPanel getFormattedMessagePanel(String message){ JPanel labelsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); labelsPanel.setBackground(AppThemeColor.TRANSPARENT); String itemName = StringUtils.substringBetween(message, "to buy your ", " listed for"); if(itemName == null){ itemName = StringUtils.substringBetween(message, "to buy your ", " for my"); } itemLabel = new ExLabel(itemName); itemLabel.setForeground(AppThemeColor.TEXT_IMPORTANT); labelsPanel.add(itemLabel); ExLabel secondPart = new ExLabel("listed for "); secondPart.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(secondPart); String price = StringUtils.substringBetween(message, "listed for ", " in "); if(price == null){ price = StringUtils.substringBetween(message, "for my ", " in "); } String[] split = price.split(" "); ExLabel currencyLabel = null; BufferedImage buttonIcon = null; try { switch (split[1]) { case "chaos": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Chaos_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "exalted": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Exalted_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } default: currencyLabel = new ExLabel(split[1]); currencyLabel.setForeground(AppThemeColor.TEXT_MESSAGE); break; } } catch (IOException e) { e.printStackTrace(); } ExLabel priceLabel = new ExLabel(split[0]); priceLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(priceLabel); labelsPanel.add(currencyLabel); String offer = StringUtils.substringAfterLast(message, "in Breach"); //todo String tabName = StringUtils.substringBetween(message, "(stash tab ", "; position:"); if(tabName !=null ){ offer = StringUtils.substringAfter(message, ")"); } ExLabel offerLabel = new ExLabel(offer); offerLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(offerLabel); return labelsPanel; } #location 21 #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 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void load(){ File configFile = new File(HISTORY_FILE); if (configFile.exists()) { JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject)parser.parse(new FileReader(HISTORY_FILE)); JSONArray msgsArray = (JSONArray) root.get("messages"); messages = new String[msgsArray.size()]; for (int i = 0; i < msgsArray.size(); i++) { messages[i] = (String) msgsArray.get(i); } } catch (Exception e) { logger.error("Error during loading history file: ", e); } }else { createEmptyFile(); } }
#vulnerable code public void load(){ File configFile = new File(HISTORY_FILE); if (configFile.exists()) { JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject)parser.parse(new FileReader(HISTORY_FILE)); JSONArray msgsArray = (JSONArray) root.get("messages"); messages = new String[msgsArray.size()]; for (int i = 0; i < msgsArray.size(); i++) { messages[i] = (String) msgsArray.get(i); } } catch (Exception e) { logger.error("Error during loading history file: ", e); } }else { try { FileWriter fileWriter = new FileWriter(HISTORY_FILE); JSONObject root = new JSONObject(); root.put("messages", new JSONArray()); fileWriter.write(root.toJSONString()); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { logger.error("Error during creating history file: ", e); } } } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void load() { File configFile = new File(CONFIG_FILE); if (!configFile.exists()) { try { new File(CONFIG_FILE_PATH).mkdir(); FileWriter fileWriter = new FileWriter(CONFIG_FILE); fileWriter.write(new JSONObject().toJSONString()); fileWriter.flush(); fileWriter.close(); saveButtonsConfig(getDefaultButtons()); cachedFramesSettings = getDefaultFramesSettings(); getDefaultFramesSettings().forEach(this::saveFrameSettings); } catch (IOException e) { logger.error(e); } } else { loadConfigFile(); } }
#vulnerable code private void load() { File configFile = new File(CONFIG_FILE); if (!configFile.exists()) { try { new File(CONFIG_FILE_PATH).mkdir(); FileWriter fileWriter = new FileWriter(CONFIG_FILE); fileWriter.write(new JSONObject().toJSONString()); fileWriter.flush(); fileWriter.close(); saveButtonsConfig(getDefaultButtons()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double width = screenSize.getWidth(); double height = screenSize.getHeight(); saveComponentLocation("TaskBarFrame", new Point(500, 500)); saveComponentLocation("MessageFrame", new Point(700, 500)); saveComponentLocation("GamePathChooser", new Point(600, 500)); saveComponentLocation("TestCasesFrame", new Point(900, 500)); saveComponentLocation("SettingsFrame", new Point(600, 600)); saveComponentLocation("HistoryFrame", new Point(600, 600)); saveComponentLocation("NotificationFrame", new Point((int) width / 2, (int) height / 2)); } catch (IOException e) { logger.error(e); } } else { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(CONFIG_FILE)); JSONObject jsonObject = (JSONObject) obj; String gamePath = (String) jsonObject.get("gamePath"); JSONArray buttons = (JSONArray) jsonObject.get("buttons"); Map<String, String> buttonsConfig = new HashMap<>(); if (buttons != null) { for (JSONObject next : (Iterable<JSONObject>) buttons) { buttonsConfig.put((String) next.get("title"), (String) next.get("value")); } } else { buttonsConfig = getDefaultButtons(); } JSONObject taskBarLocation = (JSONObject) jsonObject.get("TaskBarFrame"); Point taskBarPoint = new Point( Integer.valueOf(String.valueOf(taskBarLocation.get("x"))), Integer.valueOf(String.valueOf(taskBarLocation.get("y")))); JSONObject messageLocation = (JSONObject) jsonObject.get("MessageFrame"); Point messagePoint = new Point( Integer.valueOf(String.valueOf(messageLocation.get("x"))), Integer.valueOf(String.valueOf(messageLocation.get("y")))); JSONObject gamePathLocation = (JSONObject) jsonObject.get("GamePathChooser"); Point gamePathPoint = new Point( Integer.valueOf(String.valueOf(gamePathLocation.get("x"))), Integer.valueOf(String.valueOf(gamePathLocation.get("y")))); JSONObject settingsLocation = (JSONObject) jsonObject.get("SettingsFrame"); Point settingsPoint = new Point( Integer.valueOf(String.valueOf(settingsLocation.get("x"))), Integer.valueOf(String.valueOf(settingsLocation.get("y")))); JSONObject historyLocation = (JSONObject) jsonObject.get("HistoryFrame"); Point historyPoint = new Point( Integer.valueOf(String.valueOf(historyLocation.get("x"))), Integer.valueOf(String.valueOf(historyLocation.get("y")))); JSONObject notificationLocation = (JSONObject) jsonObject.get("NotificationFrame"); Point notificationPoint = new Point( Integer.valueOf(String.valueOf(notificationLocation.get("x"))), Integer.valueOf(String.valueOf(notificationLocation.get("y")))); //removing JSONObject testLocation = (JSONObject) jsonObject.get("TestCasesFrame"); Point testPoint = new Point( Integer.valueOf(String.valueOf(testLocation.get("x"))), Integer.valueOf(String.valueOf(testLocation.get("y")))); properties.put("gamePath", gamePath); properties.put("buttons", buttonsConfig); properties.put("TaskBarFrame", taskBarPoint); properties.put("MessageFrame", messagePoint); properties.put("GamePathChooser", gamePathPoint); properties.put("SettingsFrame", settingsPoint); properties.put("HistoryFrame", historyPoint); properties.put("NotificationFrame", notificationPoint); //removing properties.put("TestCasesFrame", testPoint); } catch (Exception e) { logger.error("Error in ConfigManager.load", e); } } } #location 43 #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 public static void signalPublish(String key, String value) throws Exception { long start = System.currentTimeMillis(); final Datum datum = new Datum(); datum.key = key; datum.value = value; if (RaftCore.getDatum(key) == null) { datum.timestamp.set(1L); } else { datum.timestamp.set(RaftCore.getDatum(key).timestamp.incrementAndGet()); } JSONObject json = new JSONObject(); json.put("datum", datum); json.put("source", peers.local()); json.put("increaseTerm", false); onPublish(datum, peers.local(), false); final String content = JSON.toJSONString(json); for (final String server : peers.allServersIncludeMyself()) { if (isLeader(server)) { continue; } final String url = buildURL(server, API_ON_PUB); HttpClient.asyncHttpPostLarge(url, Arrays.asList("key=" + key), content, new AsyncCompletionHandler<Integer>() { @Override public Integer onCompleted(Response response) throws Exception { if (response.getStatusCode() != HttpURLConnection.HTTP_OK) { Loggers.RAFT.warn("RAFT", "failed to publish data to peer, datumId=" + datum.key + ", peer=" + server + ", http code=" + response.getStatusCode()); return 1; } return 0; } @Override public STATE onContentWriteCompleted() { return STATE.CONTINUE; } }); } long end = System.currentTimeMillis(); Loggers.RAFT.info("signalPublish cost " + (end - start) + " ms" + " : " + key); }
#vulnerable code public static void signalPublish(String key, String value) throws Exception { long start = System.currentTimeMillis(); final Datum datum = new Datum(); datum.key = key; datum.value = value; if (RaftCore.getDatum(key) == null) { datum.timestamp.set(1L); } else { datum.timestamp.set(RaftCore.getDatum(key).timestamp.incrementAndGet()); } JSONObject json = new JSONObject(); json.put("datum", datum); json.put("source", peers.local()); onPublish(datum, peers.local()); final String content = JSON.toJSONString(json); for (final String server : peers.allServersIncludeMyself()) { if (isLeader(server)) { continue; } final String url = buildURL(server, API_ON_PUB); HttpClient.asyncHttpPostLarge(url, Arrays.asList("key=" + key), content, new AsyncCompletionHandler<Integer>() { @Override public Integer onCompleted(Response response) throws Exception { if (response.getStatusCode() != HttpURLConnection.HTTP_OK) { Loggers.RAFT.warn("RAFT", "failed to publish data to peer, datumId=" + datum.key + ", peer=" + server + ", http code=" + response.getStatusCode()); return 1; } return 0; } @Override public STATE onContentWriteCompleted() { return STATE.CONTINUE; } }); } long end = System.currentTimeMillis(); Loggers.RAFT.info("signalPublish cost " + (end - start) + " ms" + " : " + key); } #location 18 #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 = 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 private void refreshSrvIfNeed() { try { if (!CollectionUtils.isEmpty(serverList)) { LogUtils.LOG.debug("server list provided by user: " + serverList); return; } if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { return; } List<String> list = getServerListFromEndpoint(); if (CollectionUtils.isEmpty(list)) { throw new Exception("Can not acquire vipserver list"); } if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); } serversFromEndpoint = list; lastSrvRefTime = System.currentTimeMillis(); } catch (Throwable e) { LogUtils.LOG.warn("failed to update server list", e); } }
#vulnerable code private void refreshSrvIfNeed() { try { if (!CollectionUtils.isEmpty(serverList)) { LogUtils.LOG.debug("server list provided by user: " + serverList); return; } if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { return; } List<String> list = getServerListFromEndpoint(); if (list.isEmpty()) { throw new Exception("Can not acquire vipserver list"); } if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); } serversFromEndpoint = list; lastSrvRefTime = System.currentTimeMillis(); } catch (Throwable e) { LogUtils.LOG.warn("failed to update server list", e); } } #location 15 #vulnerability type NULL_DEREFERENCE
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 @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 @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 4 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @RequestMapping("/onAddIP4Dom") public String onAddIP4Dom(HttpServletRequest request) throws Exception { if (Switch.getDisableAddIP()) { throw new AccessControlException("Adding IP for dom is forbidden now."); } String clientIP = WebUtils.required(request, "clientIP"); long term = Long.parseLong(WebUtils.required(request, "term")); if (!RaftCore.isLeader(clientIP)) { Loggers.RAFT.warn("peer(" + JSON.toJSONString(clientIP) + ") tried to publish " + "data but wasn't leader, leader: " + JSON.toJSONString(RaftCore.getLeader())); throw new IllegalStateException("peer(" + clientIP + ") tried to publish " + "data but wasn't leader"); } if (term < RaftCore.getPeerSet().local().term.get()) { Loggers.RAFT.warn("out of date publish, pub-term: " + JSON.toJSONString(clientIP) + ", cur-term: " + JSON.toJSONString(RaftCore.getPeerSet().local())); throw new IllegalStateException("out of date publish, pub-term:" + term + ", cur-term: " + RaftCore.getPeerSet().local().term.get()); } RaftCore.getPeerSet().local().resetLeaderDue(); final String dom = WebUtils.required(request, "dom"); if (domainsManager.getDomain(dom) == null) { throw new IllegalStateException("dom doesn't exist: " + dom); } boolean updateOnly = Boolean.parseBoolean(WebUtils.optional(request, "updateOnly", Boolean.FALSE.toString())); String ipListString = WebUtils.required(request, "ipList"); List<IpAddress> newIPs = new ArrayList<>(); List<String> ipList; 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(",")); for (String ip : ipList) { IpAddress ipAddr = IpAddress.fromJSON(ip); newIPs.add(ipAddr); } } if (CollectionUtils.isEmpty(newIPs)) { throw new IllegalArgumentException("Empty ip list"); } if (updateOnly) { //make sure every IP is in the dom, otherwise refuse update List<IpAddress> oldIPs = domainsManager.getDomain(dom).allIPs(); Collection diff = CollectionUtils.subtract(newIPs, oldIPs); if (diff.size() != 0) { throw new IllegalArgumentException("these IPs are not present: " + Arrays.toString(diff.toArray()) + ", if you want to add them, remove updateOnly flag"); } } domainsManager.easyAddIP4Dom(dom, newIPs, term); return "ok"; }
#vulnerable code @RequestMapping("/onAddIP4Dom") public String onAddIP4Dom(HttpServletRequest request) throws Exception { if (Switch.getDisableAddIP()) { throw new AccessControlException("Adding IP for dom is forbidden now."); } String clientIP = WebUtils.required(request, "clientIP"); long term = Long.parseLong(WebUtils.required(request, "term")); if (!RaftCore.isLeader(clientIP)) { Loggers.RAFT.warn("peer(" + JSON.toJSONString(clientIP) + ") tried to publish " + "data but wasn't leader, leader: " + JSON.toJSONString(RaftCore.getLeader())); throw new IllegalStateException("peer(" + clientIP + ") tried to publish " + "data but wasn't leader"); } if (term < RaftCore.getPeerSet().local().term.get()) { Loggers.RAFT.warn("out of date publish, pub-term: " + JSON.toJSONString(clientIP) + ", cur-term: " + JSON.toJSONString(RaftCore.getPeerSet().local())); throw new IllegalStateException("out of date publish, pub-term:" + term + ", cur-term: " + RaftCore.getPeerSet().local().term.get()); } RaftCore.getPeerSet().local().resetLeaderDue(); final String dom = WebUtils.required(request, "dom"); if (domainsManager.getDomain(dom) == null) { throw new IllegalStateException("dom doesn't exist: " + dom); } boolean updateOnly = Boolean.parseBoolean(WebUtils.optional(request, "updateOnly", Boolean.FALSE.toString())); String ipListString = WebUtils.required(request, "ipList"); List<IpAddress> newIPs = new ArrayList<>(); List<String> ipList; 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(",")); for (String ip : ipList) { IpAddress ipAddr = IpAddress.fromJSON(ip); newIPs.add(ipAddr); } } long timestamp = Long.parseLong(WebUtils.required(request, "timestamp")); if (CollectionUtils.isEmpty(newIPs)) { throw new IllegalArgumentException("Empty ip list"); } if (updateOnly) { //make sure every IP is in the dom, otherwise refuse update List<IpAddress> oldIPs = domainsManager.getDomain(dom).allIPs(); Collection diff = CollectionUtils.subtract(newIPs, oldIPs); if (diff.size() != 0) { throw new IllegalArgumentException("these IPs are not present: " + Arrays.toString(diff.toArray()) + ", if you want to add them, remove updateOnly flag"); } } domainsManager.easyAddIP4Dom(dom, newIPs, timestamp, term); return "ok"; } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
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 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 dom. 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); }
#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 dom. 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)); addOrReplaceService(service); 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 26 #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()); 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 static List<String> readClusterConf() throws IOException { List<String> instanceList = new ArrayList<String>(); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(new File(CLUSTER_CONF_FILE_PATH)), UTF_8); List<String> lines = IoUtils.readLines(reader); String comment = "#"; for (String line : lines) { String instance = line.trim(); if (instance.startsWith(comment)) { // # it is ip continue; } if (instance.contains(comment)) { // 192.168.71.52:8848 # Instance A instance = instance.substring(0, instance.indexOf(comment)); instance = instance.trim(); } instanceList.add(instance); } return instanceList; } finally { if (reader != null) { reader.close(); } } }
#vulnerable code public static List<String> readClusterConf() throws IOException { List<String> instanceList = new ArrayList<String>(); List<String> lines = IoUtils.readLines( new InputStreamReader(new FileInputStream(new File(CLUSTER_CONF_FILE_PATH)), UTF_8)); String comment = "#"; for (String line : lines) { String instance = line.trim(); if (instance.startsWith(comment)) { // # it is ip continue; } if (instance.contains(comment)) { // 192.168.71.52:8848 # Instance A instance = instance.substring(0, instance.indexOf(comment)); instance = instance.trim(); } instanceList.add(instance); } return instanceList; } #location 3 #vulnerability type RESOURCE_LEAK
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 23 #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 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 @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 3 #vulnerability type CHECKERS_PRINTF_ARGS
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 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 12 #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 14 #vulnerability type RESOURCE_LEAK
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 @Override public Instance selectOneHealthyInstance(String serviceName, String groupName, List<String> clusters, boolean subscribe) throws NacosException { if (subscribe) { return Balancer.RandomByWeight.selectHost( hostReactor.getServiceInfo(NamingUtils.getGroupedName(serviceName, groupName), StringUtils.join(clusters, ","))); } else { return Balancer.RandomByWeight.selectHost( hostReactor.getServiceInfoDirectlyFromServer(NamingUtils.getGroupedName(serviceName, groupName), StringUtils.join(clusters, ","))); } }
#vulnerable code @Override public Instance selectOneHealthyInstance(String serviceName, String groupName, List<String> clusters, boolean subscribe) throws NacosException { if (subscribe) { return Balancer.RandomByWeight.selectHost( hostReactor.getServiceInfo(groupName + Constants.SERVICE_INFO_SPLITER + serviceName, StringUtils.join(clusters, ","))); } else { return Balancer.RandomByWeight.selectHost( hostReactor.getServiceInfoDirectlyFromServer(groupName + Constants.SERVICE_INFO_SPLITER + serviceName, StringUtils.join(clusters, ","))); } } #location 5 #vulnerability type NULL_DEREFERENCE
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 @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 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void initNamespace(Properties properties) { namespace = ParamUtil.parseNamespace(properties); properties.put(PropertyKeyConst.NAMESPACE, namespace); }
#vulnerable code private void initNamespace(Properties properties) { String namespaceTmp = null; String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, System.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, String.valueOf(Constants.DEFAULT_USE_CLOUD_NAMESPACE_PARSING))); if (Boolean.parseBoolean(isUseCloudNamespaceParsing)) { namespaceTmp = TemplateUtils.stringBlankAndThenExecute(namespaceTmp, new Callable<String>() { @Override public String call() { return TenantUtil.getUserTenantForAcm(); } }); namespaceTmp = TemplateUtils.stringBlankAndThenExecute(namespaceTmp, new Callable<String>() { @Override public String call() { String namespace = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE); return StringUtils.isNotBlank(namespace) ? namespace : EMPTY; } }); } if (StringUtils.isBlank(namespaceTmp)) { namespaceTmp = properties.getProperty(PropertyKeyConst.NAMESPACE); } namespace = StringUtils.isNotBlank(namespaceTmp) ? namespaceTmp.trim() : EMPTY; properties.put(PropertyKeyConst.NAMESPACE, namespace); } #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 evolutionVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf")); reader.setCompatibilityMode(CompatibilityMode.EVOLUTION); 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().getFirst("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType t = it.next(); assertEquals("905-666-1234", t.getValue()); Set<TelephoneTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().getFirst("X-COUCHDB-UUID")); t = it.next(); assertEquals("905-555-1234", t.getValue()); 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().getFirst("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().getFirst("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.getExtendedType("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.getExtendedType("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().getFirst("X-COUCHDB-UUID")); assertFalse(it.hasNext()); it = vcard.getExtendedType("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.getExtendedType("X-EVOLUTION-SPOUSE").iterator(); t = it.next(); assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName()); assertEquals("Maria", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedType("X-EVOLUTION-MANAGER").iterator(); t = it.next(); assertEquals("X-EVOLUTION-MANAGER", t.getTypeName()); assertEquals("Big Blue", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedType("X-EVOLUTION-ASSISTANT").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName()); assertEquals("Little Red", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedType("X-EVOLUTION-ANNIVERSARY").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName()); assertEquals("1980-03-22", t.getValue()); assertFalse(it.hasNext()); } }
#vulnerable code @Test public void evolutionVCard() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf"))); reader.setCompatibilityMode(CompatibilityMode.EVOLUTION); 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().getFirst("X-COUCHDB-UUID")); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType t = it.next(); assertEquals("905-666-1234", t.getValue()); Set<TelephoneTypeParameter> types = t.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().getFirst("X-COUCHDB-UUID")); t = it.next(); assertEquals("905-555-1234", t.getValue()); 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().getFirst("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().getFirst("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.getExtendedType("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.getExtendedType("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().getFirst("X-COUCHDB-UUID")); assertFalse(it.hasNext()); it = vcard.getExtendedType("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.getExtendedType("X-EVOLUTION-SPOUSE").iterator(); t = it.next(); assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName()); assertEquals("Maria", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedType("X-EVOLUTION-MANAGER").iterator(); t = it.next(); assertEquals("X-EVOLUTION-MANAGER", t.getTypeName()); assertEquals("Big Blue", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedType("X-EVOLUTION-ASSISTANT").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName()); assertEquals("Little Red", t.getValue()); assertFalse(it.hasNext()); it = vcard.getExtendedType("X-EVOLUTION-ANNIVERSARY").iterator(); t = it.next(); assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName()); assertEquals("1980-03-22", t.getValue()); assertFalse(it.hasNext()); } } #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 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("LABEL", "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.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\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.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\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 adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); adr.getSubTypes().put("LANGUAGE", "FR"); adr.getSubTypes().put("LANGUAGE", "es"); adr.getSubTypes().put("X-PARKING", "10"); vcard.addAddress(adr); //2.1 StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1); vcw.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;X-PARKING=10: ;;;;;;\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); vcw.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;X-PARKING=10: ;;;;;;\r\n"); sb.append("END: vcard\r\n"); expected = sb.toString(); assertEquals(expected, actual); } #location 29 #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 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(); }
#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")); EmailType email = new EmailType("[email protected]"); email.addType(EmailTypeParameter.HOME); vcard.addEmail(email); TelephoneType tel = new TelephoneType("+1 555-555-1234"); tel.addType(TelephoneTypeParameter.CELL); vcard.addTelephoneNumber(tel); tel = new TelephoneType("+1 555-555-9876"); tel.addType(TelephoneTypeParameter.HOME); vcard.addTelephoneNumber(tel); UrlType url = new UrlType("http://mikeangstadt.name"); url.setType("home"); vcard.addUrl(url); url = new UrlType("http://code.google.com/p/ez-vcard"); url.setType("work"); 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)); NicknameType nickname = new NicknameType(); nickname.addValue("Mike"); vcard.setNickname(nickname); vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York")); File profile = new File("portrait.jpg"); byte data[] = new byte[(int) profile.length()]; InputStream in = new FileInputStream(profile); in.read(data); in.close(); PhotoType photo = new PhotoType(data, ImageTypeParameter.JPEG); vcard.addPhoto(photo); //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())); vcard.setVersion(VCardVersion.V3_0); vcard.write(new File("mike-angstadt.vcf")); } #location 63 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() throws Exception { VCard vcard = new VCard(); StructuredNameType n = new StructuredNameType(); n.setGiven("Michael"); n.setFamily("Angstadt"); vcard.setStructuredName(n); FormattedNameType fn = new FormattedNameType("Michael Angstadt"); vcard.setFormattedName(fn); PhotoType photo = new PhotoType(); photo.setUrl("http://example.com/image.jpg"); vcard.getPhotos().add(photo); StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1); vcw.write(vcard); System.out.println(sw.toString()); }
#vulnerable code @Test public void test() throws Exception { VCard vcard = new VCard(); StructuredNameType n = new StructuredNameType(); n.setGiven("Michael"); n.setFamily("Angstadt"); vcard.setStructuredName(n); FormattedNameType fn = new FormattedNameType("Michael Angstadt"); vcard.setFormattedName(fn); PhotoType photo = new PhotoType(); photo.setUrl("http://example.com/image.jpg"); vcard.getPhotos().add(photo); VCardWriter vcw = new VCardWriter(new OutputStreamWriter(System.out)); vcw.write(vcard); } #location 17 #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 public T find(V value) { checkInit(); for (T obj : preDefined) { if (matches(obj, value)) { return obj; } } return null; }
#vulnerable code public T find(V value) { return find(value, false, false); } #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 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("LABEL", "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.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\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.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\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 adr = new AddressType(); adr.getSubTypes().put("X-DOORMAN", "true"); adr.getSubTypes().put("LANGUAGE", "FR"); adr.getSubTypes().put("LANGUAGE", "es"); adr.getSubTypes().put("X-PARKING", "10"); vcard.addAddress(adr); //2.1 StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1); vcw.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;X-PARKING=10: ;;;;;;\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); vcw.setAddGenerator(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;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n"); sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;X-PARKING=10: ;;;;;;\r\n"); sb.append("END: vcard\r\n"); expected = sb.toString(); assertEquals(expected, actual); } #location 29 #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.getValue()); 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.getValue()); 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.getValue()); 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.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("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.getExtendedType("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.getExtendedType("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedType("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20120801", f.getValue()); f = vcard.getExtendedType("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedType("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.getExtendedType("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("TheManagerName", f.getValue()); f = vcard.getExtendedType("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("TheAssistantName", f.getValue()); f = vcard.getExtendedType("X-MS-SPOUSE").get(0); assertEquals("X-MS-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); } }
#vulnerable code @Test public void outlook2007VCard() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(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.getValue()); 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.getValue()); 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.getValue()); 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.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("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.getExtendedType("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.getExtendedType("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedType("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20120801", f.getValue()); f = vcard.getExtendedType("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedType("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.getExtendedType("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("TheManagerName", f.getValue()); f = vcard.getExtendedType("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("TheAssistantName", f.getValue()); f = vcard.getExtendedType("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 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 labels() throws Exception { VCard vcard = new VCard(); //address with label AddressType adr = new AddressType(); adr.setStreetAddress("123 Main St."); adr.setLocality("Austin"); adr.setRegion("TX"); adr.setPostalCode("12345"); adr.setLabel("123 Main St.\r\nAustin, TX 12345"); adr.addType(AddressTypeParameter.HOME); vcard.addAddress(adr); //address without label adr = new AddressType(); adr.setStreetAddress("222 Broadway"); adr.setLocality("New York"); adr.setRegion("NY"); adr.setPostalCode("99999"); adr.addType(AddressTypeParameter.WORK); vcard.addAddress(adr); //orphaned label LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111"); label.addType(AddressTypeParameter.PARCEL); vcard.addOrphanedLabel(label); //3.0 //LABEL types should be used StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, 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:3.0\r\n"); sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n"); sb.append("END:VCARD\r\n"); String expected = sb.toString(); assertEquals(expected, actual); //4.0 //LABEL parameters should be used sw = new StringWriter(); vcw = new VCardWriter(sw, VCardVersion.V4_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:4.0\r\n"); sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("END:VCARD\r\n"); expected = sb.toString(); assertEquals(expected, actual); }
#vulnerable code @Test public void labels() throws Exception { VCard vcard = new VCard(); //address with label AddressType adr = new AddressType(); adr.setStreetAddress("123 Main St."); adr.setLocality("Austin"); adr.setRegion("TX"); adr.setPostalCode("12345"); adr.setLabel("123 Main St.\r\nAustin, TX 12345"); adr.addType(AddressTypeParameter.HOME); vcard.addAddress(adr); //address without label adr = new AddressType(); adr.setStreetAddress("222 Broadway"); adr.setLocality("New York"); adr.setRegion("NY"); adr.setPostalCode("99999"); adr.addType(AddressTypeParameter.WORK); vcard.addAddress(adr); //orphaned label LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111"); label.addType(AddressTypeParameter.PARCEL); vcard.addOrphanedLabel(label); //3.0 //LABEL types should be used StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null); vcw.setAddProdId(false); vcw.write(vcard); String actual = sw.toString(); StringBuilder sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:3.0\r\n"); sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n"); sb.append("END:VCARD\r\n"); String expected = sb.toString(); assertEquals(expected, actual); //4.0 //LABEL parameters should be used sw = new StringWriter(); vcw = new VCardWriter(sw, VCardVersion.V4_0, null); vcw.setAddProdId(false); vcw.write(vcard); actual = sw.toString(); sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:4.0\r\n"); sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("END:VCARD\r\n"); expected = sb.toString(); assertEquals(expected, actual); } #location 34 #vulnerability type RESOURCE_LEAK
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 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 gmailSingle() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("gmail-single.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Greg Dartmouth", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Dartmouth", f.getFamily()); assertEquals("Greg", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertTrue(f.getPrefixes().isEmpty()); assertTrue(f.getSuffixes().isEmpty()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); 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(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("item1", f.getGroup()); assertEquals("555 555 2222", f.getText()); types = f.getTypes(); assertTrue(types.isEmpty()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("123 Home St" + NEWLINE + "Home City, HM 12345", 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)); f = it.next(); assertEquals("item2", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("321 Custom St", f.getStreetAddress()); assertEquals("Custom City", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("98765", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertTrue(types.isEmpty()); assertFalse(it.hasNext()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheCompany"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheJobTitle", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1960); c.set(Calendar.MONTH, Calendar.SEPTEMBER); c.set(Calendar.DAY_OF_MONTH, 10); assertEquals(c.getTime(), f.getDate()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://TheProfile.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertTrue(types.isEmpty()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is GMail's note field." + NEWLINE + "It should be added as a NOTE type." + NEWLINE + "ACustomField: CustomField", f.getValue()); assertFalse(it.hasNext()); } //extended types { assertEquals(12, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Grregg", f.getValue()); f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dart-mowth", f.getValue()); f = vcard.getExtendedProperties("X-ICQ").get(0); assertEquals("X-ICQ", f.getTypeName()); assertEquals("123456789", f.getValue()); Iterator<RawType> abLabelIt = vcard.getExtendedProperties("X-ABLABEL").iterator(); { f = abLabelIt.next(); assertEquals("item1", f.getGroup()); assertEquals("GRAND_CENTRAL", f.getValue()); f = abLabelIt.next(); assertEquals("item2", f.getGroup()); assertEquals("CustomAdrType", f.getValue()); f = abLabelIt.next(); assertEquals("item3", f.getGroup()); assertEquals("PROFILE", f.getValue()); f = abLabelIt.next(); assertEquals("item4", f.getGroup()); assertEquals("_$!<Anniversary>!$_", f.getValue()); f = abLabelIt.next(); assertEquals("item5", f.getGroup()); assertEquals("_$!<Spouse>!$_", f.getValue()); f = abLabelIt.next(); assertEquals("item6", f.getGroup()); assertEquals("CustomRelationship", f.getValue()); assertFalse(abLabelIt.hasNext()); } f = vcard.getExtendedProperties("X-ABDATE").get(0); assertEquals("item4", f.getGroup()); assertEquals("X-ABDATE", f.getTypeName()); assertEquals("1970-06-02", f.getValue()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); assertEquals("item5", f.getGroup()); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("MySpouse", f.getValue()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(1); assertEquals("item6", f.getGroup()); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("MyCustom", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void gmailSingle() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("gmail-single.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Greg Dartmouth", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Dartmouth", f.getFamily()); assertEquals("Greg", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertTrue(f.getPrefixes().isEmpty()); assertTrue(f.getSuffixes().isEmpty()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); 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(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("item1", f.getGroup()); assertEquals("555 555 2222", f.getText()); types = f.getTypes(); assertTrue(types.isEmpty()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("123 Home St" + NEWLINE + "Home City, HM 12345", 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)); f = it.next(); assertEquals("item2", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("321 Custom St", f.getStreetAddress()); assertEquals("Custom City", f.getLocality()); assertEquals("TX", f.getRegion()); assertEquals("98765", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertTrue(types.isEmpty()); assertFalse(it.hasNext()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheCompany"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheJobTitle", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1960); c.set(Calendar.MONTH, Calendar.SEPTEMBER); c.set(Calendar.DAY_OF_MONTH, 10); assertEquals(c.getTime(), f.getDate()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://TheProfile.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertTrue(types.isEmpty()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is GMail's note field." + NEWLINE + "It should be added as a NOTE type." + NEWLINE + "ACustomField: CustomField", f.getValue()); assertFalse(it.hasNext()); } //extended types { assertEquals(12, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Grregg", f.getValue()); f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dart-mowth", f.getValue()); f = vcard.getExtendedProperties("X-ICQ").get(0); assertEquals("X-ICQ", f.getTypeName()); assertEquals("123456789", f.getValue()); Iterator<RawType> abLabelIt = vcard.getExtendedProperties("X-ABLABEL").iterator(); { f = abLabelIt.next(); assertEquals("item1", f.getGroup()); assertEquals("GRAND_CENTRAL", f.getValue()); f = abLabelIt.next(); assertEquals("item2", f.getGroup()); assertEquals("CustomAdrType", f.getValue()); f = abLabelIt.next(); assertEquals("item3", f.getGroup()); assertEquals("PROFILE", f.getValue()); f = abLabelIt.next(); assertEquals("item4", f.getGroup()); assertEquals("_$!<Anniversary>!$_", f.getValue()); f = abLabelIt.next(); assertEquals("item5", f.getGroup()); assertEquals("_$!<Spouse>!$_", f.getValue()); f = abLabelIt.next(); assertEquals("item6", f.getGroup()); assertEquals("CustomRelationship", f.getValue()); assertFalse(abLabelIt.hasNext()); } f = vcard.getExtendedProperties("X-ABDATE").get(0); assertEquals("item4", f.getGroup()); assertEquals("X-ABDATE", f.getTypeName()); assertEquals("1970-06-02", f.getValue()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); assertEquals("item5", f.getGroup()); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("MySpouse", f.getValue()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(1); assertEquals("item6", f.getGroup()); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("MyCustom", 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 doMarshalValue(StringBuilder sb, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) { if (url != null) { sb.append(url); } else if (vcard != null) { throw new EmbeddedVCardException(vcard); } else { throw new SkipMeException("Property has neither a URL nor an embedded vCard."); } }
#vulnerable code @Override protected void doMarshalValue(StringBuilder sb, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) { //VCardWriter handles 2.1 AGENT types that have an embedded vCard. //this method will not be called for these instances if (url != null) { sb.append(url); } else { StringWriter sw = new StringWriter(); VCardWriter writer = new VCardWriter(sw, version, null, "\n"); writer.setCompatibilityMode(compatibilityMode); writer.setAddGenerator(false); try { writer.write(vcard); } catch (IOException e) { //never thrown because we're writing to a string } String str = sw.toString(); for (String w : writer.getWarnings()) { warnings.add("AGENT marshal warning: " + w); } sb.append(VCardStringUtils.escapeText(str)); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void iPhoneVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//iOS 5.0.1//EN", 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()); } //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()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); 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(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); 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)); f = it.next(); assertEquals("905-777-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("905-888-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getText()); assertEquals("item2", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item3", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item4", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item5", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(32531, f.getData().length); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<AssistantPhone>!$_", f.getValue()); f = vcard.getExtendedProperties("X-ABADR").get(0); assertEquals("item3", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); f = vcard.getExtendedProperties("X-ABADR").get(1); assertEquals("item4", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue()); f = vcard.getExtendedProperties("X-ABLABEL").get(1); assertEquals("item5", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void iPhoneVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//iOS 5.0.1//EN", 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()); } //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()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); 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(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); 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)); f = it.next(); assertEquals("905-777-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("905-888-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getText()); assertEquals("item2", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item3", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item4", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item5", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(32531, f.getData().length); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<AssistantPhone>!$_", f.getValue()); f = vcard.getExtendedProperties("X-ABADR").get(0); assertEquals("item3", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); f = vcard.getExtendedProperties("X-ABADR").get(1); assertEquals("item4", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue()); f = vcard.getExtendedProperties("X-ABLABEL").get(1); assertEquals("item5", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", 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 labels() throws Exception { VCard vcard = new VCard(); //address with label AddressType adr = new AddressType(); adr.setStreetAddress("123 Main St."); adr.setLocality("Austin"); adr.setRegion("TX"); adr.setPostalCode("12345"); adr.setLabel("123 Main St.\r\nAustin, TX 12345"); adr.addType(AddressTypeParameter.HOME); vcard.addAddress(adr); //address without label adr = new AddressType(); adr.setStreetAddress("222 Broadway"); adr.setLocality("New York"); adr.setRegion("NY"); adr.setPostalCode("99999"); adr.addType(AddressTypeParameter.WORK); vcard.addAddress(adr); //orphaned label LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111"); label.addType(AddressTypeParameter.PARCEL); vcard.addOrphanedLabel(label); //3.0 //LABEL types should be used StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, 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:3.0\r\n"); sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n"); sb.append("END:VCARD\r\n"); String expected = sb.toString(); assertEquals(expected, actual); //4.0 //LABEL parameters should be used sw = new StringWriter(); vcw = new VCardWriter(sw, VCardVersion.V4_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:4.0\r\n"); sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("END:VCARD\r\n"); expected = sb.toString(); assertEquals(expected, actual); }
#vulnerable code @Test public void labels() throws Exception { VCard vcard = new VCard(); //address with label AddressType adr = new AddressType(); adr.setStreetAddress("123 Main St."); adr.setLocality("Austin"); adr.setRegion("TX"); adr.setPostalCode("12345"); adr.setLabel("123 Main St.\r\nAustin, TX 12345"); adr.addType(AddressTypeParameter.HOME); vcard.addAddress(adr); //address without label adr = new AddressType(); adr.setStreetAddress("222 Broadway"); adr.setLocality("New York"); adr.setRegion("NY"); adr.setPostalCode("99999"); adr.addType(AddressTypeParameter.WORK); vcard.addAddress(adr); //orphaned label LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111"); label.addType(AddressTypeParameter.PARCEL); vcard.addOrphanedLabel(label); //3.0 //LABEL types should be used StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null); vcw.setAddProdId(false); vcw.write(vcard); String actual = sw.toString(); StringBuilder sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:3.0\r\n"); sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n"); sb.append("END:VCARD\r\n"); String expected = sb.toString(); assertEquals(expected, actual); //4.0 //LABEL parameters should be used sw = new StringWriter(); vcw = new VCardWriter(sw, VCardVersion.V4_0, null); vcw.setAddProdId(false); vcw.write(vcard); actual = sw.toString(); sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); sb.append("VERSION:4.0\r\n"); sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n"); sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n"); sb.append("END:VCARD\r\n"); expected = sb.toString(); assertEquals(expected, actual); } #location 34 #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 iPhoneVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf")); reader.setCompatibilityMode(CompatibilityMode.I_PHONE); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//iOS 5.0.1//EN", 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()); } //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()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); 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(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("905-666-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("905-777-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("905-888-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getValue()); assertEquals("item2", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item3", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item4", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item5", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(32531, f.getData().length); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<AssistantPhone>!$_", f.getValue()); f = vcard.getExtendedType("X-ABADR").get(0); assertEquals("item3", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); f = vcard.getExtendedType("X-ABADR").get(1); assertEquals("item4", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue()); f = vcard.getExtendedType("X-ABLABEL").get(1); assertEquals("item5", f.getGroup()); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); } }
#vulnerable code @Test public void iPhoneVCard() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf"))); reader.setCompatibilityMode(CompatibilityMode.I_PHONE); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//iOS 5.0.1//EN", 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()); } //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()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(EmailTypeParameter.PREF)); 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(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("905-666-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("905-777-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("905-888-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getValue()); assertEquals("item2", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item3", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item4", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item5", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(32531, f.getData().length); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedType("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<AssistantPhone>!$_", f.getValue()); f = vcard.getExtendedType("X-ABADR").get(0); assertEquals("item3", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); f = vcard.getExtendedType("X-ABADR").get(1); assertEquals("item4", f.getGroup()); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue()); f = vcard.getExtendedType("X-ABLABEL").get(1); assertEquals("item5", f.getGroup()); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<HomePage>!$_", 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 macAddressBookVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.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()); 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()); } //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)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("905-777-1234", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("905-666-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); f = it.next(); assertEquals("905-555-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-888-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getText()); assertEquals("item1", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item2", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item3", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.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()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item4", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(null, f.getContentType()); assertEquals(18242, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(9, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Jon", f.getValue()); f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dow", f.getValue()); f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("AssistantPhone", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedProperties("X-ABADR").get(0); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedProperties("X-ABADR").get(1); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue()); assertEquals("item3", f.getGroup()); f = vcard.getExtendedProperties("X-ABLABEL").get(1); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); assertEquals("item4", f.getGroup()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item5", f.getGroup()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); f = vcard.getExtendedProperties("X-ABLABEL").get(2); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("Spouse", f.getValue()); assertEquals("item5", f.getGroup()); f = vcard.getExtendedProperties("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void macAddressBookVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.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()); 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()); } //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)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("905-777-1234", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("905-666-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); f = it.next(); assertEquals("905-555-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-888-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getText()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getText()); assertEquals("item1", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item2", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item3", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.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()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item4", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(null, f.getContentType()); assertEquals(18242, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(9, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Jon", f.getValue()); f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dow", f.getValue()); f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("AssistantPhone", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedProperties("X-ABADR").get(0); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedProperties("X-ABADR").get(1); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue()); assertEquals("item3", f.getGroup()); f = vcard.getExtendedProperties("X-ABLABEL").get(1); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); assertEquals("item4", f.getGroup()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item5", f.getGroup()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); f = vcard.getExtendedProperties("X-ABLABEL").get(2); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("Spouse", f.getValue()); assertEquals("item5", f.getGroup()); f = vcard.getExtendedProperties("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", 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 macAddressBookVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.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()); 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()); } //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)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("905-777-1234", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("905-666-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); f = it.next(); assertEquals("905-555-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-888-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getValue()); assertEquals("item1", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item2", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item3", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.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()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item4", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(null, f.getContentType()); assertEquals(18242, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(9, 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-ABLABEL").get(0); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("AssistantPhone", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedType("X-ABADR").get(0); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedType("X-ABADR").get(1); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue()); assertEquals("item3", f.getGroup()); f = vcard.getExtendedType("X-ABLABEL").get(1); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); assertEquals("item4", f.getGroup()); f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item5", f.getGroup()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); f = vcard.getExtendedType("X-ABLABEL").get(2); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("Spouse", f.getValue()); assertEquals("item5", f.getGroup()); f = vcard.getExtendedType("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", f.getValue()); } }
#vulnerable code @Test public void macAddressBookVCard() throws Exception { VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.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()); 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()); } //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)); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("905-777-1234", f.getValue()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("905-666-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); f = it.next(); assertEquals("905-555-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-888-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-999-1234", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); f = it.next(); assertEquals("905-111-1234", f.getValue()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.PAGER)); f = it.next(); assertEquals("905-222-1234", f.getValue()); assertEquals("item1", f.getGroup()); types = f.getTypes(); assertEquals(0, types.size()); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item2", f.getGroup()); 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()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); f = it.next(); assertEquals("item3", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals(null, f.getRegion()); assertEquals("12345", f.getPostalCode()); assertEquals("USA", f.getCountry()); types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(AddressTypeParameter.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()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item4", f.getGroup()); assertEquals("http://www.ibm.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, 2012); c.set(Calendar.MONTH, Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH, 6); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(null, f.getContentType()); assertEquals(18242, f.getData().length); assertFalse(it.hasNext()); } //extended types { assertEquals(9, 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-ABLABEL").get(0); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("AssistantPhone", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedType("X-ABADR").get(0); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Silicon Alley", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedType("X-ABADR").get(1); assertEquals("X-ABADR", f.getTypeName()); assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue()); assertEquals("item3", f.getGroup()); f = vcard.getExtendedType("X-ABLABEL").get(1); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); assertEquals("item4", f.getGroup()); f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item5", f.getGroup()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); f = vcard.getExtendedType("X-ABLABEL").get(2); assertEquals("X-ABLABEL", f.getTypeName()); assertEquals("Spouse", f.getValue()); assertEquals("item5", f.getGroup()); f = vcard.getExtendedType("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", 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 test() throws Exception { VCard vcard = new VCard(); StructuredNameType n = new StructuredNameType(); n.setGiven("Michael"); n.setFamily("Angstadt"); vcard.setStructuredName(n); FormattedNameType fn = new FormattedNameType("Michael Angstadt"); vcard.setFormattedName(fn); PhotoType photo = new PhotoType(); photo.setUrl("http://example.com/image.jpg"); vcard.getPhotos().add(photo); StringWriter sw = new StringWriter(); VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1); vcw.write(vcard); System.out.println(sw.toString()); }
#vulnerable code @Test public void test() throws Exception { VCard vcard = new VCard(); StructuredNameType n = new StructuredNameType(); n.setGiven("Michael"); n.setFamily("Angstadt"); vcard.setStructuredName(n); FormattedNameType fn = new FormattedNameType("Michael Angstadt"); vcard.setFormattedName(fn); PhotoType photo = new PhotoType(); photo.setUrl("http://example.com/image.jpg"); vcard.getPhotos().add(photo); VCardWriter vcw = new VCardWriter(new OutputStreamWriter(System.out)); vcw.write(vcard); } #location 18 #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")); 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.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-666-1234", f.getText()); 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.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Jon", f.getValue()); f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dow", f.getValue()); f = vcard.getExtendedProperties("X-ABDATE").get(0); assertEquals("X-ABDATE", f.getTypeName()); assertEquals("1975-03-01", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<Anniversary>!$_", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedProperties("X-ABLABEL").get(1); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<Spouse>!$_", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item2", f.getGroup()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
#vulnerable code @Test public void gmailVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf")); 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.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(1, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); f = it.next(); assertEquals("905-666-1234", f.getText()); 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.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); assertEquals("Jon", f.getValue()); f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); assertEquals("Dow", f.getValue()); f = vcard.getExtendedProperties("X-ABDATE").get(0); assertEquals("X-ABDATE", f.getTypeName()); assertEquals("1975-03-01", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<Anniversary>!$_", f.getValue()); assertEquals("item1", f.getGroup()); f = vcard.getExtendedProperties("X-ABLABEL").get(1); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<Spouse>!$_", f.getValue()); assertEquals("item2", f.getGroup()); f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); assertEquals("X-ABRELATEDNAMES", f.getTypeName()); assertEquals("Jenny", f.getValue()); assertEquals("item2", f.getGroup()); } } #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 public List<String> execute(TsLintExecutorConfig config, List<String> files) { if (config == null) { throw new IllegalArgumentException("config"); } else if (files == null) { throw new IllegalArgumentException("files"); } // New up a command that's everything we need except the files to process // We'll use this as our reference for chunking up files, if we need to File tslintOutputFile = this.tempFolder.newFile(); String tslintOutputFilePath = tslintOutputFile.getAbsolutePath(); Command baseCommand = getBaseCommand(config, tslintOutputFilePath); LOG.debug("Using a temporary path for TsLint output: " + tslintOutputFilePath); StringStreamConsumer stdOutConsumer = new StringStreamConsumer(); StringStreamConsumer stdErrConsumer = new StringStreamConsumer(); List<String> toReturn = new ArrayList<String>(); if (config.useTsConfigInsteadOfFileList()) { LOG.debug("Running against a single project JSON file"); // If we're being asked to use a tsconfig.json file, it'll contain // the file list to lint - so don't batch, and just run with it toReturn.add(this.getCommandOutput(baseCommand, stdOutConsumer, stdErrConsumer, tslintOutputFile, config.getTimeoutMs())); } else { int baseCommandLength = baseCommand.toCommandLine().length(); int availableForBatching = MAX_COMMAND_LENGTH - baseCommandLength; List<List<String>> batches = new ArrayList<List<String>>(); List<String> currentBatch = new ArrayList<String>(); batches.add(currentBatch); int currentBatchLength = 0; for (int i = 0; i < files.size(); i++) { String nextPath = this.preparePath(files.get(i).trim()); // +1 for the space we'll be adding between filenames if (currentBatchLength + nextPath.length() + 1 > availableForBatching) { // Too long to add to this batch, create new currentBatch = new ArrayList<String>(); currentBatchLength = 0; batches.add(currentBatch); } currentBatch.add(nextPath); currentBatchLength += nextPath.length() + 1; } LOG.debug("Split " + files.size() + " files into " + batches.size() + " batches for processing"); for (int i = 0; i < batches.size(); i++) { StringBuilder outputBuilder = new StringBuilder(); List<String> thisBatch = batches.get(i); Command thisCommand = getBaseCommand(config, tslintOutputFilePath); for (int fileIndex = 0; fileIndex < thisBatch.size(); fileIndex++) { thisCommand.addArgument(thisBatch.get(fileIndex)); } 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 toReturn.add(this.getCommandOutput(thisCommand, stdOutConsumer, stdErrConsumer, tslintOutputFile, config.getTimeoutMs() * thisBatch.size())); } } return toReturn; }
#vulnerable code public List<String> execute(TsLintExecutorConfig config, List<String> files) { if (config == null) { throw new IllegalArgumentException("config"); } if (files == null) { throw new IllegalArgumentException("files"); } // New up a command that's everything we need except the files to process // We'll use this as our reference for chunking up files File tslintOutputFile = this.tempFolder.newFile(); String tslintOutputFilePath = tslintOutputFile.getAbsolutePath(); LOG.debug("Using a temporary path for TsLint output: " + tslintOutputFilePath); int baseCommandLength = getBaseCommand(config, tslintOutputFilePath).toCommandLine().length(); int availableForBatching = MAX_COMMAND_LENGTH - baseCommandLength; List<List<String>> batches = new ArrayList<List<String>>(); List<String> currentBatch = new ArrayList<String>(); batches.add(currentBatch); int currentBatchLength = 0; for (int i = 0; i < files.size(); i++) { String nextPath = this.preparePath(files.get(i).trim()); // +1 for the space we'll be adding between filenames if (currentBatchLength + nextPath.length() + 1 > availableForBatching) { // Too long to add to this batch, create new currentBatch = new ArrayList<String>(); currentBatchLength = 0; batches.add(currentBatch); } currentBatch.add(nextPath); currentBatchLength += nextPath.length() + 1; } LOG.debug("Split " + files.size() + " files into " + batches.size() + " batches for processing"); StringStreamConsumer stdOutConsumer = new StringStreamConsumer(); StringStreamConsumer stdErrConsumer = new StringStreamConsumer(); List<String> toReturn = new ArrayList<String>(); for (int i = 0; i < batches.size(); i++) { StringBuilder outputBuilder = new StringBuilder(); List<String> thisBatch = batches.get(i); Command thisCommand = getBaseCommand(config, tslintOutputFilePath); for (int fileIndex = 0; fileIndex < thisBatch.size(); fileIndex++) { thisCommand.addArgument(thisBatch.get(fileIndex)); } 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, config.getTimeoutMs() * thisBatch.size()); try { BufferedReader reader = this.getBufferedReaderForFile(tslintOutputFile); String str; while ((str = reader.readLine()) != null) { outputBuilder.append(str); } reader.close(); toReturn.add(outputBuilder.toString()); } catch (IOException ex) { LOG.error("Failed to re-read TsLint output from " + tslintOutputFilePath, ex); } } return toReturn; } #location 76 #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 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 copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException { Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath)); File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName()); LOG.info("Copying remote file " + source + " to local file " + destination); InputStream inputStream = getInputStream(remoteSourceRelativePath); FileOutputStream fileOutputStream = new FileOutputStream(destination); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); // Use copyLarge (over 2GB) try { IOUtils.copyLarge(inputStream, bufferedOutputStream); bufferedOutputStream.flush(); fileOutputStream.flush(); } finally { inputStream.close(); bufferedOutputStream.close(); fileOutputStream.close(); } }
#vulnerable code @Override public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException { Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath)); File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName()); LOG.info("Copying remote file " + source + " to local file " + destination); InputStream inputStream = getInputStream(remoteSourceRelativePath); // Use copyLarge (over 2GB) try { IOUtils.copyLarge(inputStream, new BufferedOutputStream(new FileOutputStream(destination))); } finally { inputStream.close(); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int decompress(byte[] src, int srcOffset, int srcLength, byte[] dst, int dstOff) { if (srcLength - srcOffset == 0) { return 0; } try { ByteArrayInputStream bytesIn = new ByteArrayInputStream(src, srcOffset, srcLength); GZIPInputStream gzip = new GZIPInputStream(bytesIn); int curOff = dstOff; while (curOff < dst.length - dstOff) { int amtRead = gzip.read(dst, curOff, dst.length - curOff); if (amtRead == -1) { break; } curOff += amtRead; } return curOff; } catch (IOException e) { throw new RuntimeException("Unexpected IOException while decompressing!", e); } }
#vulnerable code @Override public int decompress(byte[] src, int srcOffset, int srcLength, byte[] dst, int dstOff) { if (srcLength - srcOffset == 0) { return 0; } try { ByteArrayInputStream bytesIn = new ByteArrayInputStream(src, srcOffset, srcLength); GZIPInputStream gzip = new GZIPInputStream(bytesIn); int curOff = dstOff; while (true) { int amtRead = gzip.read(dst, curOff, dst.length - curOff); if (amtRead == -1) { break; } curOff += amtRead; } return curOff; } catch (IOException e) { throw new RuntimeException("Unexpected IOException while decompressing!", e); } } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void 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 static void main(String[] args) throws IOException { String configPath = args[0]; String log4jprops = args[1]; PropertyConfigurator.configure(log4jprops); UpdateDaemonConfigurator conf = new YamlConfigurator(configPath); new UpdateDaemon(conf, HostUtils.getHostName()).run(); }
#vulnerable code public static void main(String[] args) throws IOException { String configPath = args[0]; String log4jprops = args[1]; PropertyConfigurator.configure(log4jprops); new UpdateDaemon(null, HostUtils.getHostName()).run(); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.