output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code private int getOptimizeLevel() { return getOptionValue(Options.OPTIMIZE_LEVEL).level; }
#vulnerable code private int getOptimizeLevel() { return getOption(Options.OPTIMIZE_LEVEL); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public CodeGenerator newCodeGenerator(final AviatorClassLoader classLoader) { switch (getOptimizeLevel()) { case AviatorEvaluator.COMPILE: ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader, this.traceOutputStream); asmCodeGenerator.start(); return asmCodeGenerator; case AviatorEvaluator.EVAL: return new OptimizeCodeGenerator(this, classLoader, this.traceOutputStream); default: throw new IllegalArgumentException("Unknow option " + getOptimizeLevel()); } }
#vulnerable code public CodeGenerator newCodeGenerator(final AviatorClassLoader classLoader) { switch (getOptimizeLevel()) { case AviatorEvaluator.COMPILE: ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader, this.traceOutputStream, getOptionValue(Options.TRACE).bool); asmCodeGenerator.start(); return asmCodeGenerator; case AviatorEvaluator.EVAL: return new OptimizeCodeGenerator(this, classLoader, this.traceOutputStream, getOptionValue(Options.TRACE).bool); default: throw new IllegalArgumentException("Unknow option " + getOptimizeLevel()); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onMethodName(Token<?> lookhead) { String outtterMethodName = "lambda"; if (lookhead.getType() != TokenType.Delegate) { outtterMethodName = lookhead.getLexeme(); String innerMethodName = this.innerMethodMap.get(outtterMethodName); if (innerMethodName != null) { this.loadAviatorFunction(outtterMethodName, innerMethodName); } else { this.createAviatorFunctionObject(outtterMethodName); } } else { this.loadEnv(); this.mv.visitMethodInsn(INVOKESTATIC, "com/googlecode/aviator/runtime/RuntimeUtils", "getFunction", "(Ljava/lang/Object;Ljava/util/Map;)Lcom/googlecode/aviator/runtime/type/AviatorFunction;"); this.popOperand(); } if (this.instance.getOptionValue(Options.TRACE_EVAL).bool) { this.mv.visitMethodInsn(INVOKESTATIC, "com/googlecode/aviator/runtime/function/TraceFunction", "wrapTrace", "(Lcom/googlecode/aviator/runtime/type/AviatorFunction;)Lcom/googlecode/aviator/runtime/type/AviatorFunction;"); } this.loadEnv(); this.methodMetaDataStack.push(new MethodMetaData(outtterMethodName)); }
#vulnerable code @Override public void onMethodName(Token<?> lookhead) { String outtterMethodName = "lambda"; if (lookhead.getType() != TokenType.Delegate) { outtterMethodName = lookhead.getLexeme(); String innerMethodName = this.innerMethodMap.get(outtterMethodName); if (innerMethodName != null) { this.loadAviatorFunction(outtterMethodName, innerMethodName); } else { this.createAviatorFunctionObject(outtterMethodName); } } else { this.loadEnv(); this.mv.visitMethodInsn(INVOKESTATIC, "com/googlecode/aviator/runtime/RuntimeUtils", "getFunction", "(Ljava/lang/Object;Ljava/util/Map;)Lcom/googlecode/aviator/runtime/type/AviatorFunction;"); this.popOperand(); } if (this.instance.getOption(Options.TRACE_EVAL)) { this.mv.visitMethodInsn(INVOKESTATIC, "com/googlecode/aviator/runtime/function/TraceFunction", "wrapTrace", "(Lcom/googlecode/aviator/runtime/type/AviatorFunction;)Lcom/googlecode/aviator/runtime/type/AviatorFunction;"); } this.loadEnv(); this.methodMetaDataStack.push(new MethodMetaData(outtterMethodName)); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public AviatorObject match(AviatorObject other, Map<String, Object> env) { switch (other.getAviatorType()) { case String: AviatorString aviatorString = (AviatorString) other; Matcher m = this.pattern.matcher(aviatorString.lexeme); if (m.matches()) { boolean captureGroups = RuntimeUtils.getInstance(env) .getOptionValue(Options.PUT_CAPTURING_GROUPS_INTO_ENV).bool; if (captureGroups && env != null && env != Collections.EMPTY_MAP) { int groupCount = m.groupCount(); for (int i = 0; i <= groupCount; i++) { env.put("$" + i, m.group(i)); } } return AviatorBoolean.TRUE; } else { return AviatorBoolean.FALSE; } case JavaType: AviatorJavaType javaType = (AviatorJavaType) other; final Object javaValue = javaType.getValue(env); if (TypeUtils.isString(javaValue)) { return this.match(new AviatorString(String.valueOf(javaValue)), env); } else { throw new ExpressionRuntimeException( this.desc(env) + " could not match " + other.desc(env)); } default: throw new ExpressionRuntimeException( this.desc(env) + " could not match " + other.desc(env)); } }
#vulnerable code @Override public AviatorObject match(AviatorObject other, Map<String, Object> env) { switch (other.getAviatorType()) { case String: AviatorString aviatorString = (AviatorString) other; Matcher m = this.pattern.matcher(aviatorString.lexeme); if (m.matches()) { boolean captureGroups = RuntimeUtils.getInstance(env).getOption(Options.PUT_CAPTURING_GROUPS_INTO_ENV); if (captureGroups && env != null && env != Collections.EMPTY_MAP) { int groupCount = m.groupCount(); for (int i = 0; i <= groupCount; i++) { env.put("$" + i, m.group(i)); } } return AviatorBoolean.TRUE; } else { return AviatorBoolean.FALSE; } case JavaType: AviatorJavaType javaType = (AviatorJavaType) other; final Object javaValue = javaType.getValue(env); if (TypeUtils.isString(javaValue)) { return this.match(new AviatorString(String.valueOf(javaValue)), env); } else { throw new ExpressionRuntimeException( this.desc(env) + " could not match " + other.desc(env)); } default: throw new ExpressionRuntimeException( this.desc(env) + " could not match " + other.desc(env)); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public CodeGenerator newCodeGenerator(AviatorClassLoader classLoader) { switch (getOptimizeLevel()) { case AviatorEvaluator.COMPILE: ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader, traceOutputStream, getOptionValue(Options.TRACE).bool); asmCodeGenerator.start(); return asmCodeGenerator; case AviatorEvaluator.EVAL: return new OptimizeCodeGenerator(this, classLoader, traceOutputStream, getOptionValue(Options.TRACE).bool); default: throw new IllegalArgumentException("Unknow option " + getOptimizeLevel()); } }
#vulnerable code public CodeGenerator newCodeGenerator(AviatorClassLoader classLoader) { switch (getOptimizeLevel()) { case AviatorEvaluator.COMPILE: ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader, traceOutputStream, (Boolean) getOption(Options.TRACE)); asmCodeGenerator.start(); return asmCodeGenerator; case AviatorEvaluator.EVAL: return new OptimizeCodeGenerator(this, classLoader, traceOutputStream, (Boolean) getOption(Options.TRACE)); default: throw new IllegalArgumentException("Unknow option " + getOptimizeLevel()); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object getValue(Map<String, Object> env) { if (env != null) { if (this.name.contains(".") && RuntimeUtils.getInstance(env) .getOptionValue(Options.ENABLE_PROPERTY_SYNTAX_SUGAR).bool) { return getProperty(env); } return env.get(this.name); } return null; }
#vulnerable code @Override public Object getValue(Map<String, Object> env) { if (env != null) { if (this.name.contains(".") && RuntimeUtils.getInstance(env) .<Boolean>getOption(Options.ENABLE_PROPERTY_SYNTAX_SUGAR)) { return getProperty(env); } return env.get(this.name); } return null; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected Env genTopEnv(Map<String, Object> map) { Env env = newEnv(map, this.instance.getOption(Options.USE_USER_ENV_AS_TOP_ENV_DIRECTLY) == Boolean.TRUE); if (this.compileEnv != null && !this.compileEnv.isEmpty()) { env.putAll(this.compileEnv); } return env; }
#vulnerable code protected Env genTopEnv(Map<String, Object> map) { Env env = newEnv(map, (boolean) this.instance.getOption(Options.USE_USER_ENV_AS_TOP_ENV_DIRECTLY)); if (this.compileEnv != null && !this.compileEnv.isEmpty()) { env.putAll(this.compileEnv); } return env; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private File copyToMergedCodebase(String filename, File destFile) { File mergedFile = mergedCodebase.getFile(filename); try { filesystem.makeDirsForFile(mergedFile); filesystem.copyFile(destFile, mergedFile); return mergedFile; } catch (IOException e) { throw new MoeProblem(e.getMessage()); } }
#vulnerable code private File copyToMergedCodebase(String filename, File destFile) { FileSystem fs = Injector.INSTANCE.fileSystem(); File mergedFile = mergedCodebase.getFile(filename); try { fs.makeDirsForFile(mergedFile); fs.copyFile(destFile, mergedFile); return mergedFile; } catch (IOException e) { throw new MoeProblem(e.getMessage()); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void generateMergedFile(String filename) { File origFile = originalCodebase.getFile(filename); boolean origExists = filesystem.exists(origFile); File destFile = destinationCodebase.getFile(filename); boolean destExists = filesystem.exists(destFile); File modFile = modifiedCodebase.getFile(filename); boolean modExists = filesystem.exists(modFile); if (!destExists && !modExists) { // This should never be thrown since generateMergedFile(...) is only called on filesToMerge // from merge() which is the union of the files in the destination and modified codebases. throw new MoeProblem( "%s doesn't exist in either %s nor %s. This should not be possible.", filename, destinationCodebase, modifiedCodebase); } else if (origExists && modExists && !destExists) { if (areDifferent(filename, origFile, modFile)) { // Proceed and merge in /dev/null, which should produce a merge conflict (incoming edit on // delete). destFile = new File("/dev/null"); } else { // Defer to deletion in destination codebase. return; } } else if (origExists && !modExists && destExists) { // Blindly follow deletion of the original file by not copying it into the merged codebase. return; } else if (!origExists && !(modExists && destExists)) { // File exists only in modified or destination codebase, so just copy it over. File existingFile = (modExists ? modFile : destFile); copyToMergedCodebase(filename, existingFile); return; } else if (!origExists && modExists && destExists) { // Merge both new files (conflict expected). origFile = new File("/dev/null"); } File mergedFile = copyToMergedCodebase(filename, destFile); try { // Merges the changes that lead from origFile to modFile into mergedFile (which is a copy // of destFile). After, mergedFile will have the combined changes of modFile and destFile. cmd.runCommand( "merge", ImmutableList.of( mergedFile.getAbsolutePath(), origFile.getAbsolutePath(), modFile.getAbsolutePath()), this.mergedCodebase.getPath().getAbsolutePath()); // Return status was 0 and the merge was successful. Note it. mergedFiles.add(mergedFile.getAbsolutePath()); } catch (CommandException e) { // If merge fails with exit status 1, then a conflict occurred. Make a note of the filepath. if (e.returnStatus == 1) { failedToMergeFiles.add(mergedFile.getAbsolutePath()); } else { throw new MoeProblem( "Merge returned with unexpected status %d when trying to run \"merge -p %s %s %s\"", e.returnStatus, destFile.getAbsolutePath(), origFile.getAbsolutePath(), modFile.getAbsolutePath()); } } }
#vulnerable code public void generateMergedFile(String filename) { FileSystem fs = Injector.INSTANCE.fileSystem(); File origFile = originalCodebase.getFile(filename); boolean origExists = fs.exists(origFile); File destFile = destinationCodebase.getFile(filename); boolean destExists = fs.exists(destFile); File modFile = modifiedCodebase.getFile(filename); boolean modExists = fs.exists(modFile); if (!destExists && !modExists) { // This should never be thrown since generateMergedFile(...) is only called on filesToMerge // from merge() which is the union of the files in the destination and modified codebases. throw new MoeProblem( "%s doesn't exist in either %s nor %s. This should not be possible.", filename, destinationCodebase, modifiedCodebase); } else if (origExists && modExists && !destExists) { if (areDifferent(filename, origFile, modFile)) { // Proceed and merge in /dev/null, which should produce a merge conflict (incoming edit on // delete). destFile = new File("/dev/null"); } else { // Defer to deletion in destination codebase. return; } } else if (origExists && !modExists && destExists) { // Blindly follow deletion of the original file by not copying it into the merged codebase. return; } else if (!origExists && !(modExists && destExists)) { // File exists only in modified or destination codebase, so just copy it over. File existingFile = (modExists ? modFile : destFile); copyToMergedCodebase(filename, existingFile); return; } else if (!origExists && modExists && destExists) { // Merge both new files (conflict expected). origFile = new File("/dev/null"); } File mergedFile = copyToMergedCodebase(filename, destFile); try { // Merges the changes that lead from origFile to modFile into mergedFile (which is a copy // of destFile). After, mergedFile will have the combined changes of modFile and destFile. Injector.INSTANCE .cmd() .runCommand( "merge", ImmutableList.of( mergedFile.getAbsolutePath(), origFile.getAbsolutePath(), modFile.getAbsolutePath()), this.mergedCodebase.getPath().getAbsolutePath()); // Return status was 0 and the merge was successful. Note it. mergedFiles.add(mergedFile.getAbsolutePath()); } catch (CommandException e) { // If merge fails with exit status 1, then a conflict occurred. Make a note of the filepath. if (e.returnStatus == 1) { failedToMergeFiles.add(mergedFile.getAbsolutePath()); } else { throw new MoeProblem( "Merge returned with unexpected status %d when trying to run \"merge -p %s %s %s\"", e.returnStatus, destFile.getAbsolutePath(), origFile.getAbsolutePath(), modFile.getAbsolutePath()); } } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testUpdate() { redisSessionDAO.doCreate(session1); redisSessionDAO.doReadSession(session1.getId()); doChangeSessionName(session1, name1); redisSessionDAO.update(session1); FakeSession actualSession = (FakeSession)redisSessionDAO.doReadSession(session1.getId()); assertEquals(actualSession.getName(), name1); }
#vulnerable code @Test public void testUpdate() { redisSessionDAO.doCreate(session1); doChangeSessionName(session1, name1); redisSessionDAO.update(session1); FakeSession actualSession = (FakeSession)redisSessionDAO.doReadSession(session1.getId()); assertEquals(actualSession.getName(), name1); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRemove() throws SerializationException { FakeAuth nullValue = redisCache.remove(null); assertThat(nullValue, is(nullValue())); String testKey = "billy"; byte[] testKeyBytes = keySerializer.serialize(testPrefix + testKey); FakeAuth testValue = new FakeAuth(3, "client"); byte[] testValueBytes = valueSerializer.serialize(testValue); when(redisManager.get(testKeyBytes)).thenReturn(testValueBytes); FakeAuth actualValue = redisCache.remove(testKey); assertThat(actualValue.getId(), is(3)); assertThat(actualValue.getRole(), is("client")); }
#vulnerable code @Test public void testRemove() { redisCache.remove(null); FakeSession actualValue = redisCache.remove(testKey); assertThat(actualValue.getId(), is(3)); assertThat(actualValue.getName(), is("jack")); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDoReadSession() throws NoSuchFieldException, IllegalAccessException { Session nullSession = redisSessionDAO.doReadSession(null); assertThat(nullSession, is(nullValue())); RedisSessionDAO redisSessionDAO2 = new RedisSessionDAO(); redisSessionDAO2.setRedisManager(redisManager); redisSessionDAO2.setKeyPrefix(testPrefix); redisSessionDAO2.setExpire(2); ThreadLocal sessionsInThread = mock(ThreadLocal.class); Map<Serializable, SessionInMemory> sessionMap = new HashMap<Serializable, SessionInMemory>(); SessionInMemory sessionInMemory = new SessionInMemory(); sessionInMemory.setSession(new FakeSession(1, "Billy")); sessionInMemory.setCreateTime(new Date()); sessionMap.put("1", sessionInMemory); when(sessionsInThread.get()).thenReturn(sessionMap); TestUtils.setPrivateField(redisSessionDAO2, "sessionsInThread", sessionsInThread); FakeSession actualSession = (FakeSession)redisSessionDAO2.doReadSession("1"); assertThat(actualSession.getId().toString(), is("1")); assertThat(actualSession.getName(), is("Billy")); verify(redisManager, times(0)).get(any((new byte[0]).getClass())); }
#vulnerable code @Test public void testDoReadSession() { Session actualSession = redisSessionDAO.doReadSession(testKey); assertThat(actualSession.getId().toString(), is("3")); redisSessionDAO.doReadSession(null); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void writeFileTxt(String fileName, String[] totalFile){ FileWriter file = null; PrintWriter pw = null; try { file = new FileWriter(System.getProperty("user.dir")+"/"+fileName); pw = new PrintWriter(file); for (int i = 0; i < totalFile.length; i++) pw.println(totalFile[i]); } catch (Exception e) { e.printStackTrace(); } finally { try { // Execute the "finally" to make sure the file is closed if (null != file) file.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if (pw != null) pw.close(); } catch (Exception e2) { e2.printStackTrace(); } } }
#vulnerable code public static void writeFileTxt(String fileName, String[] totalFile){ FileWriter file = null; PrintWriter pw = null; try { file = new FileWriter(System.getProperty("user.dir")+"/"+fileName); pw = new PrintWriter(file); for (int i = 0; i < totalFile.length; i++) pw.println(totalFile[i]); } catch (Exception e) { e.printStackTrace(); } finally { try { // Execute the "finally" to make sure the file is closed if (null != file) file.close(); } catch (Exception e2) { e2.printStackTrace(); } } } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void writeFileTxt(String fileName, String[] totalFile){ FileWriter file = null; PrintWriter pw = null; try { file = new FileWriter(System.getProperty("user.dir")+"/"+fileName); pw = new PrintWriter(file); for (int i = 0; i < totalFile.length; i++) pw.println(totalFile[i]); } catch (Exception e) { e.printStackTrace(); } finally { try { // Execute the "finally" to make sure the file is closed if (null != file) file.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if (pw != null) pw.close(); } catch (Exception e2) { e2.printStackTrace(); } } }
#vulnerable code public static void writeFileTxt(String fileName, String[] totalFile){ FileWriter file = null; PrintWriter pw = null; try { file = new FileWriter(System.getProperty("user.dir")+"/"+fileName); pw = new PrintWriter(file); for (int i = 0; i < totalFile.length; i++) pw.println(totalFile[i]); } catch (Exception e) { e.printStackTrace(); } finally { try { // Execute the "finally" to make sure the file is closed if (null != file) file.close(); } catch (Exception e2) { e2.printStackTrace(); } } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void recoveryFromLog() { synchronized (mDatasets) { recoveryFromFile(Config.MASTER_CHECKPOINT_FILE, "Master Checkpoint file "); recoveryFromFile(Config.MASTER_LOG_FILE, "Master Log file "); } }
#vulnerable code private void recoveryFromLog() { MasterLogReader reader; synchronized (mDatasets) { File file = new File(Config.MASTER_CHECKPOINT_FILE); if (!file.exists()) { LOG.info("Master Checkpoint file " + Config.MASTER_CHECKPOINT_FILE + " does not exist."); } else { reader = new MasterLogReader(Config.MASTER_CHECKPOINT_FILE); while (reader.hasNext()) { DatasetInfo dataset = reader.getNextDatasetInfo(); mDatasets.put(dataset.mId, dataset); mDatasetPathToId.put(dataset.mPath, dataset.mId); } } file = new File(Config.MASTER_LOG_FILE); if (!file.exists()) { LOG.info("Master Log file " + Config.MASTER_LOG_FILE + " does not exist."); } else { reader = new MasterLogReader(Config.MASTER_LOG_FILE); while (reader.hasNext()) { DatasetInfo dataset = reader.getNextDatasetInfo(); if (dataset.mId > 0) { mDatasets.put(dataset.mId, dataset); mDatasetPathToId.put(dataset.mPath, dataset.mId); } else { mDatasets.remove(-dataset.mId); mDatasetPathToId.remove(dataset.mPath); } } } } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void evaluateStatement(Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable { container = null; FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault()); try { LOGGER.info("Setting up {} in {}", getName(), temporaryFolder.getRoot().getAbsolutePath()); container = createHiveServerContainer(target, temporaryFolder); base.evaluate(); } finally { tearDown(); } }
#vulnerable code private void evaluateStatement(Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable { container = null; setAndCheckIfWritable(temporaryFolder); try { LOGGER.info("Setting up {} in {}", getName(), temporaryFolder.getRoot().getAbsolutePath()); container = createHiveServerContainer(target, temporaryFolder); base.evaluate(); } finally { tearDown(); } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String serialize(String data) { try { AbiBin abiBin = new AbiBin(); JSONObject res = abiBin.request(RequestParams.of(netParams, () -> data)); return res.getString("binargs"); } catch (JSONException ex) { throw new IllegalArgumentException(String.format("Invalid json \"%s\" passed in.", data), ex); } catch (ApiResponseException ex) { throw new AbiSerialisationFailureException("Failed to serialize via node", ex); } }
#vulnerable code @Override public String serialize(String data) { try { AbiBin abiBin = new AbiBin(); JSONObject res = abiBin.request(RequestParams.of(netParams, () -> data)); return res.getString("binargs"); } catch (JSONException ex) { throw new IllegalArgumentException(String.format("Invalid json \"%s\" passed in.", data), ex); } catch (ApiResponseException ex) { throw new AbiSerialisationFailureException(ex.getRaw().toString(), ex); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public JSONObject getInfo() throws EvtSdkException { Info info = new Info(); return info.get(RequestParams.of(netParams)); }
#vulnerable code public JSONObject getInfo() throws EvtSdkException { Info info = new Info(); return info.get(netParams, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public JSONObject getHeadBlockHeaderState() throws EvtSdkException { HeadBlockHeaderState headBlockHeaderState = new HeadBlockHeaderState(); return headBlockHeaderState.get(RequestParams.of(netParams)); }
#vulnerable code public JSONObject getHeadBlockHeaderState() throws EvtSdkException { HeadBlockHeaderState headBlockHeaderState = new HeadBlockHeaderState(); return headBlockHeaderState.get(netParams, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static float[] getMedianErrorRates(LangDescriptor language, int maxNumFiles, int trials) throws Exception { SubsetValidator validator = new SubsetValidator(language.corpusDir, language); List<InputDocument> documents = load(validator.allFiles, language); float[] medians = new float[maxNumFiles+1]; int ncpu = Runtime.getRuntime().availableProcessors(); ExecutorService pool = Executors.newFixedThreadPool(3); // works with 2 but not 3 threads. hmm... List<Callable<Void>> jobs = new ArrayList<>(); for (int i = 1; i<=Math.min(validator.allFiles.size(), maxNumFiles); i++) { // i is corpus subset size final int corpusSubsetSize = i; Callable<Void> job = () -> { try { List<Float> errorRates = new ArrayList<>(); for (int trial = 1; trial<=trials; trial++) { // multiple trials per subset size Pair<InputDocument, List<InputDocument>> sample = validator.selectSample(documents, corpusSubsetSize); Triple<Formatter, Float, Float> results = validate(language, sample.b, sample.a, true, false); // System.out.println(sample.a.fileName+" n="+corpusSubsetSize+": error="+results.c); // System.out.println("\tcorpus =\n\t\t"+Utils.join(sample.b.iterator(), "\n\t\t")); errorRates.add(results.c); } Collections.sort(errorRates); int n = errorRates.size(); float median = errorRates.get(n/2); System.out.println("median "+language.name+" error rate for n="+corpusSubsetSize+" is "+median); medians[corpusSubsetSize] = median; } catch (Throwable t) { t.printStackTrace(System.err); } return null; }; jobs.add(job); } pool.invokeAll(jobs); pool.shutdown(); boolean terminated = pool.awaitTermination(60, TimeUnit.MINUTES); System.err.println(language.name+" terminate properly = "+terminated); return medians; }
#vulnerable code public static float[] getMedianErrorRates(LangDescriptor language, int maxNumFiles, int trials) throws Exception { SubsetValidator validator = new SubsetValidator(language.corpusDir, language); List<InputDocument> documents = load(validator.allFiles, language); float[] medians = new float[maxNumFiles+1]; for (int i = 1; i<=Math.min(validator.allFiles.size(), maxNumFiles); i++) { // i is corpus subset size List<Float> errorRates = new ArrayList<>(); for (int trial = 1; trial<=trials; trial++) { // multiple trials per subset size Pair<InputDocument, List<InputDocument>> sample = validator.selectSample(documents, i); Triple<Formatter, Float, Float> results = validate(language, sample.b, sample.a, true, false); System.out.println(sample.a.fileName+" n="+i+": error="+results.c); // System.out.println("\tcorpus =\n\t\t"+Utils.join(sample.b.iterator(), "\n\t\t")); errorRates.add(results.c); } Collections.sort(errorRates); int n = errorRates.size(); float min = errorRates.get(0); float quart = errorRates.get((int)(0.27*n)); float median = errorRates.get(n/2); float quart3 = errorRates.get((int)(0.75*n)); float max = errorRates.get(n-1); System.out.println("median error rate for n="+i+" is "+median); medians[i] = median; } return medians; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { LangDescriptor[] languages = new LangDescriptor[] { JAVA_DESCR, // JAVA8_DESCR, ANTLR4_DESCR, // SQLITE_NOISY_DESCR, // SQLITE_CLEAN_DESCR, // TSQL_NOISY_DESCR, // TSQL_CLEAN_DESCR, }; testFeatures(languages, false); }
#vulnerable code public static void main(String[] args) throws Exception { LangDescriptor[] languages = new LangDescriptor[] { JAVA_DESCR, // JAVA8_DESCR, ANTLR4_DESCR, // SQLITE_NOISY_DESCR, // SQLITE_CLEAN_DESCR, // TSQL_NOISY_DESCR, // TSQL_CLEAN_DESCR, }; Map<String,Map<String, Float>> langToFeatureMedians = new HashMap<>(); List<String> labels = new ArrayList<>(); labels.add("curated"); labels.add("all-in"); for (FeatureMetaData f : FEATURES_ALL) { labels.add(Utils.join(f.abbrevHeaderRows, " ")); } for (LangDescriptor language : languages) { System.out.println("###### "+language.name); Map<String, Float> featureToErrors = new LinkedHashMap<>(); FeatureMetaData[] injectWSFeatures = deepCopy(FEATURES_ALL); FeatureMetaData[] alignmentFeatures = deepCopy(FEATURES_ALIGN); // do it first to get answer with curated features List<Float> errors = getErrorRates(language, FEATURES_INJECT_WS, alignmentFeatures); Collections.sort(errors); int n = errors.size(); float quart = errors.get((int)(0.27*n)); float median = errors.get(n/2); float quart3 = errors.get((int)(0.75*n)); System.out.println("curated error median "+median); featureToErrors.put("curated", median); // do it again to get answer with all features errors = getErrorRates(language, FEATURES_ALL, alignmentFeatures); Collections.sort(errors); n = errors.size(); median = errors.get(n/2); System.out.println("all-in error median "+median); featureToErrors.put("all-in", median); for (FeatureMetaData feature : injectWSFeatures) { if ( feature==FeatureMetaData.UNUSED || feature.type.toString().startsWith("INFO_") ) continue; String name = Utils.join(feature.abbrevHeaderRows, " "); labels.add(name.trim()); System.out.println("wack "+name); double saveCost = feature.mismatchCost; feature.mismatchCost = 0; // wack this feature errors = getErrorRates(language, injectWSFeatures, alignmentFeatures); Collections.sort(errors); n = errors.size(); median = errors.get(n/2); featureToErrors.put(name, median); System.out.println("median error rates "+median); // reset feature feature.mismatchCost = saveCost; } System.out.println(featureToErrors); langToFeatureMedians.put(language.name, featureToErrors); } String python = "#\n"+ "# AUTO-GENERATED FILE. DO NOT EDIT\n" + "# CodeBuff <version> '<date>'\n" + "#\n"+ "import numpy as np\n"+ "import matplotlib.pyplot as plt\n\n" + "fig = plt.figure()\n"+ "ax = plt.subplot(111)\n"+ "N = <numFeatures>\n" + "featureIndexes = range(0,N)\n" + "<langToMedians:{r |\n" + "<r> = [<langToMedians.(r); separator={, }>]\n"+ "ax.plot(featureIndexes, <r>, label=\"<r>\")\n" + "}>\n" + "labels = [<labels:{l | '<l>'}; separator={, }>]\n" + "ax.set_xticklabels(labels, rotation=60, fontsize=8)\n"+ "plt.xticks(featureIndexes, labels, rotation=60)\n" + "ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)\n\n" + "ax.set_xlabel(\"Inject Whitespace Feature\")\n"+ "ax.set_ylabel(\"Median Error rate\")\n" + "ax.set_title(\"Effect of Dropping One Feature on Whitespace Decision\\nMedian Leave-one-out Validation Error Rate\")\n"+ "plt.legend()\n" + "plt.tight_layout()\n" + "plt.show()\n"; ST pythonST = new ST(python); Map<String,Collection<Float>> langToMedians = new HashMap<>(); int numFeatures = 0; for (String s : langToFeatureMedians.keySet()) { Map<String, Float> featureToErrors = langToFeatureMedians.get(s); langToMedians.put(s, featureToErrors.values()); numFeatures = featureToErrors.values().size(); } pythonST.add("langToMedians", langToMedians); pythonST.add("version", version); pythonST.add("date", new Date()); pythonST.add("numFeatures", numFeatures); pythonST.add("labels", labels); String code = pythonST.render(); String fileName = "python/src/drop_one_feature.py"; Utils.writeFile(fileName, code); System.out.println("wrote python code to "+fileName); } #location 30 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void trainOnSampleDocs() throws Exception { documentsPerExemplar = new ArrayList<>(); featureVectors = new ArrayList<>(); injectWhitespace = new ArrayList<>(); hpos = new ArrayList<>(); for (InputDocument doc : documents) { if ( showFileNames ) System.out.println(doc); // Parse document, save feature vectors to the doc Trainer trainer = new Trainer(this, doc, language.indentSize); trainer.computeFeatureVectors(); } }
#vulnerable code public void trainOnSampleDocs() throws Exception { documentsPerExemplar = new ArrayList<>(); featureVectors = new ArrayList<>(); injectWhitespace = new ArrayList<>(); hpos = new ArrayList<>(); for (InputDocument doc : documents) { if ( showFileNames ) System.out.println(doc); Triple<List<int[]>, List<Integer>, List<Integer>> results = process(doc); List<int[]> features = results.a; List<Integer> ws = results.b; List<Integer> al = results.c; for (int i=0; i<features.size(); i++) { documentsPerExemplar.add(doc); int[] featureVec = features.get(i); injectWhitespace.add(ws.get(i)); hpos.add(al.get(i)); featureVectors.add(featureVec); } } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public PageResult<TokenVo> listTokens(Map<String, Object> params, String clientId) { Integer page = MapUtils.getInteger(params, "page"); Integer limit = MapUtils.getInteger(params, "limit"); int[] startEnds = PageUtil.transToStartEnd(page, limit); //根据请求参数生成redis的key String redisKey = getRedisKey(params, clientId); long size = redisRepository.length(redisKey); List<TokenVo> result = new ArrayList<>(limit); RedisSerializer<Object> valueSerializer = RedisSerializer.java(); //查询token集合 //redisRepository.getRedisTemplate().e List<Object> tokenObjs = redisRepository.getList(redisKey, startEnds[0], startEnds[1]-1, valueSerializer); if (tokenObjs != null) { for (Object obj : tokenObjs) { DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken)obj; //构造token对象 TokenVo tokenVo = new TokenVo(); tokenVo.setTokenValue(accessToken.getValue()); tokenVo.setExpiration(accessToken.getExpiration()); //获取用户信息 Object authObj = redisRepository.get(SecurityConstants.REDIS_TOKEN_AUTH + accessToken.getValue(), valueSerializer); OAuth2Authentication authentication = (OAuth2Authentication)authObj; if (authentication != null) { OAuth2Request request = authentication.getOAuth2Request(); tokenVo.setUsername(authentication.getName()); tokenVo.setClientId(request.getClientId()); tokenVo.setGrantType(request.getGrantType()); } result.add(tokenVo); } } return PageResult.<TokenVo>builder().data(result).code(0).count(size).build(); }
#vulnerable code @Override public PageResult<TokenVo> listTokens(Map<String, Object> params, String clientId) { Integer page = MapUtils.getInteger(params, "page"); Integer limit = MapUtils.getInteger(params, "limit"); int[] startEnds = PageUtil.transToStartEnd(page, limit); //根据请求参数生成redis的key String redisKey = getRedisKey(params, clientId); long size = redisRepository.length(redisKey); List<TokenVo> result = new ArrayList<>(limit); //查询token集合 List<Object> tokenObjs = redisRepository.getList(redisKey, startEnds[0], startEnds[1]-1); if (tokenObjs != null) { for (Object obj : tokenObjs) { DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken)obj; //构造token对象 TokenVo tokenVo = new TokenVo(); tokenVo.setTokenValue(accessToken.getValue()); tokenVo.setExpiration(accessToken.getExpiration()); //获取用户信息 Object authObj = redisRepository.get(SecurityConstants.REDIS_TOKEN_AUTH + accessToken.getValue()); OAuth2Authentication authentication = (OAuth2Authentication)authObj; if (authentication != null) { OAuth2Request request = authentication.getOAuth2Request(); tokenVo.setUsername(authentication.getName()); tokenVo.setClientId(request.getClientId()); tokenVo.setGrantType(request.getGrantType()); } result.add(tokenVo); } } return PageResult.<TokenVo>builder().data(result).code(0).count(size).build(); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private ObjectNode getDataNode(Object object, Map<String, ObjectNode> includedContainer, SerializationSettings settings) throws IllegalAccessException { ObjectNode dataNode = objectMapper.createObjectNode(); // Perform initial conversion ObjectNode attributesNode = objectMapper.valueToTree(object); // Handle id, meta and relationship fields Field idField = configuration.getIdField(object.getClass()); JsonNode id = attributesNode.remove(idField.getName()); // Handle meta Field metaField = configuration.getMetaField(object.getClass()); if (metaField != null) { JsonNode meta = attributesNode.remove(metaField.getName()); if (meta != null && shouldSerializeMeta(settings)) { dataNode.set(META, meta); } } // Handle links String selfHref = null; JsonNode jsonLinks = getResourceLinks(object, attributesNode, id, settings); if (jsonLinks != null) { dataNode.set(LINKS, jsonLinks); if (jsonLinks.has(SELF)) { selfHref = jsonLinks.get(SELF).get(HREF).asText(); } } // Handle resource identifier dataNode.put(TYPE, configuration.getTypeName(object.getClass())); String resourceId = (String) idField.get(object); if (resourceId != null) { dataNode.put(ID, resourceId); // Cache the object for recursion breaking purposes resourceCache.cache(resourceId.concat(configuration.getTypeName(object.getClass())), null); } dataNode.set(ATTRIBUTES, attributesNode); // Handle relationships (remove from base type and add as relationships) List<Field> relationshipFields = configuration.getRelationshipFields(object.getClass()); if (relationshipFields != null) { ObjectNode relationshipsNode = objectMapper.createObjectNode(); for (Field relationshipField : relationshipFields) { Object relationshipObject = relationshipField.get(object); if (relationshipObject != null) { attributesNode.remove(relationshipField.getName()); Relationship relationship = configuration.getFieldRelationship(relationshipField); // In case serialisation is disabled for a given relationship, skip it if (!relationship.serialise()) { continue; } String relationshipName = relationship.value(); ObjectNode relationshipDataNode = objectMapper.createObjectNode(); relationshipsNode.set(relationshipName, relationshipDataNode); // Serialize relationship meta JsonNode relationshipMeta = getRelationshipMeta(object, relationshipName, settings); if (relationshipMeta != null) { relationshipDataNode.set(META, relationshipMeta); attributesNode.remove(configuration .getRelationshipMetaField(object.getClass(), relationshipName).getName()); } // Serialize relationship links JsonNode relationshipLinks = getRelationshipLinks(object, relationship, selfHref, settings); if (relationshipLinks != null) { relationshipDataNode.set(LINKS, relationshipLinks); // Remove link object from serialized JSON Field refField = configuration .getRelationshipLinksField(object.getClass(), relationshipName); if (refField != null) { attributesNode.remove(refField.getName()); } } if (relationshipObject instanceof Collection) { ArrayNode dataArrayNode = objectMapper.createArrayNode(); for (Object element : (Collection<?>) relationshipObject) { String relationshipType = configuration.getTypeName(element.getClass()); String idValue = (String) configuration.getIdField(element.getClass()).get(element); ObjectNode identifierNode = objectMapper.createObjectNode(); identifierNode.put(TYPE, relationshipType); identifierNode.put(ID, idValue); dataArrayNode.add(identifierNode); // Handle included data if (shouldSerializeRelationship(relationshipName, settings) && idValue != null) { String identifier = idValue.concat(relationshipType); if (!includedContainer.containsKey(identifier) && !resourceCache.contains(identifier)) { includedContainer.put(identifier, getDataNode(element, includedContainer, settings)); } } } relationshipDataNode.set(DATA, dataArrayNode); } else { String relationshipType = configuration.getTypeName(relationshipObject.getClass()); String idValue = (String) configuration.getIdField(relationshipObject.getClass()) .get(relationshipObject); ObjectNode identifierNode = objectMapper.createObjectNode(); identifierNode.put(TYPE, relationshipType); identifierNode.put(ID, idValue); relationshipDataNode.set(DATA, identifierNode); if (shouldSerializeRelationship(relationshipName, settings) && idValue != null) { String identifier = idValue.concat(relationshipType); if (!includedContainer.containsKey(identifier)) { includedContainer.put(identifier, getDataNode(relationshipObject, includedContainer, settings)); } } } } } if (relationshipsNode.size() > 0) { dataNode.set(RELATIONSHIPS, relationshipsNode); } } return dataNode; }
#vulnerable code private ObjectNode getDataNode(Object object, Map<String, ObjectNode> includedContainer, SerializationSettings settings) throws IllegalAccessException { ObjectNode dataNode = objectMapper.createObjectNode(); // Perform initial conversion ObjectNode attributesNode = objectMapper.valueToTree(object); // Handle id, meta and relationship fields Field idField = configuration.getIdField(object.getClass()); JsonNode id = attributesNode.remove(idField.getName()); // Handle meta Field metaField = configuration.getMetaField(object.getClass()); if (metaField != null) { JsonNode meta = attributesNode.remove(metaField.getName()); if (meta != null && shouldSerializeMeta(settings)) { dataNode.set(META, meta); } } // Handle links JsonNode jsonLinks = getResourceLinks(object, attributesNode, id.textValue(), settings); String selfHref = null; if (jsonLinks != null) { dataNode.set(LINKS, jsonLinks); if (jsonLinks.has(SELF)) { selfHref = jsonLinks.get(SELF).get(HREF).asText(); } } // Handle resource identifier dataNode.put(TYPE, configuration.getTypeName(object.getClass())); String resourceId = (String) idField.get(object); if (resourceId != null) { dataNode.put(ID, resourceId); // Cache the object for recursion breaking purposes resourceCache.cache(resourceId.concat(configuration.getTypeName(object.getClass())), null); } dataNode.set(ATTRIBUTES, attributesNode); // Handle relationships (remove from base type and add as relationships) List<Field> relationshipFields = configuration.getRelationshipFields(object.getClass()); if (relationshipFields != null) { ObjectNode relationshipsNode = objectMapper.createObjectNode(); for (Field relationshipField : relationshipFields) { Object relationshipObject = relationshipField.get(object); if (relationshipObject != null) { attributesNode.remove(relationshipField.getName()); Relationship relationship = configuration.getFieldRelationship(relationshipField); // In case serialisation is disabled for a given relationship, skip it if (!relationship.serialise()) { continue; } String relationshipName = relationship.value(); ObjectNode relationshipDataNode = objectMapper.createObjectNode(); relationshipsNode.set(relationshipName, relationshipDataNode); // Serialize relationship meta JsonNode relationshipMeta = getRelationshipMeta(object, relationshipName, settings); if (relationshipMeta != null) { relationshipDataNode.set(META, relationshipMeta); attributesNode.remove(configuration .getRelationshipMetaField(object.getClass(), relationshipName).getName()); } // Serialize relationship links JsonNode relationshipLinks = getRelationshipLinks(object, relationship, selfHref, settings); if (relationshipLinks != null) { relationshipDataNode.set(LINKS, relationshipLinks); // Remove link object from serialized JSON Field refField = configuration .getRelationshipLinksField(object.getClass(), relationshipName); if (refField != null) { attributesNode.remove(refField.getName()); } } if (relationshipObject instanceof Collection) { ArrayNode dataArrayNode = objectMapper.createArrayNode(); for (Object element : (Collection<?>) relationshipObject) { String relationshipType = configuration.getTypeName(element.getClass()); String idValue = (String) configuration.getIdField(element.getClass()).get(element); ObjectNode identifierNode = objectMapper.createObjectNode(); identifierNode.put(TYPE, relationshipType); identifierNode.put(ID, idValue); dataArrayNode.add(identifierNode); // Handle included data if (shouldSerializeRelationship(relationshipName, settings) && idValue != null) { String identifier = idValue.concat(relationshipType); if (!includedContainer.containsKey(identifier) && !resourceCache.contains(identifier)) { includedContainer.put(identifier, getDataNode(element, includedContainer, settings)); } } } relationshipDataNode.set(DATA, dataArrayNode); } else { String relationshipType = configuration.getTypeName(relationshipObject.getClass()); String idValue = (String) configuration.getIdField(relationshipObject.getClass()) .get(relationshipObject); ObjectNode identifierNode = objectMapper.createObjectNode(); identifierNode.put(TYPE, relationshipType); identifierNode.put(ID, idValue); relationshipDataNode.set(DATA, identifierNode); if (shouldSerializeRelationship(relationshipName, settings) && idValue != null) { String identifier = idValue.concat(relationshipType); if (!includedContainer.containsKey(identifier)) { includedContainer.put(identifier, getDataNode(relationshipObject, includedContainer, settings)); } } } } } if (relationshipsNode.size() > 0) { dataNode.set(RELATIONSHIPS, relationshipsNode); } } return dataNode; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void assertSuccessfulAuthentication(String providerId) { this.driver.navigate().to("http://localhost:8081/test-app/"); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); // choose the identity provider this.loginPage.clickSocial(providerId); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/")); // log in to identity provider this.loginPage.login("test-user", "password"); doAfterProviderAuthentication(providerId); doUpdateProfile(providerId); // authenticated and redirected to app assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app/")); assertNotNull(retrieveSessionStatus()); doAssertFederatedUser(providerId); driver.navigate().to("http://localhost:8081/test-app/logout"); driver.navigate().to("http://localhost:8081/test-app/"); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); }
#vulnerable code protected void assertSuccessfulAuthentication(String providerId) { this.driver.navigate().to("http://localhost:8081/test-app/"); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); // choose the identity provider this.loginPage.clickSocial(providerId); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/realms/realm-with-saml-identity-provider/protocol/saml")); // log in to identity provider this.loginPage.login("saml.user", "password"); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/broker/realm-with-broker/" + providerId)); // update profile this.updateProfilePage.assertCurrent(); String userEmail = "[email protected]"; String userFirstName = "New first"; String userLastName = "New last"; this.updateProfilePage.update(userFirstName, userLastName, userEmail); // authenticated and redirected to app assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app/")); KeycloakSession samlServerSession = brokerServerRule.startSession(); RealmModel brokerRealm = samlServerSession.realms().getRealm("realm-with-broker"); UserModel federatedUser = samlServerSession.users().getUserByEmail(userEmail, brokerRealm); // user created assertNotNull(federatedUser); assertEquals(userFirstName, federatedUser.getFirstName()); assertEquals(userLastName, federatedUser.getLastName()); driver.navigate().to("http://localhost:8081/test-app/logout"); driver.navigate().to("http://localhost:8081/test-app/"); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); // choose the identity provider this.loginPage.clickSocial(providerId); // already authenticated in saml idp and redirected to app assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app/")); } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) { BearerTokenAuthenticator bearer = createBearerTokenAuthenticator(); AuthenticationMechanismOutcome outcome = bearer.authenticate(exchange); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) { completeAuthentication(securityContext, bearer); return AuthenticationMechanismOutcome.AUTHENTICATED; } else if (adapterConfig.isBearerOnly()) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } OAuthAuthenticator oauth = createOAuthAuthenticator(exchange); outcome = oauth.authenticate(); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.NOT_ATTEMPTED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } completeAuthentication(securityContext, oauth); log.info("AUTHENTICATED"); return AuthenticationMechanismOutcome.AUTHENTICATED; }
#vulnerable code @Override public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) { BearerTokenAuthenticator bearer = createBearerTokenAuthenticator(); AuthenticationMechanismOutcome outcome = bearer.authenticate(exchange); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) { final AccessToken token = bearer.getToken(); String surrogate = bearer.getSurrogate(); KeycloakAuthenticatedSession session = new KeycloakAuthenticatedSession(bearer.getTokenString(), token, resourceMetadata); KeycloakPrincipal principal = completeAuthentication(securityContext, token, surrogate); propagateBearer(exchange, session, principal); return AuthenticationMechanismOutcome.AUTHENTICATED; } else if (adapterConfig.isBearerOnly()) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } OAuthAuthenticator oauth = createOAuthAuthenticator(exchange); outcome = oauth.authenticate(); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.NOT_ATTEMPTED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } KeycloakAuthenticatedSession session = new KeycloakAuthenticatedSession(oauth.getTokenString(), oauth.getToken(), resourceMetadata); KeycloakPrincipal principal = completeAuthentication(securityContext, oauth.getToken(), null); propagateOauth(exchange, session, principal); log.info("AUTHENTICATED"); return AuthenticationMechanismOutcome.AUTHENTICATED; } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Path("{username}/session-stats") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public Map<String, UserStats> getSessionStats(final @PathParam("username") String username) { logger.info("session-stats"); auth.requireView(); UserModel user = realm.getUser(username); if (user == null) { throw new NotFoundException("User not found"); } Map<String, UserStats> stats = new HashMap<String, UserStats>(); for (ApplicationModel applicationModel : realm.getApplications()) { if (applicationModel.getManagementUrl() == null) continue; UserStats appStats = new ResourceAdminManager().getUserStats(realm, applicationModel, user); if (appStats == null) continue; if (appStats.isLoggedIn()) stats.put(applicationModel.getName(), appStats); } return stats; }
#vulnerable code @Path("{username}/session-stats") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public Map<String, UserStats> getSessionStats(final @PathParam("username") String username) { logger.info("session-stats"); auth.requireView(); UserModel user = realm.getUser(username); if (user == null) { throw new NotFoundException("User not found"); } Map<String, UserStats> stats = new HashMap<String, UserStats>(); for (ApplicationModel applicationModel : realm.getApplications()) { if (applicationModel.getManagementUrl() == null) continue; UserStats appStats = new ResourceAdminManager().getUserStats(realm, applicationModel, user); if (appStats.isLoggedIn()) stats.put(applicationModel.getName(), appStats); } return stats; } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Throwable { KeycloakServerConfig config = new KeycloakServerConfig(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-b")) { config.setHost(args[++i]); } if (args[i].equals("-p")) { config.setPort(Integer.valueOf(args[++i])); } } if (System.getProperties().containsKey("resources")) { String resources = System.getProperty("resources"); if (resources == null || resources.equals("") || resources.equals("true")) { if (System.getProperties().containsKey("maven.home")) { resources = System.getProperty("user.dir").replaceFirst("testsuite.integration.*", ""); } else { for (String c : System.getProperty("java.class.path").split(File.pathSeparator)) { if (c.contains(File.separator + "testsuite" + File.separator + "integration")) { resources = c.replaceFirst("testsuite.integration.*", ""); } } } } File dir = new File(resources).getAbsoluteFile(); if (!dir.isDirectory() || !new File(dir, "admin-ui").isDirectory()) { throw new RuntimeException("Invalid resources directory"); } config.setResourcesHome(dir.getAbsolutePath()); } final KeycloakServer keycloak = new KeycloakServer(config); keycloak.sysout = true; keycloak.start(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-import")) { keycloak.importRealm(new FileInputStream(args[++i])); } } if (System.getProperties().containsKey("import")) { keycloak.importRealm(new FileInputStream(System.getProperty("import"))); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { keycloak.stop(); } }); }
#vulnerable code public static void main(String[] args) throws Throwable { KeycloakServerConfig config = new KeycloakServerConfig(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-b")) { config.setHost(args[++i]); } if (args[i].equals("-p")) { config.setPort(Integer.valueOf(args[++i])); } } if (System.getProperties().containsKey("resources")) { String resources = System.getProperty("resources"); if (resources == null || resources.equals("")) { for (String c : System.getProperty("java.class.path").split(File.pathSeparator)) { if (c.contains(File.separator + "testsuite" + File.separator + "integration")) { config.setResourcesHome(c.replaceFirst("testsuite.integration.*", "")); } } } else { config.setResourcesHome(resources); } } final KeycloakServer keycloak = new KeycloakServer(config); keycloak.sysout = true; keycloak.start(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-import")) { keycloak.importRealm(new FileInputStream(args[++i])); } } if (System.getProperties().containsKey("import")) { keycloak.importRealm(new FileInputStream(System.getProperty("import"))); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { keycloak.stop(); } }); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void verifyAccess(AccessToken token, RealmModel realm, ClientModel client, UserModel user) throws OAuthErrorException { ApplicationModel clientApp = (client instanceof ApplicationModel) ? (ApplicationModel)client : null; if (token.getRealmAccess() != null) { for (String roleName : token.getRealmAccess().getRoles()) { RoleModel role = realm.getRole(roleName); if (role == null) { throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid realm role " + roleName); } if (!user.hasRole(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for realm role: " + roleName); } if (!client.hasScope(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has realm scope: " + roleName); } } } if (token.getResourceAccess() != null) { for (Map.Entry<String, AccessToken.Access> entry : token.getResourceAccess().entrySet()) { ApplicationModel app = realm.getApplicationByName(entry.getKey()); if (app == null) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Application no longer exists", "Application no longer exists: " + entry.getKey()); } for (String roleName : entry.getValue().getRoles()) { RoleModel role = app.getRole(roleName); if (role == null) { throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown application role: " + roleName); } if (!user.hasRole(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for application role " + roleName); } if (clientApp != null && !clientApp.equals(app) && !client.hasScope(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has application scope" + roleName); } } } } }
#vulnerable code public void verifyAccess(AccessToken token, RealmModel realm, ClientModel client, UserModel user) throws OAuthErrorException { ApplicationModel clientApp = (client instanceof ApplicationModel) ? (ApplicationModel)client : null; if (token.getRealmAccess() != null) { for (String roleName : token.getRealmAccess().getRoles()) { RoleModel role = realm.getRole(roleName); if (role == null) { throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid realm role " + roleName); } if (!user.hasRole(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for realm role: " + roleName); } if (!client.hasScope(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has realm scope: " + roleName); } } } if (token.getResourceAccess() != null) { for (Map.Entry<String, AccessToken.Access> entry : token.getResourceAccess().entrySet()) { ApplicationModel app = realm.getApplicationByName(entry.getKey()); if (app == null) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Application no longer exists", "Application no longer exists: " + app.getName()); } for (String roleName : entry.getValue().getRoles()) { RoleModel role = app.getRole(roleName); if (role == null) { throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown application role: " + roleName); } if (!user.hasRole(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for application role " + roleName); } if (clientApp != null && !clientApp.equals(app) && !client.hasScope(role)) { throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has application scope" + roleName); } } } } } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void start() { if (started) { throw new IllegalStateException("Filter already started. Make sure to specify just keycloakConfigResolver or keycloakConfigFile but not both"); } if (keycloakConfigResolverClass != null) { Class<? extends KeycloakConfigResolver> resolverClass = loadResolverClass(); try { KeycloakConfigResolver resolver = resolverClass.newInstance(); log.info("Using " + resolver + " to resolve Keycloak configuration on a per-request basis."); this.deploymentContext = new AdapterDeploymentContext(resolver); } catch (Exception e) { throw new RuntimeException("Unable to instantiate resolver " + resolverClass); } } else { if (keycloakConfigFile == null) { throw new IllegalArgumentException("You need to specify either keycloakConfigResolverClass or keycloakConfigFile in configuration"); } InputStream is = loadKeycloakConfigFile(); KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is); deploymentContext = new AdapterDeploymentContext(kd); log.info("Keycloak is using a per-deployment configuration loaded from: " + keycloakConfigFile); } nodesRegistrationManagement = new NodesRegistrationManagement(); started = true; }
#vulnerable code protected void start() { if (started) { throw new IllegalStateException("Filter already started. Make sure to specify just keycloakConfigResolver or keycloakConfigFile but not both"); } if (keycloakConfigResolverClass != null) { Class<?> clazz; try { clazz = getClass().getClassLoader().loadClass(keycloakConfigResolverClass); } catch (ClassNotFoundException cnfe) { // Fallback to tccl try { clazz = Thread.currentThread().getContextClassLoader().loadClass(keycloakConfigResolverClass); } catch (ClassNotFoundException cnfe2) { throw new RuntimeException("Unable to find resolver class: " + keycloakConfigResolverClass); } } try { KeycloakConfigResolver resolver = (KeycloakConfigResolver) clazz.newInstance(); log.info("Using " + resolver + " to resolve Keycloak configuration on a per-request basis."); this.deploymentContext = new AdapterDeploymentContext(resolver); } catch (Exception e) { throw new RuntimeException("Unable to instantiate resolver " + clazz); } } else { if (keycloakConfigFile == null) { throw new IllegalArgumentException("You need to specify either keycloakConfigResolverClass or keycloakConfigFile in configuration"); } InputStream is = readConfigFile(); KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is); deploymentContext = new AdapterDeploymentContext(kd); log.info("Keycloak is using a per-deployment configuration loaded from: " + keycloakConfigFile); } nodesRegistrationManagement = new NodesRegistrationManagement(); started = true; } #location 31 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void checkKeycloakSession(Request request, HttpFacade facade) { if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) return; RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName()); if (session == null) return; // just in case session got serialized if (session.getDeployment() == null) session.setDeployment(deploymentContext.resolveDeployment(facade)); if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return; // FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will // not be updated boolean success = session.refreshExpiredToken(false); if (success && session.isActive()) return; // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session Session catalinaSession = request.getSessionInternal(); log.debugf("Cleanup and expire session %s after failed refresh", catalinaSession.getId()); catalinaSession.removeNote(KeycloakSecurityContext.class.getName()); request.setUserPrincipal(null); request.setAuthType(null); catalinaSession.setPrincipal(null); catalinaSession.setAuthType(null); catalinaSession.expire(); }
#vulnerable code protected void checkKeycloakSession(Request request, HttpFacade facade) { if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) return; RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName()); if (session == null) return; // just in case session got serialized if (session.getDeployment() == null) session.setDeployment(deploymentContext.resolveDeployment(facade)); if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return; // FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will // not be updated boolean success = session.refreshExpiredToken(false); if (success && session.isActive()) return; request.getSessionInternal().removeNote(KeycloakSecurityContext.class.getName()); request.setUserPrincipal(null); request.setAuthType(null); request.getSessionInternal().setPrincipal(null); request.getSessionInternal().setAuthType(null); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getPemFromKey(Key key) { StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(key); pemWriter.flush(); pemWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); return PemUtils.removeBeginEnd(s); }
#vulnerable code public static String getPemFromKey(Key key) { StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(key); pemWriter.flush(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); return PemUtils.removeBeginEnd(s); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void backchannelLogout(UserSessionModel userSession, ClientSessionModel clientSession) { ClientModel client = clientSession.getClient(); if (!(client instanceof ApplicationModel)) return; ApplicationModel app = (ApplicationModel)client; if (app.getManagementUrl() == null) return; SAML2LogoutRequestBuilder logoutBuilder = new SAML2LogoutRequestBuilder() .userPrincipal(userSession.getUser().getUsername()) .destination(client.getClientId()); if (requiresRealmSignature(client)) { logoutBuilder.signatureAlgorithm(getSignatureAlgorithm(client)) .signWith(realm.getPrivateKey(), realm.getPublicKey()) .signDocument(); } /* if (requiresEncryption(client)) { PublicKey publicKey = null; try { publicKey = PemUtils.decodePublicKey(client.getAttribute(ClientModel.PUBLIC_KEY)); } catch (Exception e) { logger.error("failed", e); return; } logoutBuilder.encrypt(publicKey); } */ String logoutRequestString = null; try { logoutRequestString = logoutBuilder.postBinding().encoded(); } catch (Exception e) { logger.warn("failed to send saml logout", e); return; } String adminUrl = ResourceAdminManager.getManagementUrl(uriInfo.getRequestUri(), app); ApacheHttpClient4Executor executor = ResourceAdminManager.createExecutor(); try { ClientRequest request = executor.createRequest(adminUrl); request.formParameter(GeneralConstants.SAML_REQUEST_KEY, logoutRequestString); request.formParameter(SAML2LogOutHandler.BACK_CHANNEL_LOGOUT, SAML2LogOutHandler.BACK_CHANNEL_LOGOUT); ClientResponse response = null; try { response = request.post(); response.releaseConnection(); // Undertow will redirect root urls not ending in "/" to root url + "/". Test for this weird behavior if (response.getStatus() == 302 && !adminUrl.endsWith("/")) { String redirect = (String)response.getHeaders().getFirst(HttpHeaders.LOCATION); String withSlash = adminUrl + "/"; if (withSlash.equals(redirect)) { request = executor.createRequest(withSlash); request.formParameter(GeneralConstants.SAML_REQUEST_KEY, logoutRequestString); request.formParameter(SAML2LogOutHandler.BACK_CHANNEL_LOGOUT, SAML2LogOutHandler.BACK_CHANNEL_LOGOUT); response = request.post(); response.releaseConnection(); } } } catch (Exception e) { logger.warn("failed to send saml logout", e); } } finally { executor.getHttpClient().getConnectionManager().shutdown(); } }
#vulnerable code @Override public void backchannelLogout(UserSessionModel userSession, ClientSessionModel clientSession) { ClientModel client = clientSession.getClient(); if (!(client instanceof ApplicationModel)) return; ApplicationModel app = (ApplicationModel)client; if (app.getManagementUrl() == null) return; SAML2LogoutRequestBuilder logoutBuilder = new SAML2LogoutRequestBuilder() .userPrincipal(userSession.getUser().getUsername()) .destination(client.getClientId()); if (requiresRealmSignature(client)) { logoutBuilder.signatureAlgorithm(getSignatureAlgorithm(client)); logoutBuilder.sign(realm.getPrivateKey(), realm.getPublicKey()); } /* if (requiresEncryption(client)) { PublicKey publicKey = null; try { publicKey = PemUtils.decodePublicKey(client.getAttribute(ClientModel.PUBLIC_KEY)); } catch (Exception e) { logger.error("failed", e); return; } logoutBuilder.encrypt(publicKey); } */ String logoutRequestString = null; try { logoutRequestString = logoutBuilder.postBinding().encoded(); } catch (Exception e) { logger.warn("failed to send saml logout", e); return; } String adminUrl = ResourceAdminManager.getManagementUrl(uriInfo.getRequestUri(), app); ApacheHttpClient4Executor executor = ResourceAdminManager.createExecutor(); try { ClientRequest request = executor.createRequest(adminUrl); request.formParameter(GeneralConstants.SAML_REQUEST_KEY, logoutRequestString); request.formParameter(SAML2LogOutHandler.BACK_CHANNEL_LOGOUT, SAML2LogOutHandler.BACK_CHANNEL_LOGOUT); ClientResponse response = null; try { response = request.post(); response.releaseConnection(); // Undertow will redirect root urls not ending in "/" to root url + "/". Test for this weird behavior if (response.getStatus() == 302 && !adminUrl.endsWith("/")) { String redirect = (String)response.getHeaders().getFirst(HttpHeaders.LOCATION); String withSlash = adminUrl + "/"; if (withSlash.equals(redirect)) { request = executor.createRequest(withSlash); request.formParameter(GeneralConstants.SAML_REQUEST_KEY, logoutRequestString); request.formParameter(SAML2LogOutHandler.BACK_CHANNEL_LOGOUT, SAML2LogOutHandler.BACK_CHANNEL_LOGOUT); response = request.post(); response.releaseConnection(); } } } catch (Exception e) { logger.warn("failed to send saml logout", e); } } finally { executor.getHttpClient().getConnectionManager().shutdown(); } } #location 51 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getPemFromCertificate(X509Certificate certificate) { StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(certificate); pemWriter.flush(); pemWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); return PemUtils.removeBeginEnd(s); }
#vulnerable code public static String getPemFromCertificate(X509Certificate certificate) { StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(certificate); pemWriter.flush(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); return PemUtils.removeBeginEnd(s); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); addModules(deploymentUnit); }
#vulnerable code @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); KeycloakAdapterConfigService service = KeycloakAdapterConfigService.find(phaseContext.getServiceRegistry()); if (service.isKeycloakDeployment(deploymentUnit.getName())) { addModules(deploymentUnit); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void copySnapshot() { int length = dirtyIndex.get(); if (length <= dirtySize) { for (int i = 0; i < length; i++) { int index = dirtyArray.get(i); this.snapshot[index] = getLive(i); } } else { for (int i = 0; i < snapshot.length; i++) { this.snapshot[i] = getLive(i); } } }
#vulnerable code @Override public void copySnapshot() { int length = dirtyIndex.get(); if (length <= dirtyArray.length) { for (int i = 0; i < length; i++) { int index = dirtyArray[i]; this.snapshot[index] = live[index]; } } else { for (int i = 0; i < live.length; i++) { this.snapshot[i] = live[i]; } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @DelayedWrite public short set(int index, short value) { boolean success = false; int divIndex = index >> 1; boolean isZero = (index & 0x1) == 0; short one; short zero; short old = 0; while (!success) { int packed = live.get(divIndex); if (isZero) { old = unpackZero(packed); one = unpackOne(packed); zero = value; } else { old = unpackOne(packed); one = value; zero = unpackZero(packed); } success = live.compareAndSet(divIndex, packed, pack(zero, one)); } markDirty(index); return old; }
#vulnerable code @DelayedWrite public short set(int index, short value) { synchronized (live) { live[index] = value; } int localDirtyIndex = dirtyIndex.getAndIncrement(); if (localDirtyIndex < dirtyArray.length) { dirtyArray[localDirtyIndex] = index; } return snapshot[index]; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void copySnapshot() { int length = dirtyIndex.get(); if (length <= dirtySize) { for (int i = 0; i < length; i++) { int index = dirtyArray.get(i); this.snapshot[index] = getLive(i); } } else { for (int i = 0; i < snapshot.length; i++) { this.snapshot[i] = getLive(i); } } }
#vulnerable code @Override public void copySnapshot() { int length = dirtyIndex.get(); if (length <= dirtyArray.length) { for (int i = 0; i < length; i++) { int index = dirtyArray[i]; this.snapshot[index] = live[index]; } } else { for (int i = 0; i < live.length; i++) { this.snapshot[i] = live[i]; } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @DelayedWrite public short set(int index, short value) { boolean success = false; int divIndex = index >> 1; boolean isZero = (index & 0x1) == 0; short one; short zero; short old = 0; while (!success) { int packed = live.get(divIndex); if (isZero) { old = unpackZero(packed); one = unpackOne(packed); zero = value; } else { old = unpackOne(packed); one = value; zero = unpackZero(packed); } success = live.compareAndSet(divIndex, packed, pack(zero, one)); } markDirty(index); return old; }
#vulnerable code @DelayedWrite public short set(int index, short value) { synchronized (live) { live[index] = value; } int localDirtyIndex = dirtyIndex.getAndIncrement(); if (localDirtyIndex < dirtyArray.length) { dirtyArray[localDirtyIndex] = index; } return snapshot[index]; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static KeePassDatabase getInstance(File keePassDatabaseFile) { if(keePassDatabaseFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass database file."); } InputStream keePassDatabaseStream = null; try { keePassDatabaseStream = new FileInputStream(keePassDatabaseFile); return getInstance(keePassDatabaseStream); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The KeePass database file could not be found. You must provide a valid KeePass database file."); } finally { if (keePassDatabaseStream != null) { try { keePassDatabaseStream.close(); } catch (IOException e) { // Ignore } } } }
#vulnerable code public static KeePassDatabase getInstance(File keePassDatabaseFile) { if(keePassDatabaseFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass database file."); } try { return getInstance(new FileInputStream(keePassDatabaseFile)); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The KeePass database file could not be found. You must provide a valid KeePass database file."); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata() throws FileNotFoundException { KeePassFile keePassFile = parseKeePassXml(); Assert.assertEquals("KeePass", keePassFile.getMeta().getGenerator()); Assert.assertEquals("TestDatabase", keePassFile.getMeta().getDatabaseName()); Assert.assertEquals("Just a sample db", keePassFile.getMeta().getDatabaseDescription()); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseNameChanged().getTime())); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseDescriptionChanged().getTime())); Assert.assertEquals(365, keePassFile.getMeta().getMaintenanceHistoryDays()); Assert.assertEquals(true, keePassFile.getMeta().getRecycleBinEnabled()); Assert.assertEquals("AAAAAAAAAAAAAAAAAAAAAA==", keePassFile.getMeta().getRecycleBinUuid()); Assert.assertEquals("2014-11-22 18:58:56", dateFormatter.format(keePassFile.getMeta().getRecycleBinChanged().getTime())); Assert.assertEquals(10, keePassFile.getMeta().getHistoryMaxItems()); Assert.assertEquals(6291456, keePassFile.getMeta().getHistoryMaxSize()); }
#vulnerable code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); Assert.assertEquals("KeePass", keePassFile.getMeta().getGenerator()); Assert.assertEquals("TestDatabase", keePassFile.getMeta().getDatabaseName()); Assert.assertEquals("Just a sample db", keePassFile.getMeta().getDatabaseDescription()); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseNameChanged().getTime())); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseDescriptionChanged().getTime())); Assert.assertEquals(365, keePassFile.getMeta().getMaintenanceHistoryDays()); Assert.assertEquals(true, keePassFile.getMeta().getRecycleBinEnabled()); Assert.assertEquals("AAAAAAAAAAAAAAAAAAAAAA==", keePassFile.getMeta().getRecycleBinUuid()); Assert.assertEquals("2014-11-22 18:58:56", dateFormatter.format(keePassFile.getMeta().getRecycleBinChanged().getTime())); Assert.assertEquals(10, keePassFile.getMeta().getHistoryMaxItems()); Assert.assertEquals(6291456, keePassFile.getMeta().getHistoryMaxSize()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isPasswordProtected() { return getPropertyByName(PASSWORD).isProtected(); }
#vulnerable code public boolean isPasswordProtected() { return getPropertyByName(PASSWORD).isProtected(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectGroups() throws FileNotFoundException { KeePassFile keePassFile = parseKeePassXml(); List<Group> groups = keePassFile.getTopGroups(); Assert.assertNotNull(groups); Assert.assertEquals(6, groups.size()); Assert.assertEquals("General", groups.get(0).getName()); Assert.assertEquals("FqvMJ8yjlUSAEt9OmNSj2A==", groups.get(0).getUuid()); Assert.assertEquals("Windows", groups.get(1).getName()); Assert.assertEquals("rXt7D+EM/0qW1rgPB4g5nw==", groups.get(1).getUuid()); Assert.assertEquals("Network", groups.get(2).getName()); Assert.assertEquals("DwdAaKn4tEyXFlU56/2UBQ==", groups.get(2).getUuid()); Assert.assertEquals("Internet", groups.get(3).getName()); Assert.assertEquals("COgUrPt5P0676DeyZn/auQ==", groups.get(3).getUuid()); Assert.assertEquals("eMail", groups.get(4).getName()); Assert.assertEquals("/xWfOfnC6ki76sNhrZR7rw==", groups.get(4).getUuid()); Assert.assertEquals("Homebanking", groups.get(5).getName()); Assert.assertEquals("Rdjt21Jla0+E5Q9ElJHw1g==", groups.get(5).getUuid()); }
#vulnerable code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectGroups() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); List<Group> groups = keePassFile.getTopGroups(); Assert.assertNotNull(groups); Assert.assertEquals(6, groups.size()); Assert.assertEquals("General", groups.get(0).getName()); Assert.assertEquals("FqvMJ8yjlUSAEt9OmNSj2A==", groups.get(0).getUuid()); Assert.assertEquals("Windows", groups.get(1).getName()); Assert.assertEquals("rXt7D+EM/0qW1rgPB4g5nw==", groups.get(1).getUuid()); Assert.assertEquals("Network", groups.get(2).getName()); Assert.assertEquals("DwdAaKn4tEyXFlU56/2UBQ==", groups.get(2).getUuid()); Assert.assertEquals("Internet", groups.get(3).getName()); Assert.assertEquals("COgUrPt5P0676DeyZn/auQ==", groups.get(3).getUuid()); Assert.assertEquals("eMail", groups.get(4).getName()); Assert.assertEquals("/xWfOfnC6ki76sNhrZR7rw==", groups.get(4).getUuid()); Assert.assertEquals("Homebanking", groups.get(5).getName()); Assert.assertEquals("Rdjt21Jla0+E5Q9ElJHw1g==", groups.get(5).getUuid()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isTitleProtected() { return getPropertyByName(TITLE).isProtected(); }
#vulnerable code public boolean isTitleProtected() { return getPropertyByName(TITLE).isProtected(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenWritingDatabaseFileShouldBeAbleToReadItAlso() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new KeePassDatabaseXmlParser().fromXml(fileInputStream); new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), keePassFile); FileOutputStream file = new FileOutputStream("target/test-classes/writeDatabase.kdbx"); KeePassDatabase.write(keePassFile, "abcdefg", file); KeePassDatabase database = KeePassDatabase.getInstance("target/test-classes/writeDatabase.kdbx"); KeePassHeader header = database.getHeader(); Assert.assertEquals(CompressionAlgorithm.Gzip, header.getCompression()); Assert.assertEquals(CrsAlgorithm.Salsa20, header.getCrsAlgorithm()); Assert.assertEquals(8000, header.getTransformRounds()); KeePassFile openDatabase = database.openDatabase("abcdefg"); Entry sampleEntry = openDatabase.getEntryByTitle("Sample Entry"); Assert.assertEquals("User Name", sampleEntry.getUsername()); Assert.assertEquals("Password", sampleEntry.getPassword()); Entry sampleEntryTwo = openDatabase.getEntryByTitle("Sample Entry #2"); Assert.assertEquals("Michael321", sampleEntryTwo.getUsername()); Assert.assertEquals("12345", sampleEntryTwo.getPassword()); }
#vulnerable code @Test public void whenWritingDatabaseFileShouldBeAbleToReadItAlso() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new KeePassDatabaseXmlParser().fromXml(fileInputStream, Salsa20.createInstance(protectedStreamKey)); new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), keePassFile); FileOutputStream file = new FileOutputStream("target/test-classes/writeDatabase.kdbx"); KeePassDatabase.write(keePassFile, "abcdefg", file); KeePassDatabase database = KeePassDatabase.getInstance("target/test-classes/writeDatabase.kdbx"); KeePassHeader header = database.getHeader(); Assert.assertEquals(CompressionAlgorithm.Gzip, header.getCompression()); Assert.assertEquals(CrsAlgorithm.Salsa20, header.getCrsAlgorithm()); Assert.assertEquals(8000, header.getTransformRounds()); KeePassFile openDatabase = database.openDatabase("abcdefg"); Entry sampleEntry = openDatabase.getEntryByTitle("Sample Entry"); Assert.assertEquals("User Name", sampleEntry.getUsername()); Assert.assertEquals("Password", sampleEntry.getPassword()); Entry sampleEntryTwo = openDatabase.getEntryByTitle("Sample Entry #2"); Assert.assertEquals("Michael321", sampleEntryTwo.getUsername()); Assert.assertEquals("12345", sampleEntryTwo.getPassword()); } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private byte[] processDatabaseEncryption(boolean encrypt, byte[] database, KeePassHeader header, byte[] aesKey) throws IOException { byte[] metaData = new byte[KeePassHeader.VERSION_SIGNATURE_LENGTH + header.getHeaderSize()]; SafeInputStream inputStream = new SafeInputStream(new BufferedInputStream(new ByteArrayInputStream(database))); inputStream.readSafe(metaData); byte[] payload = StreamUtils.toByteArray(inputStream); byte[] processedPayload; if (encrypt) { processedPayload = Aes.encrypt(aesKey, header.getEncryptionIV(), payload); } else { processedPayload = Aes.decrypt(aesKey, header.getEncryptionIV(), payload); } ByteArrayOutputStream output = new ByteArrayOutputStream(); output.write(metaData); output.write(processedPayload); return output.toByteArray(); }
#vulnerable code private byte[] processDatabaseEncryption(boolean encrypt, byte[] database, KeePassHeader header, byte[] aesKey) throws IOException { byte[] metaData = new byte[KeePassHeader.VERSION_SIGNATURE_LENGTH + header.getHeaderSize()]; BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(database)); bufferedInputStream.read(metaData); byte[] payload = StreamUtils.toByteArray(bufferedInputStream); byte[] processedPayload; if (encrypt) { processedPayload = Aes.encrypt(aesKey, header.getEncryptionIV(), payload); } else { processedPayload = Aes.decrypt(aesKey, header.getEncryptionIV(), payload); } ByteArrayOutputStream output = new ByteArrayOutputStream(); output.write(metaData); output.write(processedPayload); return output.toByteArray(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private KeePassFile parseKeePassXml() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new KeePassDatabaseXmlParser().fromXml(fileInputStream); new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), keePassFile); return keePassFile; }
#vulnerable code private KeePassFile parseKeePassXml() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new KeePassDatabaseXmlParser().fromXml(fileInputStream, Salsa20.createInstance(protectedStreamKey)); new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), keePassFile); return keePassFile; } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectEntries() throws FileNotFoundException { KeePassFile keePassFile = parseKeePassXml(); List<Entry> entries = keePassFile.getTopEntries(); Assert.assertNotNull(entries); Assert.assertEquals(2, entries.size()); Assert.assertEquals("libdLW88cU6BvrPQlvKqMA==", entries.get(0).getUuid()); Assert.assertEquals(5, entries.get(0).getProperties().size()); Assert.assertEquals("Sample Entry", entries.get(0).getTitle()); Assert.assertEquals("http://keepass.info/", entries.get(0).getUrl()); Assert.assertEquals("User Name", entries.get(0).getUsername()); Assert.assertEquals("Notes", entries.get(0).getNotes()); Assert.assertEquals("Password", entries.get(0).getPassword()); }
#vulnerable code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectEntries() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); List<Entry> entries = keePassFile.getTopEntries(); Assert.assertNotNull(entries); Assert.assertEquals(2, entries.size()); Assert.assertEquals("libdLW88cU6BvrPQlvKqMA==", entries.get(0).getUuid()); Assert.assertEquals(5, entries.get(0).getProperties().size()); Assert.assertEquals("Sample Entry", entries.get(0).getTitle()); Assert.assertEquals("http://keepass.info/", entries.get(0).getUrl()); Assert.assertEquals("User Name", entries.get(0).getUsername()); Assert.assertEquals("Notes", entries.get(0).getNotes()); Assert.assertEquals("Password", entries.get(0).getPassword()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expected = UnsupportedOperationException.class) public void whenVersionIsNotSupportedShouldThrowException() throws IOException { KeePassHeader header = new KeePassHeader(new RandomGenerator()); // unsupported format --> e.g. v5 byte[] rawHeader = ByteUtils.hexStringToByteArray("03D9A29A67FB4BB501000500"); header.checkVersionSupport(rawHeader); }
#vulnerable code @Test(expected = UnsupportedOperationException.class) public void whenVersionIsNotSupportedShouldThrowException() throws IOException { KeePassHeader header = new KeePassHeader(new RandomGenerator()); // new v4 format FileInputStream fileInputStream = new FileInputStream(ResourceUtils.getResource("DatabaseWithV4Format.kdbx")); byte[] rawHeader = StreamUtils.toByteArray(fileInputStream); header.checkVersionSupport(rawHeader); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private byte[] processDatabaseEncryption(boolean encrypt, byte[] database, KeePassHeader header, byte[] aesKey) throws IOException { byte[] metaData = new byte[KeePassHeader.VERSION_SIGNATURE_LENGTH + header.getHeaderSize()]; SafeInputStream inputStream = new SafeInputStream(new BufferedInputStream(new ByteArrayInputStream(database))); inputStream.readSafe(metaData); byte[] payload = StreamUtils.toByteArray(inputStream); byte[] processedPayload; if (encrypt) { processedPayload = Aes.encrypt(aesKey, header.getEncryptionIV(), payload); } else { processedPayload = Aes.decrypt(aesKey, header.getEncryptionIV(), payload); } ByteArrayOutputStream output = new ByteArrayOutputStream(); output.write(metaData); output.write(processedPayload); return output.toByteArray(); }
#vulnerable code private byte[] processDatabaseEncryption(boolean encrypt, byte[] database, KeePassHeader header, byte[] aesKey) throws IOException { byte[] metaData = new byte[KeePassHeader.VERSION_SIGNATURE_LENGTH + header.getHeaderSize()]; BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(database)); bufferedInputStream.read(metaData); byte[] payload = StreamUtils.toByteArray(bufferedInputStream); byte[] processedPayload; if (encrypt) { processedPayload = Aes.encrypt(aesKey, header.getEncryptionIV(), payload); } else { processedPayload = Aes.decrypt(aesKey, header.getEncryptionIV(), payload); } ByteArrayOutputStream output = new ByteArrayOutputStream(); output.write(metaData); output.write(processedPayload); return output.toByteArray(); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenWritingKeePassFileShouldBeAbleToReadItAgain() throws IOException { // Read decrypted and write again FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassDatabaseXmlParser parser = new KeePassDatabaseXmlParser(); KeePassFile keePassFile = parser.fromXml(fileInputStream); ByteArrayOutputStream outputStream = parser.toXml(keePassFile); OutputStream fileOutputStream = new FileOutputStream("target/test-classes/testDatabase_decrypted2.xml"); outputStream.writeTo(fileOutputStream); // Read written file FileInputStream writtenInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted2.xml"); KeePassFile writtenKeePassFile = parser.fromXml(writtenInputStream); new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), writtenKeePassFile); Assert.assertEquals("Password", writtenKeePassFile.getEntryByTitle("Sample Entry").getPassword()); }
#vulnerable code @Test public void whenWritingKeePassFileShouldBeAbleToReadItAgain() throws IOException { // Read decrypted and write again FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassDatabaseXmlParser parser = new KeePassDatabaseXmlParser(); KeePassFile keePassFile = parser.fromXml(fileInputStream, Salsa20.createInstance(protectedStreamKey)); new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), keePassFile); ByteArrayOutputStream outputStream = parser.toXml(keePassFile, Salsa20.createInstance(protectedStreamKey)); OutputStream fileOutputStream = new FileOutputStream("target/test-classes/testDatabase_decrypted2.xml"); outputStream.writeTo(fileOutputStream); // Read written file FileInputStream writtenInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted2.xml"); KeePassFile writtenKeePassFile = parser.fromXml(writtenInputStream, Salsa20.createInstance(protectedStreamKey)); new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), writtenKeePassFile); Assert.assertEquals("Password", writtenKeePassFile.getEntryByTitle("Sample Entry").getPassword()); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public KeePassFile openDatabase(String password) { try { byte[] passwordBytes = password.getBytes("UTF-8"); byte[] hashedPassword = Sha256.hash(passwordBytes); return decryptAndParseDatabase(hashedPassword); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException("The encoding UTF-8 is not supported"); } }
#vulnerable code public KeePassFile openDatabase(String password) { try { byte[] aesDecryptedDbFile = decrypter.decryptDatabase(password, keepassHeader, keepassFile); byte[] startBytes = new byte[32]; ByteArrayInputStream decryptedStream = new ByteArrayInputStream(aesDecryptedDbFile); decryptedStream.read(startBytes); // compare startBytes if(!Arrays.equals(keepassHeader.getStreamStartBytes(), startBytes)) { throw new KeepassDatabaseUnreadable("The keepass database file seems to be corrupt or cannot be decrypted."); } HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); byte[] decompressed = hashedBlockBytes; // unzip if necessary if(keepassHeader.getCompression().equals(CompressionAlgorithm.Gzip)) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(hashedBlockBytes)); decompressed = StreamUtils.toByteArray(gzipInputStream); } ProtectedStringCrypto protectedStringCrypto; if(keepassHeader.getCrsAlgorithm().equals(CrsAlgorithm.Salsa20)) { protectedStringCrypto = Salsa20.createInstance(keepassHeader.getProtectedStreamKey()); } else { throw new UnsupportedOperationException("Only Salsa20 is supported as CrsAlgorithm at the moment!"); } return xmlParser.parse(new ByteArrayInputStream(decompressed), protectedStringCrypto); } catch (IOException e) { throw new RuntimeException("Could not open database file", e); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectEntries() throws FileNotFoundException { KeePassFile keePassFile = parseKeePassXml(); List<Entry> entries = keePassFile.getTopEntries(); Assert.assertNotNull(entries); Assert.assertEquals(2, entries.size()); Assert.assertEquals("libdLW88cU6BvrPQlvKqMA==", entries.get(0).getUuid()); Assert.assertEquals(5, entries.get(0).getProperties().size()); Assert.assertEquals("Sample Entry", entries.get(0).getTitle()); Assert.assertEquals("http://keepass.info/", entries.get(0).getUrl()); Assert.assertEquals("User Name", entries.get(0).getUsername()); Assert.assertEquals("Notes", entries.get(0).getNotes()); Assert.assertEquals("Password", entries.get(0).getPassword()); }
#vulnerable code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectEntries() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); List<Entry> entries = keePassFile.getTopEntries(); Assert.assertNotNull(entries); Assert.assertEquals(2, entries.size()); Assert.assertEquals("libdLW88cU6BvrPQlvKqMA==", entries.get(0).getUuid()); Assert.assertEquals(5, entries.get(0).getProperties().size()); Assert.assertEquals("Sample Entry", entries.get(0).getTitle()); Assert.assertEquals("http://keepass.info/", entries.get(0).getUrl()); Assert.assertEquals("User Name", entries.get(0).getUsername()); Assert.assertEquals("Notes", entries.get(0).getNotes()); Assert.assertEquals("Password", entries.get(0).getPassword()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private byte[] unHashBlockStream(SafeInputStream decryptedStream) throws IOException { HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); return StreamUtils.toByteArray(hashedBlockInputStream); }
#vulnerable code private byte[] unHashBlockStream(SafeInputStream decryptedStream) throws IOException { HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); return hashedBlockBytes; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void checkVersionSupport(byte[] keepassFile) throws IOException { BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; int readBytes = inputStream.read(signature); if(readBytes == -1) { throw new UnsupportedOperationException("Could not read KeePass header. The provided file seems to be no KeePass database file!"); } ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); if (signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1_INT && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2_INT) { return; } else if (signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1_INT && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2_INT) { throw new UnsupportedOperationException( "The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); } else { throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); } }
#vulnerable code public void checkVersionSupport(byte[] keepassFile) throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; bufferedInputStream.read(signature); ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); if (signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1_INT && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2_INT) { return; } else if (signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1_INT && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2_INT) { throw new UnsupportedOperationException( "The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); } else { throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public KeePassFile openDatabase(String password) { try { byte[] passwordBytes = password.getBytes("UTF-8"); byte[] hashedPassword = Sha256.hash(passwordBytes); return decryptAndParseDatabase(hashedPassword); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException("The encoding UTF-8 is not supported"); } }
#vulnerable code public KeePassFile openDatabase(String password) { try { byte[] aesDecryptedDbFile = decrypter.decryptDatabase(password, keepassHeader, keepassFile); byte[] startBytes = new byte[32]; ByteArrayInputStream decryptedStream = new ByteArrayInputStream(aesDecryptedDbFile); decryptedStream.read(startBytes); // compare startBytes if(!Arrays.equals(keepassHeader.getStreamStartBytes(), startBytes)) { throw new KeepassDatabaseUnreadable("The keepass database file seems to be corrupt or cannot be decrypted."); } HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); byte[] decompressed = hashedBlockBytes; // unzip if necessary if(keepassHeader.getCompression().equals(CompressionAlgorithm.Gzip)) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(hashedBlockBytes)); decompressed = StreamUtils.toByteArray(gzipInputStream); } ProtectedStringCrypto protectedStringCrypto; if(keepassHeader.getCrsAlgorithm().equals(CrsAlgorithm.Salsa20)) { protectedStringCrypto = Salsa20.createInstance(keepassHeader.getProtectedStreamKey()); } else { throw new UnsupportedOperationException("Only Salsa20 is supported as CrsAlgorithm at the moment!"); } return xmlParser.parse(new ByteArrayInputStream(decompressed), protectedStringCrypto); } catch (IOException e) { throw new RuntimeException("Could not open database file", e); } } #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 whenInputIsKeyFileShouldParseFileAndReturnCorrectData() throws IOException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/DatabaseWithKeyfile.key"); byte[] keyFileContent = StreamUtils.toByteArray(fileInputStream); KeyFile keyFile = new KeyFileXmlParser().fromXml(keyFileContent); Assert.assertEquals("RP+rYNZL4lrGtDMBPzOuctlh3NAutSG5KGsT38C+qPQ=", keyFile.getKey().getData()); }
#vulnerable code @Test public void whenInputIsKeyFileShouldParseFileAndReturnCorrectData() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/DatabaseWithKeyfile.key"); KeyFile keyFile = new KeyFileXmlParser().fromXml(fileInputStream); Assert.assertEquals("RP+rYNZL4lrGtDMBPzOuctlh3NAutSG5KGsT38C+qPQ=", keyFile.getKey().getData()); } #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 whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata() throws FileNotFoundException { KeePassFile keePassFile = parseKeePassXml(); Assert.assertEquals("KeePass", keePassFile.getMeta().getGenerator()); Assert.assertEquals("TestDatabase", keePassFile.getMeta().getDatabaseName()); Assert.assertEquals("Just a sample db", keePassFile.getMeta().getDatabaseDescription()); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseNameChanged().getTime())); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseDescriptionChanged().getTime())); Assert.assertEquals(365, keePassFile.getMeta().getMaintenanceHistoryDays()); Assert.assertEquals(true, keePassFile.getMeta().getRecycleBinEnabled()); Assert.assertEquals("AAAAAAAAAAAAAAAAAAAAAA==", keePassFile.getMeta().getRecycleBinUuid()); Assert.assertEquals("2014-11-22 18:58:56", dateFormatter.format(keePassFile.getMeta().getRecycleBinChanged().getTime())); Assert.assertEquals(10, keePassFile.getMeta().getHistoryMaxItems()); Assert.assertEquals(6291456, keePassFile.getMeta().getHistoryMaxSize()); }
#vulnerable code @Test public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); Assert.assertEquals("KeePass", keePassFile.getMeta().getGenerator()); Assert.assertEquals("TestDatabase", keePassFile.getMeta().getDatabaseName()); Assert.assertEquals("Just a sample db", keePassFile.getMeta().getDatabaseDescription()); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseNameChanged().getTime())); Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseDescriptionChanged().getTime())); Assert.assertEquals(365, keePassFile.getMeta().getMaintenanceHistoryDays()); Assert.assertEquals(true, keePassFile.getMeta().getRecycleBinEnabled()); Assert.assertEquals("AAAAAAAAAAAAAAAAAAAAAA==", keePassFile.getMeta().getRecycleBinUuid()); Assert.assertEquals("2014-11-22 18:58:56", dateFormatter.format(keePassFile.getMeta().getRecycleBinChanged().getTime())); Assert.assertEquals(10, keePassFile.getMeta().getHistoryMaxItems()); Assert.assertEquals(6291456, keePassFile.getMeta().getHistoryMaxSize()); } #location 16 #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) { usage1(); //usage2(); }
#vulnerable code public static void main(String[] args) { String allExtractRegularUrl = "http://localhost:8080/HtmlExtractorServer/api/all_extract_regular.jsp"; String redisHost = "localhost"; int redisPort = 6379; HtmlExtractor htmlExtractor = HtmlExtractor.getInstance(allExtractRegularUrl, redisHost, redisPort); String url = "http://money.163.com/08/1219/16/4THR2TMP002533QK.html"; List<ExtractResult> extractResults = htmlExtractor.extract(url, "gb2312"); int i = 1; for (ExtractResult extractResult : extractResults) { System.out.println((i++) + "、网页 " + extractResult.getUrl() + " 的抽取结果"); for(ExtractResultItem extractResultItem : extractResult.getExtractResultItems()){ System.out.print("\t"+extractResultItem.getField()+" = "+extractResultItem.getValue()); } System.out.println("\tdescription = "+extractResult.getDescription()); System.out.println("\tkeywords = "+extractResult.getKeywords()); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { //下面的三种方法代表了3种不同的使用模式,只能单独使用 //usage1(); usage2(); //usage3(); }
#vulnerable code public static void main(String[] args) { //下面的三种方法代表了3种不同的使用模式,只能单独使用 //usage1(); //usage2(); usage3(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAverageAll() { List<Tuple> expected = computeExpected("SELECT AVG(totalprice) FROM orders", DOUBLE); TupleStream price = createTupleStream(ordersData, Column.ORDER_TOTALPRICE, DOUBLE); AggregationOperator aggregation = new AggregationOperator(price, AverageAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); }
#vulnerable code @Test public void testAverageAll() { List<Tuple> expected = computeExpected("SELECT AVG(totalprice) FROM orders", DOUBLE); TupleStream price = createBlockStream(ordersData, Column.ORDER_TOTALPRICE, DOUBLE); AggregationOperator aggregation = new AggregationOperator(price, AverageAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Tuple createTuple(String value) { TupleInfo tupleInfo = new TupleInfo(VARIABLE_BINARY); Tuple tuple = tupleInfo.builder() .append(Slices.wrappedBuffer(value.getBytes(UTF_8))) .build(); return tuple; }
#vulnerable code private Tuple createTuple(String value) { byte[] bytes = value.getBytes(UTF_8); Slice slice = Slices.allocate(bytes.length + SIZE_OF_SHORT); slice.output() .appendShort(bytes.length + 2) .appendBytes(bytes); return new Tuple(slice, new TupleInfo(VARIABLE_BINARY)); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCountAll() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM orders", FIXED_INT_64); TupleStream orders = createTupleStream(ordersData, Column.ORDER_ORDERKEY, FIXED_INT_64); AggregationOperator aggregation = new AggregationOperator(orders, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); }
#vulnerable code @Test public void testCountAll() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM orders", FIXED_INT_64); TupleStream orders = createBlockStream(ordersData, Column.ORDER_ORDERKEY, FIXED_INT_64); AggregationOperator aggregation = new AggregationOperator(orders, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void writeTo(List<UncompressedBlock> blocks, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream output) throws IOException, WebApplicationException { OutputStreamSliceOutput sliceOutput = new OutputStreamSliceOutput(output); for (UncompressedBlock block : blocks) { Slice slice = block.getSlice(); sliceOutput.appendInt(slice.length()) .appendInt(block.getCount()) .appendLong(block.getRange().getStart()) .appendBytes(slice) .flush(); } }
#vulnerable code @Override public void writeTo(List<UncompressedBlock> blocks, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream output) throws IOException, WebApplicationException { for (UncompressedBlock block : blocks) { Slice slice = block.getSlice(); // write header ByteArraySlice blockHeader = Slices.allocate(SIZE_OF_INT + SIZE_OF_INT + SIZE_OF_LONG); blockHeader.output() .appendInt(slice.length()) .appendInt(block.getCount()) .appendLong(block.getRange().getStart()); output.write(blockHeader.getRawArray()); // write slice slice.getBytes(0, output, slice.length()); } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCountAllWithComparison() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM lineitem WHERE tax < discount", FIXED_INT_64); TupleStream discount = createTupleStream(lineitemData, Column.LINEITEM_DISCOUNT, DOUBLE); TupleStream tax = createTupleStream(lineitemData, Column.LINEITEM_TAX, DOUBLE); ComparisonOperator comparison = new ComparisonOperator(tax, discount, new DoubleLessThanComparison()); AggregationOperator aggregation = new AggregationOperator(comparison, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); }
#vulnerable code @Test public void testCountAllWithComparison() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM lineitem WHERE tax < discount", FIXED_INT_64); TupleStream discount = createBlockStream(lineitemData, Column.LINEITEM_DISCOUNT, DOUBLE); TupleStream tax = createBlockStream(lineitemData, Column.LINEITEM_TAX, DOUBLE); ComparisonOperator comparison = new ComparisonOperator(tax, discount, new DoubleLessThanComparison()); AggregationOperator aggregation = new AggregationOperator(comparison, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void writeTo(UncompressedBlock block, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream output) throws IOException, WebApplicationException { Slice slice = block.getSlice(); new OutputStreamSliceOutput(output) .appendInt(slice.length()) .appendInt(block.getCount()) .appendLong(block.getRange().getStart()) .appendBytes(slice); }
#vulnerable code @Override public void writeTo(UncompressedBlock block, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream output) throws IOException, WebApplicationException { Slice slice = block.getSlice(); // write header ByteArraySlice header = Slices.allocate(SIZE_OF_INT + SIZE_OF_INT + SIZE_OF_LONG); header.output() .appendInt(slice.length()) .appendInt(block.getCount()) .appendLong(block.getRange().getStart()); output.write(header.getRawArray()); // write slice slice.getBytes(0, output, slice.length()); } #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 testCountAllWithPredicate() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM orders WHERE orderstatus = 'F'", FIXED_INT_64); TupleStream orderStatus = createTupleStream(ordersData, Column.ORDER_ORDERSTATUS, VARIABLE_BINARY); ApplyPredicateOperator filtered = new ApplyPredicateOperator(orderStatus, new Predicate<Cursor>() { @Override public boolean apply(Cursor input) { return input.getSlice(0).equals(Slices.copiedBuffer("F", Charsets.UTF_8)); } }); AggregationOperator aggregation = new AggregationOperator(filtered, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); }
#vulnerable code @Test public void testCountAllWithPredicate() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM orders WHERE orderstatus = 'F'", FIXED_INT_64); TupleStream orderStatus = createBlockStream(ordersData, Column.ORDER_ORDERSTATUS, VARIABLE_BINARY); ApplyPredicateOperator filtered = new ApplyPredicateOperator(orderStatus, new Predicate<Cursor>() { @Override public boolean apply(Cursor input) { return input.getSlice(0).equals(Slices.copiedBuffer("F", Charsets.UTF_8)); } }); AggregationOperator aggregation = new AggregationOperator(filtered, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSelectWithComparison() { List<Tuple> expected = computeExpected("SELECT orderkey FROM lineitem WHERE tax < discount", FIXED_INT_64); RowSourceBuilder orderKey = createTupleStream(lineitemData, Column.LINEITEM_ORDERKEY, FIXED_INT_64); TupleStream discount = createTupleStream(lineitemData, Column.LINEITEM_DISCOUNT, DOUBLE); TupleStream tax = createTupleStream(lineitemData, Column.LINEITEM_TAX, DOUBLE); ComparisonOperator comparison = new ComparisonOperator(tax, discount, new DoubleLessThanComparison()); FilterOperator result = new FilterOperator(orderKey.getTupleInfo(), orderKey, comparison); assertEqualsIgnoreOrder(tuples(result), expected); }
#vulnerable code @Test public void testSelectWithComparison() { List<Tuple> expected = computeExpected("SELECT orderkey FROM lineitem WHERE tax < discount", FIXED_INT_64); RowSourceBuilder orderKey = createBlockStream(lineitemData, Column.LINEITEM_ORDERKEY, FIXED_INT_64); TupleStream discount = createBlockStream(lineitemData, Column.LINEITEM_DISCOUNT, DOUBLE); TupleStream tax = createBlockStream(lineitemData, Column.LINEITEM_TAX, DOUBLE); ComparisonOperator comparison = new ComparisonOperator(tax, discount, new DoubleLessThanComparison()); FilterOperator result = new FilterOperator(orderKey.getTupleInfo(), orderKey, comparison); assertEqualsIgnoreOrder(tuples(result), expected); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Tuple createTuple(String key, long count) { TupleInfo tupleInfo = new TupleInfo(VARIABLE_BINARY, FIXED_INT_64); Tuple tuple = tupleInfo.builder() .append(Slices.wrappedBuffer(key.getBytes(UTF_8))) .append(count) .build(); return tuple; }
#vulnerable code private Tuple createTuple(String key, long count) { byte[] bytes = key.getBytes(Charsets.UTF_8); Slice slice = Slices.allocate(SIZE_OF_LONG + SIZE_OF_SHORT + bytes.length); slice.output() .appendLong(count) .appendShort(10 + bytes.length) .appendBytes(bytes); return new Tuple(slice, new TupleInfo(VARIABLE_BINARY, FIXED_INT_64)); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCreatePipelineAggregatedSharedTask() throws Exception { FreeStyleProject build1 = jenkins.createFreeStyleProject("build1"); FreeStyleProject build2 = jenkins.createFreeStyleProject("build2"); FreeStyleProject sonar = jenkins.createFreeStyleProject("sonar1"); build1.getPublishersList().add(new BuildTrigger("sonar1", true)); build2.getPublishersList().add(new BuildTrigger("sonar1", true)); build1.save(); build2.save(); jenkins.getInstance().rebuildDependencyGraph(); jenkins.setQuietPeriod(0); PipelineFactory factory = new PipelineFactory(); final Pipeline pipe1 = factory.extractPipeline("pipe1", build1); final Pipeline pipe2 = factory.extractPipeline("pipe2", build2); Pipeline aggregated1 = factory.createPipelineAggregated(pipe1); Pipeline aggregated2 = factory.createPipelineAggregated(pipe2); assertNull(aggregated1.getStages().get(0).getVersion()); assertNull(aggregated2.getStages().get(0).getVersion()); assertTrue(aggregated1.getStages().get(0).getTasks().get(0).getStatus().isIdle()); assertTrue(aggregated2.getStages().get(0).getTasks().get(0).getStatus().isIdle()); jenkins.buildAndAssertSuccess(build1); jenkins.waitUntilNoActivity(); assertNotNull(sonar.getLastBuild()); assertEquals(pipe1.getStages().size(), 2); assertEquals(pipe2.getStages().size(), 2); assertNotNull(sonar.getBuild("1")); aggregated1 = factory.createPipelineAggregated(pipe1); aggregated2 = factory.createPipelineAggregated(pipe2); assertEquals("#1", aggregated1.getStages().get(1).getVersion()); assertEquals(jenkins.getInstance().getRootUrl() + "job/sonar1/1/", aggregated1.getStages().get(1).getTasks().get(0).getLink()); assertEquals(true, aggregated2.getStages().get(1).getTasks().get(0).getStatus().isIdle()); assertEquals(jenkins.getInstance().getRootUrl() + "job/sonar1/", aggregated2.getStages().get(1).getTasks().get(0).getLink()); jenkins.buildAndAssertSuccess(build2); jenkins.waitUntilNoActivity(); aggregated1 = factory.createPipelineAggregated(pipe1); aggregated2 = factory.createPipelineAggregated(pipe2); assertEquals("#1", aggregated1.getStages().get(1).getVersion()); assertEquals("#1", aggregated2.getStages().get(1).getVersion()); assertEquals(true, aggregated2.getStages().get(1).getTasks().get(0).getStatus().isSuccess()); assertEquals(jenkins.getInstance().getRootUrl() + "job/sonar1/2/", aggregated2.getStages().get(1).getTasks().get(0).getLink()); jenkins.buildAndAssertSuccess(build1); jenkins.waitUntilNoActivity(); aggregated1 = factory.createPipelineAggregated(pipe1); aggregated2 = factory.createPipelineAggregated(pipe2); assertEquals("#2", aggregated1.getStages().get(1).getVersion()); assertEquals("#1", aggregated2.getStages().get(1).getVersion()); assertEquals(jenkins.getInstance().getRootUrl() + "job/sonar1/3/", aggregated1.getStages().get(1).getTasks().get(0).getLink()); assertEquals(jenkins.getInstance().getRootUrl() + "job/sonar1/2/", aggregated2.getStages().get(1).getTasks().get(0).getLink()); }
#vulnerable code @Test public void testCreatePipelineAggregatedSharedTask() throws Exception { FreeStyleProject build1 = jenkins.createFreeStyleProject("build1"); FreeStyleProject build2 = jenkins.createFreeStyleProject("build2"); FreeStyleProject sonar = jenkins.createFreeStyleProject("sonar1"); build1.getPublishersList().add(new BuildTrigger("sonar1", true)); build2.getPublishersList().add(new BuildTrigger("sonar1", true)); build1.save(); build2.save(); jenkins.getInstance().rebuildDependencyGraph(); jenkins.setQuietPeriod(0); jenkins.buildAndAssertSuccess(build1); jenkins.waitUntilNoActivity(); assertNotNull(sonar.getLastBuild()); PipelineFactory factory = new PipelineFactory(); final Pipeline pipe1 = factory.extractPipeline("pipe1", build1); final Pipeline pipe2 = factory.extractPipeline("pipe2", build2); assertEquals(pipe1.getStages().size(), 2); assertEquals(pipe2.getStages().size(), 2); assertNotNull(sonar.getBuild("1")); Pipeline aggregated1 = factory.createPipelineAggregated(pipe1); Pipeline aggregated2 = factory.createPipelineAggregated(pipe2); assertEquals("#1", aggregated1.getStages().get(1).getVersion()); assertEquals(true, aggregated2.getStages().get(1).getStatus().isIdle()); jenkins.buildAndAssertSuccess(build2); jenkins.waitUntilNoActivity(); Pipeline aggregated3 = factory.createPipelineAggregated(pipe1); Pipeline aggregated4 = factory.createPipelineAggregated(pipe2); assertEquals("#1", aggregated3.getStages().get(1).getVersion()); assertEquals("#1", aggregated4.getStages().get(1).getVersion()); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Pipeline getPipeline() { AbstractProject first = Jenkins.getInstance().getItem(firstJob, Jenkins.getInstance(), AbstractProject.class); AbstractBuild prevBuild = null; List<Stage> stages = newArrayList(); for (AbstractProject job : getAllDownstreamJobs(first)) { AbstractBuild build = job.getLastBuild(); Task task; if (stages.isEmpty() || build != null && build.equals(getDownstreamBuild(job, prevBuild))) { Status status = build != null? resolveStatus(build): idle(); task = new Task(job.getDisplayName(), status); prevBuild = build; } else { task = new Task(job.getDisplayName(), idle()); prevBuild = null; } Stage stage = new Stage(job.getDisplayName(), singletonList(task)); stages.add(stage); } return new Pipeline(title, stages); }
#vulnerable code public Pipeline getPipeline() { AbstractProject first = Jenkins.getInstance().getItem(firstJob, Jenkins.getInstance(), AbstractProject.class); AbstractBuild prevBuild = null; List<Stage> stages = newArrayList(); boolean isFirst = true; for (AbstractProject job : getAllDownstreamJobs(first)) { AbstractBuild build = job.getLastBuild(); Task task; if (isFirst || build.equals(getDownstreamBuild(job, prevBuild))) { Status status = resolveStatus(build); if (status == Status.RUNNING) { task = new Task(job.getDisplayName(), status, (int) Math.round((double) (System.currentTimeMillis() - build.getTimestamp().getTimeInMillis()) / build.getEstimatedDuration() * 100.0)); } else { task = new Task(job.getDisplayName(), status, 100); } prevBuild = build; } else { task = new Task(job.getDisplayName(), Status.NOTRUNNED, 0); prevBuild = null; } Stage stage = new Stage(job.getDisplayName(), singletonList(task)); stages.add(stage); isFirst = false; } return new Pipeline(title, stages); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Pipeline createPipelineAggregated(Pipeline pipeline) { List<Stage> stages = new ArrayList<>(); for (Stage stage : pipeline.getStages()) { List<Task> tasks = new ArrayList<>(); AbstractBuild firstTask = getJenkinsJob(stage.getTasks().get(0)).getLastBuild(); AbstractBuild versionBuild = getFirstUpstreamBuild(firstTask); String version = null; if (versionBuild != null) { version = versionBuild.getDisplayName(); } for (Task task : stage.getTasks()) { AbstractProject job = getJenkinsJob(task); AbstractBuild currentBuild = match(job.getBuilds(), versionBuild); if (currentBuild != null) { tasks.add(new Task(task.getId(), task.getName(), resolveStatus(job, currentBuild), Jenkins.getInstance().getRootUrl() + currentBuild.getUrl(), getTestResult(currentBuild))); } else { tasks.add(new Task(task.getId(), task.getName(), StatusFactory.idle(), task.getLink(), null)); } } stages.add(new Stage(stage.getName(), tasks, version)); } //TODO add triggeredBy return new Pipeline(pipeline.getName(), null, null, stages); }
#vulnerable code public Pipeline createPipelineAggregated(Pipeline pipeline) { List<Stage> stages = new ArrayList<>(); for (Stage stage : pipeline.getStages()) { List<Task> tasks = new ArrayList<>(); AbstractBuild firstTask = getJenkinsJob(stage.getTasks().get(0)).getLastBuild(); AbstractBuild versionBuild = getFirstUpstreamBuild(firstTask); String version = versionBuild.getDisplayName(); for (Task task : stage.getTasks()) { AbstractProject job = getJenkinsJob(task); AbstractBuild currentBuild = match(job.getBuilds(), versionBuild); if (currentBuild != null) { tasks.add(new Task(task.getId(), task.getName(), resolveStatus(job, currentBuild), Jenkins.getInstance().getRootUrl() + currentBuild.getUrl(), getTestResult(currentBuild))); } else { tasks.add(new Task(task.getId(), task.getName(), StatusFactory.idle(), task.getLink(), null)); } } stages.add(new Stage(stage.getName(), tasks, version)); } //TODO add triggeredBy return new Pipeline(pipeline.getName(), null, null, stages); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void parseContent() { if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { text = new EmojiMsgXmlHandler(this).getHtml(getMediaLink()); } else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { text = new ImageMsgXmlHandler(this).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_APP) { text = new AppMsgXmlHandler(this).getHtml(getMediaLink()); } // else if (MsgType == WechatMessage.MSGTYPE_FILE) { // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); // } else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { text = "视频消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOICE) { text = "语音消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { text = "小视频(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { text = "验证消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { text = "视频邀请消息(请在手机上查看)"; } else { String temp = StringUtils.decodeXml(Content); text = temp; } }
#vulnerable code public void parseContent() { String temp = StringUtils.decodeXml(Content); if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { text = new EmojiMsgXmlHandler(temp).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { text = new ImageMsgXmlHandler(temp).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_APP) { text = new AppMsgXmlHandler(temp).getHtml(getMediaLink(), this); } // else if (MsgType == WechatMessage.MSGTYPE_FILE) { // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); // } else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { text = "视频消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOICE) { text = "语音消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { text = "小视频(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { text = "验证消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { text = "视频邀请消息(请在手机上查看)"; } else { text = temp; } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Before public void setUp() throws Exception { String content = File2String.read("appmsg-file.xml"); WechatMessage m = new WechatMessage(); m.Content = content; handler = new AppMsgXmlHandler(m); }
#vulnerable code @Before public void setUp() throws Exception { String content = File2String.read("appmsg-file.xml"); handler = new AppMsgXmlHandler(content); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { // 创建一个新对象时需要扫描二维码登录,并且传一个处理接收到消息的回调,如果你不需要接收消息,可以传null final SmartQQClient client = new SmartQQClient(); client.setWorkDir(new File("target").getAbsoluteFile()); DefaultLoginCallback loginCallback = new DefaultLoginCallback(); loginCallback.setTitle("QQ", "请使用手机QQ扫描"); client.setLoginCallback(loginCallback); client.login(); client.setReceiveCallback(new ReceiveCallback() { @Override public void onReceiveMessage(AbstractMessage message, AbstractFrom from) { System.out.println(from + " > " + message.getText()); boolean unkown = false; QQContact qqContact = null; if (from instanceof GroupFrom) { GroupFrom gf = (GroupFrom) from; unkown = (gf.getGroupUser() == null || gf.getGroupUser().isUnknown()); qqContact = client.getGroup(gf.getGroup().getId()); } else if (from instanceof DiscussFrom) { DiscussFrom gf = (DiscussFrom) from; unkown = (gf.getDiscussUser() == null || gf.getDiscussUser().isUnknown()); qqContact = client.getGroup(gf.getDiscuss().getId()); } else { qqContact = (Friend) (from.getContact()); } System.out.println( String.format("unknown?%s, newbie?%s, contact:%s", unkown, from.isNewbie(), qqContact)); } @Override public void onReceiveError(Throwable e) { e.printStackTrace(System.err); } }); while (true) { if (client.isLogin()) { break; } Thread.sleep(1000); } client.init(); // 登录成功后便可以编写你自己的业务逻辑了 List<Category> categories = client.getFriendListWithCategory(); for (Category category : categories) { System.out.println(category.getName()); for (Friend friend : category.getFriends()) { System.out.println("————" + friend.getNickname()); } } client.parseRecents(client.getRecentList()); client.start(); // 使用后调用close方法关闭,你也可以使用try-with-resource创建该对象并自动关闭 // client.close(); }
#vulnerable code public static void main(String[] args) throws Exception{ // 创建一个新对象时需要扫描二维码登录,并且传一个处理接收到消息的回调,如果你不需要接收消息,可以传null final SmartQQClient client = new SmartQQClient(); client.setWorkDir(new File("target").getAbsoluteFile()); DefaultLoginCallback loginCallback = new DefaultLoginCallback(); loginCallback.setTitle("QQ", "请使用手机QQ扫描"); client.setLoginCallback(loginCallback); client.login(); // 登录成功后便可以编写你自己的业务逻辑了 List<Category> categories = client.getFriendListWithCategory(); for (Category category : categories) { System.out.println(category.getName()); for (Friend friend : category.getFriends()) { System.out.println("————" + friend.getNickname()); } } client.setReceiveCallback(new ReceiveCallback() { @Override public void onReceiveMessage(AbstractMessage message, AbstractFrom from) { System.out.println("from " + from + " msg: " + message); } @Override public void onReceiveError(Throwable e) { e.printStackTrace(System.err); } }); client.start(); // 使用后调用close方法关闭,你也可以使用try-with-resource创建该对象并自动关闭 // client.close(); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void parseContent() { if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { text = new EmojiMsgXmlHandler(this).getHtml(getMediaLink()); } else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { text = new ImageMsgXmlHandler(this).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_APP) { text = new AppMsgXmlHandler(this).getHtml(getMediaLink()); } // else if (MsgType == WechatMessage.MSGTYPE_FILE) { // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); // } else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { text = "视频消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOICE) { text = "语音消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { text = "小视频(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { text = "验证消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { text = "视频邀请消息(请在手机上查看)"; } else { String temp = StringUtils.decodeXml(Content); text = temp; } }
#vulnerable code public void parseContent() { String temp = StringUtils.decodeXml(Content); if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { text = new EmojiMsgXmlHandler(temp).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { text = new ImageMsgXmlHandler(temp).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_APP) { text = new AppMsgXmlHandler(temp).getHtml(getMediaLink(), this); } // else if (MsgType == WechatMessage.MSGTYPE_FILE) { // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); // } else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { text = "视频消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOICE) { text = "语音消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { text = "小视频(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { text = "验证消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { text = "视频邀请消息(请在手机上查看)"; } else { text = temp; } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Before public void setUp() throws Exception { String content = File2String.read("init.xml"); WechatMessage m = new WechatMessage(); m.Content = content; handler = new InitMsgXmlHandler(m); }
#vulnerable code @Before public void setUp() throws Exception { String content = File2String.read("init.xml"); handler = new InitMsgXmlHandler(content); } #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 testGetRecents() { AppMsgInfo info = handler.decode(); Assert.assertEquals("南京abc.xlsx", info.title); System.out.println(info); WechatMessage m = new WechatMessage(); m.Content = File2String.read("appmsg-publisher.xml"); handler = new AppMsgXmlHandler(m); info = handler.decode(); Assert.assertEquals("谷歌开发者", info.appName); System.out.println(info); }
#vulnerable code @Test public void testGetRecents() { AppMsgInfo info = handler.decode(); Assert.assertEquals("南京abc.xlsx", info.title); System.out.println(info); handler = new AppMsgXmlHandler( File2String.read("appmsg-publisher.xml")); info = handler.decode(); Assert.assertEquals("谷歌开发者", info.appName); System.out.println(info); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void parseContent() { if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { text = new EmojiMsgXmlHandler(this).getHtml(getMediaLink()); } else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { text = new ImageMsgXmlHandler(this).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_APP) { text = new AppMsgXmlHandler(this).getHtml(getMediaLink()); } // else if (MsgType == WechatMessage.MSGTYPE_FILE) { // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); // } else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { text = "视频消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOICE) { text = "语音消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { text = "小视频(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { text = "验证消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { text = "视频邀请消息(请在手机上查看)"; } else { String temp = StringUtils.decodeXml(Content); text = temp; } }
#vulnerable code public void parseContent() { String temp = StringUtils.decodeXml(Content); if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { text = new EmojiMsgXmlHandler(temp).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { text = new ImageMsgXmlHandler(temp).getHtml(getMediaLink(), this); } else if (MsgType == WechatMessage.MSGTYPE_APP) { text = new AppMsgXmlHandler(temp).getHtml(getMediaLink(), this); } // else if (MsgType == WechatMessage.MSGTYPE_FILE) { // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); // } else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { text = "视频消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOICE) { text = "语音消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { text = "小视频(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { text = "验证消息(请在手机上查看)"; } else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { text = "视频邀请消息(请在手机上查看)"; } else { text = temp; } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Connection getConnection(String dbPath) throws SQLException { if(DEFAULT_DB_PATH.equals(dbPath)){ return getConnection(); }else { SqliteBaseConnection currCon = createBaseConnection(dbPath); addRunningConnection(currCon); return currCon.getConnection(); } }
#vulnerable code public static Connection getConnection(String dbPath) throws SQLException { // 先进先出原则 SqliteBaseConnection currCon = null; synchronized (idleConList) { // 当可用连接池不为空时候 if (SqliteUtils.isNotEmpty(idleConList)) { currCon = idleConList.get(0); idleConList.remove(0); addRunningConnection(currCon); } if (currCon == null || currCon.getConnection() == null || currCon.getConnection().isClosed()) { currCon = createBaseConnection(dbPath); addRunningConnection(currCon); } } return currCon.getConnection(); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Map<String, GssFunction> get() { return GssFunctions.getFunctionMap(); }
#vulnerable code public Map<String, GssFunction> get() { return new ImmutableMap.Builder<String, GssFunction>() // Arithmetic functions. .put("add", new GssFunctions.AddToNumericValue()) .put("sub", new GssFunctions.SubtractFromNumericValue()) .put("mult", new GssFunctions.Mult()) // Not named "div" so it will not be confused with the HTML element. .put("divide", new GssFunctions.Div()) .put("min", new GssFunctions.MinValue()) .put("max", new GssFunctions.MaxValue()) // Color functions. .put("blendColors", new BlendColors()) .put("blendColorsRgb", new BlendColorsRGB()) .put("makeMutedColor", new MakeMutedColor()) .put("addHsbToCssColor", new AddHsbToCssColor()) .put("makeContrastingColor", new MakeContrastingColor()) .put("addToNumericValue", new AddToNumericValue()) .put("subtractFromNumericValue", new SubtractFromNumericValue()) .put("adjustBrightness", new AdjustBrightness()) // Logic functions. .put("selectFrom", new SelectFrom()) .build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Map<String, String> getFilenameProvideMap() { return filenameProvideMap; }
#vulnerable code public Map<String, String> getFilenameProvideMap() { return ImmutableMap.copyOf(filenameProvideMap); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ZooKeeper getClient(){ if (zooKeeper==null) { try { if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) { if (zooKeeper==null) { // 二次校验,防止并发创建client // init new-client ZooKeeper newZk = null; try { newZk = new ZooKeeper(zkaddress, 10000, watcher); if (zkdigest!=null && zkdigest.trim().length()>0) { newZk.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password" } newZk.exists(zkpath, false); // sync wait until succcess conn // set success new-client zooKeeper = newZk; logger.info(">>>>>>>>>> xxl-rpc, XxlZkClient init success."); } catch (Exception e) { // close fail new-client if (newZk != null) { newZk.close(); } logger.error(e.getMessage(), e); } finally { INSTANCE_INIT_LOCK.unlock(); } } } } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } if (zooKeeper == null) { throw new XxlRpcException("XxlZkClient.zooKeeper is null."); } return zooKeeper; }
#vulnerable code public ZooKeeper getClient(){ if (zooKeeper==null) { try { if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) { if (zooKeeper==null) { // 二次校验,防止并发创建client try { zooKeeper = new ZooKeeper(zkaddress, 10000, watcher); // TODO,本地变量方式,成功才会赋值 if (zkdigest!=null && zkdigest.trim().length()>0) { zooKeeper.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password" } zooKeeper.exists(zkpath, false); // sync } catch (Exception e) { logger.error(e.getMessage(), e); } finally { INSTANCE_INIT_LOCK.unlock(); } logger.info(">>>>>>>>>> xxl-rpc, XxlZkClient init success."); } } } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } if (zooKeeper == null) { throw new XxlRpcException("XxlZkClient.zooKeeper is null."); } return zooKeeper; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("rawtypes") @Override public void onFinished(Invocation invocation,Object result) { Object[] args = invocation.getArgs(); MappedStatement mt = (MappedStatement)args[0]; String mapperNameSpace = mt.getId().substring(0, mt.getId().lastIndexOf(SPLIT_PONIT)); QueryMethodCache cacheInfo = null; if(mt.getSqlCommandType().equals(SqlCommandType.SELECT)){ if(result == null)return; if((cacheInfo = getQueryMethodCache(mt.getId())) == null)return; if(result instanceof List){ List list = (List)result; if(list.isEmpty())return; result = cacheInfo.collectionResult ? result : list.get(0); } final String cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]); //按主键查询以及标记非引用关系的缓存直接读取缓存 if(cacheInfo.isSecondQueryById() == false){ if(cacheProvider.set(cacheKey,result, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("_autocache_ method[{}] put result to cache,cacheKey:{}",mt.getId(),cacheKey); } //结果为集合的情况,增加key到cacheGroup if(cacheInfo.groupRalated){ cacheProvider.putGroupKeys(cacheInfo.cacheGroupKey, cacheKey,cacheInfo.expire); logger.debug("_autocache_ method[{}] add key:[{}] to group key:[{}]",mt.getId(),cacheInfo.cacheGroupKey, cacheKey); }else{ // cacheUniqueSelectRef(result, mt, cacheKey); } }else{ //之前没有按主键的缓存,增加按主键缓存 String idCacheKey = genarateQueryCacheKey(getQueryByPkMethodCache(mt.getId()).keyPattern,result); if(idCacheKey != null && cacheKey != null && cacheProvider.set(idCacheKey,result, cacheInfo.expire) && cacheProvider.set(cacheKey,idCacheKey, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("_autocache_ method[{}] put result to cache,cacheKey:{},and add ref cacheKey:{}",mt.getId(),idCacheKey,cacheKey); } } }else{ if(!cacheEnableMappers.contains(mapperNameSpace))return; //返回0,未更新成功 if(result != null && ((int)result) == 0)return; if(updateCacheMethods.containsKey(mt.getId())){ String cacheByPkKey = null; UpdateByPkMethodCache updateMethodCache = updateCacheMethods.get(mt.getId()); if(updateMethodCache.sqlCommandType.equals(SqlCommandType.DELETE)){ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); cacheProvider.remove(cacheByPkKey); if(logger.isDebugEnabled())logger.debug("_autocache_ method[{}] remove cacheKey:{} from cache",mt.getId(),cacheByPkKey); }else{ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); boolean insertCommond = mt.getSqlCommandType().equals(SqlCommandType.INSERT); if(insertCommond || mt.getSqlCommandType().equals(SqlCommandType.UPDATE)){ if(result != null){ QueryMethodCache queryByPkMethodCache = getQueryByPkMethodCache(mt.getId()); cacheProvider.set(cacheByPkKey,args[1], queryByPkMethodCache.expire); if(logger.isDebugEnabled())logger.debug("_autocache_ method[{}] update cacheKey:{}",mt.getId(),cacheByPkKey); //插入其他唯一字段引用 if(insertCommond)cacheUniqueSelectRef(args[1], mt, cacheByPkKey); // addCurrentThreadCacheKey(cacheByPkKey); } } } }else{//按条件删除和更新的情况 try { Executor executor = (Executor) invocation.getTarget(); Object parameterObject = args[1]; ResultHandler resultHandler = null; EntityInfo entityInfo = MybatisMapperParser.getEntityInfoByMapper(mapperNameSpace); MappedStatement statement = getQueryIdsMappedStatementForUpdateCache(mt,entityInfo); List<?> idsResult = executor.query(statement, parameterObject, RowBounds.DEFAULT, resultHandler); if(idsResult != null){ for (Object id : idsResult) { String cacheKey = entityInfo.getEntityClass().getSimpleName() + ".id:" + id.toString(); cacheProvider.remove(cacheKey); } if(logger.isDebugEnabled())logger.debug("_autocache_ update Method[{}] executed,remove ralate cache {}.id:[{}]",mt.getId(),entityInfo.getEntityClass().getSimpleName(),idsResult); } } catch (Exception e) { logger.error("_autocache_ update Method[{}] remove ralate cache error",e); } } //删除同一cachegroup关联缓存 removeCacheByGroup(mt.getId(), mapperNameSpace); } }
#vulnerable code @SuppressWarnings("rawtypes") @Override public void onFinished(Invocation invocation,Object result) { Object[] args = invocation.getArgs(); MappedStatement mt = (MappedStatement)args[0]; String mapperNameSpace = mt.getId().substring(0, mt.getId().lastIndexOf(SPLIT_PONIT)); QueryMethodCache cacheInfo = null; if(mt.getSqlCommandType().equals(SqlCommandType.SELECT)){ if(result == null)return; if((cacheInfo = getQueryMethodCache(mt.getId())) == null)return; if(result instanceof List){ List list = (List)result; if(list.isEmpty())return; result = cacheInfo.collectionResult ? result : list.get(0); } final String cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]); //按主键查询以及标记非引用关系的缓存直接读取缓存 if(cacheInfo.isSecondQueryById() == false){ if(cacheProvider.set(cacheKey,result, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("method[{}] put result to cache,cacheKey:{}",mt.getId(),cacheKey); } //结果为集合的情况,增加key到cacheGroup if(cacheInfo.groupRalated){ cacheProvider.putGroupKeys(cacheInfo.cacheGroupKey, cacheKey,cacheInfo.expire); logger.debug("method[{}] add key:[{}] to group key:[{}]",mt.getId(),cacheInfo.cacheGroupKey, cacheKey); }else{ // cacheUniqueSelectRef(result, mt, cacheKey); } }else{ //之前没有按主键的缓存,增加按主键缓存 String idCacheKey = genarateQueryCacheKey(getQueryByPkMethodCache(mt.getId()).keyPattern,result); if(idCacheKey != null && cacheKey != null && cacheProvider.set(idCacheKey,result, cacheInfo.expire) && cacheProvider.set(cacheKey,idCacheKey, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("method[{}] put result to cache,cacheKey:{},and add ref cacheKey:{}",mt.getId(),idCacheKey,cacheKey); } } }else{ //返回0,未更新成功 if(result != null && ((int)result) == 0)return; if(updateCacheMethods.containsKey(mt.getId())){ String cacheByPkKey = null; UpdateByPkMethodCache updateMethodCache = updateCacheMethods.get(mt.getId()); if(updateMethodCache.sqlCommandType.equals(SqlCommandType.DELETE)){ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); cacheProvider.remove(cacheByPkKey); if(logger.isDebugEnabled())logger.debug("method[{}] remove cacheKey:{} from cache",mt.getId(),cacheByPkKey); }else{ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); boolean insertCommond = mt.getSqlCommandType().equals(SqlCommandType.INSERT); if(insertCommond || mt.getSqlCommandType().equals(SqlCommandType.UPDATE)){ if(result != null){ QueryMethodCache queryByPkMethodCache = getQueryByPkMethodCache(mt.getId()); cacheProvider.set(cacheByPkKey,args[1], queryByPkMethodCache.expire); if(logger.isDebugEnabled())logger.debug("method[{}] update cacheKey:{}",mt.getId(),cacheByPkKey); //插入其他唯一字段引用 if(insertCommond)cacheUniqueSelectRef(args[1], mt, cacheByPkKey); // addCurrentThreadCacheKey(cacheByPkKey); } } } }else{//按条件删除和更新的情况 System.out.println(args); System.out.println(mt); BoundSql boundSql = mt.getBoundSql(args[1]); Object parameterObject2 = boundSql.getParameterObject(); System.out.println(parameterObject2); System.out.println(boundSql.getSql()); System.out.println(); } //删除同一cachegroup关联缓存 removeCacheByGroup(mt.getId(), mapperNameSpace); } } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void resetCorrectOffsets() { consumer.pause(consumer.assignment()); Map<String, List<PartitionInfo>> topicInfos = consumer.listTopics(); Set<String> topics = topicInfos.keySet(); List<String> expectTopics = new ArrayList<>(topicHandlers.keySet()); List<PartitionInfo> patitions = null; for (String topic : topics) { if(!expectTopics.contains(topic))continue; patitions = topicInfos.get(topic); for (PartitionInfo partition : patitions) { try { //期望的偏移 long expectOffsets = consumerContext.getLatestProcessedOffsets(topic, partition.partition()); // TopicPartition topicPartition = new TopicPartition(topic, partition.partition()); OffsetAndMetadata metadata = consumer.committed(new TopicPartition(partition.topic(), partition.partition())); if(expectOffsets >= 0){ if(expectOffsets < metadata.offset()){ consumer.seek(topicPartition, expectOffsets); logger.info("seek Topic[{}] partition[{}] from {} to {}",topic, partition.partition(),metadata.offset(),expectOffsets); } } } catch (Exception e) { logger.warn("try seek topic["+topic+"] partition["+partition.partition()+"] offsets error"); } } } consumer.resume(consumer.assignment()); }
#vulnerable code private void resetCorrectOffsets() { KafkaConsumerCommand consumerCommand = new KafkaConsumerCommand(consumerContext.getProperties().getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)); try { List<TopicInfo> topicInfos = consumerCommand.consumerGroup(consumerContext.getGroupId()).getTopics(); for (TopicInfo topic : topicInfos) { List<TopicPartitionInfo> partitions = topic.getPartitions(); for (TopicPartitionInfo partition : partitions) { try { //期望的偏移 long expectOffsets = consumerContext.getLatestProcessedOffsets(topic.getTopicName(), partition.getPartition()); // if(expectOffsets < partition.getOffset()){ consumer.seek(new TopicPartition(topic.getTopicName(), partition.getPartition()), expectOffsets); logger.info("seek Topic[{}] partition[{}] from {} to {}",topic.getTopicName(), partition.getPartition(),partition.getOffset(),expectOffsets); } } catch (Exception e) { logger.warn("try seek topic["+topic.getTopicName()+"] partition["+partition.getPartition()+"] offsets error",e); } } } } catch (Exception e) { logger.warn("KafkaConsumerCommand.consumerGroup("+consumerContext.getGroupId()+") error",e); } consumerCommand.close(); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void start() { createKafkaConsumer(); //按主题数创建ConsumerWorker线程 for (int i = 0; i < topicHandlers.size(); i++) { ConsumerWorker consumer = new ConsumerWorker(); consumerWorks.add(consumer); fetcheExecutor.submit(consumer); } }
#vulnerable code @Override public void start() { for (int i = 0; i < topicHandlers.size(); i++) { ConsumerWorker<String, DefaultMessage> consumer = new ConsumerWorker<>(configs, topicHandlers,processExecutor); consumers.add(consumer); fetcheExecutor.submit(consumer); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private synchronized static void load() { try { if(inited)return; File dir = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath()); loadPropertiesFromFile(dir); inited = true; } catch (Exception e) { inited = true; throw new RuntimeException(e); } }
#vulnerable code private synchronized static void load() { try { if(!properties.isEmpty())return; File dir = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath()); File[] propFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("properties"); } }); for (File file : propFiles) { Properties p = new Properties(); p.load(new FileReader(file)); properties.add(p); } inited = true; } catch (Exception e) { inited = true; throw new RuntimeException(e); } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object onInterceptor(Invocation invocation) throws Throwable { final Executor executor = (Executor) invocation.getTarget(); final Object[] args = invocation.getArgs(); final MappedStatement orignMappedStatement = (MappedStatement)args[0]; if(!orignMappedStatement.getSqlCommandType().equals(SqlCommandType.SELECT))return null; if(!pageMappedStatements.keySet().contains(orignMappedStatement.getId()))return null; final RowBounds rowBounds = (RowBounds) args[2]; final ResultHandler resultHandler = (ResultHandler) args[3]; final Object parameter = args[1]; PageParams pageParams = PageExecutor.getPageParams(); if(pageParams == null && pageMappedStatements.get(orignMappedStatement.getId())){ if(parameter instanceof Map){ Collection parameterValues = ((Map)parameter).values(); for (Object val : parameterValues) { if(val instanceof PageParams){ pageParams = (PageParams) val; break; } } }else{ pageParams = (PageParams) parameter; } } if(pageParams == null)return null; BoundSql boundSql = orignMappedStatement.getBoundSql(parameter); //查询总数 MappedStatement countMappedStatement = getCountMappedStatement(orignMappedStatement); Long total = executeQueryCount(executor, countMappedStatement, parameter, boundSql, rowBounds, resultHandler); //按分页查询 MappedStatement limitMappedStatement = getLimitMappedStatementIfNotCreate(orignMappedStatement); boundSql = limitMappedStatement.getBoundSql(parameter); boundSql.setAdditionalParameter(PARAMETER_OFFSET, pageParams.getOffset()); boundSql.setAdditionalParameter(PARAMETER_SIZE, pageParams.getPageSize()); List<?> datas = executor.query(limitMappedStatement, parameter, RowBounds.DEFAULT, resultHandler,null,boundSql); Page<Object> page = new Page<Object>(pageParams,total,(List<Object>) datas); List<Page<?>> list = new ArrayList<Page<?>>(1); list.add(page); return list; }
#vulnerable code @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object onInterceptor(Invocation invocation) throws Throwable { final Executor executor = (Executor) invocation.getTarget(); final Object[] args = invocation.getArgs(); final RowBounds rowBounds = (RowBounds) args[2]; final ResultHandler resultHandler = (ResultHandler) args[3]; final MappedStatement orignMappedStatement = (MappedStatement)args[0]; final Object parameter = args[1]; if(!orignMappedStatement.getSqlCommandType().equals(SqlCommandType.SELECT))return null; if(!pageMappedStatements.keySet().contains(orignMappedStatement.getId()))return null; PageParams pageParams = PageExecutor.getPageParams(); if(pageParams == null && pageMappedStatements.get(orignMappedStatement.getId())){ if(parameter instanceof Map){ Collection parameterValues = ((Map)parameter).values(); for (Object val : parameterValues) { if(val instanceof PageParams){ pageParams = (PageParams) val; break; } } }else{ pageParams = (PageParams) parameter; } } if(pageParams == null)return null; BoundSql boundSql = orignMappedStatement.getBoundSql(parameter); //查询总数 MappedStatement countMappedStatement = getCountMappedStatement(orignMappedStatement); Long total = executeQueryCount(executor, countMappedStatement, parameter, boundSql, rowBounds, resultHandler); //按分页查询 MappedStatement limitMappedStatement = getLimitMappedStatementIfNotCreate(orignMappedStatement); boundSql = limitMappedStatement.getBoundSql(parameter); boundSql.setAdditionalParameter(PARAMETER_OFFSET, pageParams.getOffset()); boundSql.setAdditionalParameter(PARAMETER_SIZE, pageParams.getPageSize()); List<?> datas = executor.query(limitMappedStatement, parameter, RowBounds.DEFAULT, resultHandler,null,boundSql); Page<Object> page = new Page<Object>(pageParams,total,(List<Object>) datas); List<Page<?>> list = new ArrayList<Page<?>>(1); list.add(page); return list; } #location 42 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void setRuning(String jobName, Date fireTime) { updatingStatus = false; try { JobConfig config = getConf(jobName,false); config.setRunning(true); config.setLastFireTime(fireTime); config.setModifyTime(Calendar.getInstance().getTimeInMillis()); config.setErrorMsg(null); //更新本地 schedulerConfgs.put(jobName, config); try { if(zkAvailabled)zkClient.writeData(getPath(config), JsonUtils.toJson(config)); } catch (Exception e) { checkZkAvailabled(); logger.warn(String.format("Job[{}] setRuning error...", jobName),e); } } finally { updatingStatus = false; } }
#vulnerable code @Override public void setRuning(String jobName, Date fireTime) { updatingStatus = false; try { JobConfig config = getConf(jobName,false); config.setRunning(true); config.setLastFireTime(fireTime); config.setCurrentNodeId(JobContext.getContext().getNodeId()); config.setModifyTime(Calendar.getInstance().getTimeInMillis()); config.setErrorMsg(null); //更新本地 schedulerConfgs.put(jobName, config); try { if(zkAvailabled)zkClient.writeData(getPath(config), JsonUtils.toJson(config)); } catch (Exception e) { checkZkAvailabled(); logger.warn(String.format("Job[{}] setRuning error...", jobName),e); } } finally { updatingStatus = false; } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("rawtypes") @Override public void onFinished(Invocation invocation,Object result) { Object[] args = invocation.getArgs(); MappedStatement mt = (MappedStatement)args[0]; String mapperNameSpace = mt.getId().substring(0, mt.getId().lastIndexOf(SPLIT_PONIT)); QueryMethodCache cacheInfo = null; if(mt.getSqlCommandType().equals(SqlCommandType.SELECT)){ if(result == null)return; if((cacheInfo = getQueryMethodCache(mt.getId())) == null)return; if(result instanceof List){ List list = (List)result; if(list.isEmpty())return; result = cacheInfo.uniqueResult ? list.get(0) : result; } final String cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]); //按主键查询以及标记非引用关系的缓存直接读取缓存 if(cacheInfo.isPk || !cacheInfo.uniqueResult){ if(cacheProvider.set(cacheKey,result, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("method[{}] put result to cache,cacheKey:{}",mt.getId(),cacheKey); } //结果为集合的情况,增加key到cacheGroup if(!cacheInfo.uniqueResult){ cacheProvider.putGroupKeys(cacheInfo.cacheGroupKey, cacheKey,cacheInfo.expire); logger.debug("method[{}] add key:[{}] to group key:[{}]",mt.getId(),cacheInfo.cacheGroupKey, cacheKey); }else{ // cacheUniqueSelectRef(result, mt, cacheKey); } }else{ //之前没有按主键的缓存,增加按主键缓存 String idCacheKey = genarateQueryCacheKey(getQueryByPkMethodCache(mt.getId()).keyPattern,result); if(idCacheKey != null && cacheKey != null && cacheProvider.set(idCacheKey,result, cacheInfo.expire) && cacheProvider.set(cacheKey,idCacheKey, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("method[{}] put result to cache,cacheKey:{},and add ref cacheKey:{}",mt.getId(),idCacheKey,cacheKey); } } }else{ //返回0,未更新成功 if(result != null && ((int)result) == 0)return; if(updateCacheMethods.containsKey(mt.getId())){ String cacheByPkKey = null; UpdateByPkMethodCache updateMethodCache = updateCacheMethods.get(mt.getId()); if(updateMethodCache.sqlCommandType.equals(SqlCommandType.DELETE)){ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); cacheProvider.remove(cacheByPkKey); if(logger.isDebugEnabled())logger.debug("method[{}] remove cacheKey:{} from cache",mt.getId(),cacheByPkKey); }else{ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); boolean insertCommond = mt.getSqlCommandType().equals(SqlCommandType.INSERT); if(insertCommond || mt.getSqlCommandType().equals(SqlCommandType.UPDATE)){ if(result != null){ QueryMethodCache queryByPkMethodCache = getQueryByPkMethodCache(mt.getId()); cacheProvider.set(cacheByPkKey,args[1], queryByPkMethodCache.expire); if(logger.isDebugEnabled())logger.debug("method[{}] update cacheKey:{}",mt.getId(),cacheByPkKey); //插入其他唯一字段引用 if(insertCommond)cacheUniqueSelectRef(args[1], mt, cacheByPkKey); // addCurrentThreadCacheKey(cacheByPkKey); } } } } //删除同一cachegroup关联缓存 removeCacheByGroup(mt.getId(), mapperNameSpace); } }
#vulnerable code @SuppressWarnings("rawtypes") @Override public void onFinished(Invocation invocation,Object result) { Object[] args = invocation.getArgs(); MappedStatement mt = (MappedStatement)args[0]; QueryMethodCache cacheInfo = null; if(mt.getSqlCommandType().equals(SqlCommandType.SELECT)){ if(result == null)return; if((cacheInfo = getQueryMethodCache(mt.getId())) == null)return; if(result instanceof List){ List list = (List)result; if(list.isEmpty())return; result = cacheInfo.uniqueResult ? list.get(0) : result; } final String cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]); //按主键查询以及标记非引用关系的缓存直接读取缓存 if(cacheInfo.isPk || !cacheInfo.uniqueResult){ if(cacheProvider.set(cacheKey,result, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("method[{}] put result to cache,cacheKey:{}",mt.getId(),cacheKey); } //结果为集合的情况,增加key到cacheGroup if(!cacheInfo.uniqueResult){ cacheProvider.putGroupKeys(cacheInfo.cacheGroupKey, cacheKey,cacheInfo.expire); } }else{ //之前没有按主键的缓存,增加按主键缓存 String idCacheKey = genarateQueryCacheKey(getQueryByPkMethodCache(mt.getId()).keyPattern,result); if(idCacheKey != null && cacheKey != null && cacheProvider.set(idCacheKey,result, cacheInfo.expire) && cacheProvider.set(cacheKey,idCacheKey, cacheInfo.expire)){ if(logger.isDebugEnabled())logger.debug("method[{}] put result to cache,cacheKey:{},and add ref cacheKey:{}",mt.getId(),idCacheKey,cacheKey); } } }else{ if(updateCacheMethods.containsKey(mt.getId())){ String cacheByPkKey = null; UpdateByPkMethodCache updateMethodCache = updateCacheMethods.get(mt.getId()); if(updateMethodCache.sqlCommandType.equals(SqlCommandType.DELETE)){ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); cacheProvider.remove(cacheByPkKey); if(logger.isDebugEnabled())logger.debug("method[{}] remove cacheKey:{} from cache",mt.getId(),cacheByPkKey); //TODO 清除关联缓存 }else{ cacheByPkKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]); boolean insertCommond = mt.getSqlCommandType().equals(SqlCommandType.INSERT); if(insertCommond || mt.getSqlCommandType().equals(SqlCommandType.UPDATE)){ if(result != null){ QueryMethodCache queryByPkMethodCache = getQueryByPkMethodCache(mt.getId()); cacheProvider.set(cacheByPkKey,args[1], queryByPkMethodCache.expire); if(logger.isDebugEnabled())logger.debug("method[{}] update cacheKey:{}",mt.getId(),cacheByPkKey); //插入其他唯一字段引用 if(insertCommond)cacheUniqueSelectRef(args[1], mt, cacheByPkKey); // addCurrentThreadCacheKey(cacheByPkKey); } } } //TODO 删除同一cachegroup关联缓存 cacheProvider.clearGroupKeys(updateMethodCache.cacheGroupKey); } } } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected XInputStream open(String path) throws Exception { // final XInputStream is = new XInputStreamImpl(new FileInputStream(path)); try { // Check binlog magic final byte[] magic = is.readBytes(MySQLConstants.BINLOG_MAGIC.length); if(!CodecUtils.equals(magic, MySQLConstants.BINLOG_MAGIC)) { throw new NestableRuntimeException("invalid binlog magic, file: " + path); } // if(this.startPosition > MySQLConstants.BINLOG_MAGIC.length) { is.skip(this.startPosition - MySQLConstants.BINLOG_MAGIC.length); } return is; } catch(Exception e) { IOUtils.closeQuietly(is); throw e; } }
#vulnerable code protected XInputStream open(String path) throws Exception { // final RandomAccessFile file = new RandomAccessFile(path, "r"); final XInputStream is = new XInputStreamImpl(new RamdomAccessFileInputStream(file)); try { // Check binlog magic final byte[] magic = is.readBytes(MySQLConstants.BINLOG_MAGIC.length); if(!CodecUtils.equals(magic, MySQLConstants.BINLOG_MAGIC)) { throw new NestableRuntimeException("invalid binlog magic, file: " + path); } // if(this.startPosition > MySQLConstants.BINLOG_MAGIC.length) { is.skip(this.startPosition - MySQLConstants.BINLOG_MAGIC.length); } return is; } catch(Exception e) { IOUtils.closeQuietly(is); throw e; } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected XInputStream open(String path) throws Exception { // final XInputStream is = new XInputStreamImpl(new RamdomAccessFileInputStream(new File(path))); try { // Check binlog magic final byte[] magic = is.readBytes(MySQLConstants.BINLOG_MAGIC.length); if(!CodecUtils.equals(magic, MySQLConstants.BINLOG_MAGIC)) { throw new NestableRuntimeException("invalid binlog magic, file: " + path); } // if(this.startPosition > MySQLConstants.BINLOG_MAGIC.length) { is.skip(this.startPosition - MySQLConstants.BINLOG_MAGIC.length); } return is; } catch(Exception e) { IOUtils.closeQuietly(is); throw e; } }
#vulnerable code protected XInputStream open(String path) throws Exception { // final RandomAccessFile file = new RandomAccessFile(path, "r"); final XInputStream is = new XInputStreamImpl(new RamdomAccessFileInputStream(file)); try { // Check binlog magic final byte[] magic = is.readBytes(MySQLConstants.BINLOG_MAGIC.length); if(!CodecUtils.equals(magic, MySQLConstants.BINLOG_MAGIC)) { throw new NestableRuntimeException("invalid binlog magic, file: " + path); } // if(this.startPosition > MySQLConstants.BINLOG_MAGIC.length) { is.skip(this.startPosition - MySQLConstants.BINLOG_MAGIC.length); } return is; } catch(Exception e) { IOUtils.closeQuietly(is); throw e; } } #location 18 #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 file = "src/test/resources/jansi.ans"; if( args.length>0 ) file = args[0]; // Allows us to disable ANSI processing. if( "true".equals(System.getProperty("jansi", "true")) ) { AnsiConsole.systemInstall(); } PrintStream out = System.out; FileInputStream f = new FileInputStream(file); int c; while( (c=f.read())>=0 ) { out.write(c); } f.close(); }
#vulnerable code public static void main(String[] args) throws IOException { AnsiConsole.systemInstall(); PrintStream out = System.out; FileInputStream f = new FileInputStream("src/test/resources/jansi.ans"); int c; while( (c=f.read())>=0 ) { out.write(c); } f.close(); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Client(String user_id, String license_key) { this.user_id = user_id; this.license_key = license_key; }
#vulnerable code Country Country(String ip_address) { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("https://geoip.maxmind.com/geoip/country/" + ip_address); httpget.addHeader("Accept","application/json"); httpget.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials(user_id,license_key),"UTF-8",false)); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(instream)); return new Country(reader.readLine()); } } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return null; } #location 19 #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 ) { String user_id = args[0]; String license_key = args[1]; String ip_address = args[2]; Client cl = new Client(user_id,license_key); Country c = cl.Country(ip_address); System.out.println(c.get_country_name("en")); }
#vulnerable code public static void main( String[] args ) { try { String user_id = args[0]; String license_key = args[1]; String ip_address = args[2]; Client cl = new Client(user_id,license_key); JSONObject o = cl.Country(ip_address); o = o.getJSONObject("country"); o = o.getJSONObject("name"); String name = o.getString("en"); System.out.println(name); } catch (JSONException e) { e.printStackTrace(); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private JSONObject responseFor(String path, String ip_address) throws GeoIP2Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); String uri = "https://" + host; if (host.startsWith("localhost")) { uri = "http://" + host; } uri = uri + "/geoip/v2.0/" + path + "/" + ip_address; HttpGet httpget = new HttpGet(uri); httpget.addHeader("Accept", "application/json"); httpget.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials(userId, licenseKey), "UTF-8", false)); HttpResponse response = null; try { response = httpclient.execute(httpget); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } int status = response.getStatusLine().getStatusCode(); if (status == 200) { return handleSuccess(response, uri); } else { handleErrorStatus(response, status, uri); } return null; }
#vulnerable code private JSONObject responseFor(String path, String ip_address) throws GeoIP2Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { // String uri = "https://ct4-test.maxmind.com/geoip/" + path + "/" + // ip_address; String uri = "https://" + host; if (host.startsWith("localhost")) { uri = "http://" + host; } uri = uri + "/geoip/v2.0/" + path + "/" + ip_address; HttpGet httpget = new HttpGet(uri); httpget.addHeader("Accept", "application/json"); httpget.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials(userId, licenseKey), "UTF-8", false)); HttpResponse response = httpclient.execute(httpget); int status = response.getStatusLine().getStatusCode(); if (status == 200) { return handleSuccess(response, uri); } else { handleErrorStatus(response, status, uri); } } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return null; } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Client(String user_id, String license_key) { this.user_id = user_id; this.license_key = license_key; }
#vulnerable code Country Country(String ip_address) { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("https://geoip.maxmind.com/geoip/country/" + ip_address); httpget.addHeader("Accept","application/json"); httpget.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials(user_id,license_key),"UTF-8",false)); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(instream)); return new Country(reader.readLine()); } } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return null; } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public <T> Collection<T> loadAll(Class<T> type, Filters filters, SortOrder sortOrder, Pagination pagination, int depth) { Transaction tx = session.ensureTransaction(); String entityType = session.entityType(type.getName()); QueryStatements queryStatements = session.queryStatementsFor(type); // all this business about selecting which type of model/response to handle is horribly hacky // it should be possible for the response handler to select based on the model implementation // and we should have a single method loadAll(...). Filters should not be a special case // though they are at the moment because of the problems with "graph" response format. if (filters.isEmpty()) { Query qry = queryStatements.findByType(entityType, depth) .setSortOrder(sortOrder) .setPagination(pagination); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, tx)) { return session.responseHandler().loadAll(type, response); } } else { filters = resolvePropertyAnnotations(type, filters); Query qry = queryStatements.findByProperties(entityType, filters, depth) .setSortOrder(sortOrder) .setPagination(pagination); if (depth != 0) { try (Neo4jResponse<GraphRowModel> response = session.requestHandler().execute((GraphRowModelQuery) qry, tx)) { return session.responseHandler().loadByProperty(type, response); } } else { try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, tx)) { return session.responseHandler().loadAll(type, response); } } } }
#vulnerable code @Override public <T> Collection<T> loadAll(Class<T> type, Filters filters, SortOrder sortOrder, Pagination pagination, int depth) { String url = session.ensureTransaction().url(); String entityType = session.entityType(type.getName()); QueryStatements queryStatements = session.queryStatementsFor(type); // all this business about selecting which type of model/response to handle is horribly hacky // it should be possible for the response handler to select based on the model implementation // and we should have a single method loadAll(...). Filters should not be a special case // though they are at the moment because of the problems with "graph" response format. if (filters.isEmpty()) { Query qry = queryStatements.findByType(entityType, depth) .setSortOrder(sortOrder) .setPagination(pagination); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, url)) { return session.responseHandler().loadAll(type, response); } } else { filters = resolvePropertyAnnotations(type, filters); Query qry = queryStatements.findByProperties(entityType, filters, depth) .setSortOrder(sortOrder) .setPagination(pagination); if (depth != 0) { try (Neo4jResponse<GraphRowModel> response = session.requestHandler().execute((GraphRowModelQuery) qry, url)) { return session.responseHandler().loadByProperty(type, response); } } else { try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, url)) { return session.responseHandler().loadAll(type, response); } } } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public <T> T load(Class<T> type, Long id, int depth) { Transaction tx = session.ensureTransaction(); QueryStatements queryStatements = session.queryStatementsFor(type); Query qry = queryStatements.findOne(id,depth); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, tx)) { return session.responseHandler().loadById(type, response, id); } }
#vulnerable code @Override public <T> T load(Class<T> type, Long id, int depth) { String url = session.ensureTransaction().url(); QueryStatements queryStatements = session.queryStatementsFor(type); Query qry = queryStatements.findOne(id,depth); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, url)) { return session.responseHandler().loadById(type, response, id); } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean bothWayMappingRequired(Object srcObject, String relationshipType, Object tgtObject, String relationshipDirection) { boolean mapBothWays = false; ClassInfo tgtInfo = metaData.classInfo(tgtObject); if(tgtInfo == null) { LOGGER.warn("Unable to process {} on {}. Checck the mapping.", relationshipType, srcObject.getClass()); // #347. attribute is not a rel ? maybe would be better to change FieldInfo.persistableAsProperty ? return false; } for (FieldInfo tgtRelReader : tgtInfo.relationshipFields()) { String tgtRelationshipDirection = tgtRelReader.relationshipDirection(); if ((tgtRelationshipDirection.equals(Relationship.OUTGOING) || tgtRelationshipDirection.equals(Relationship.INCOMING)) //The relationship direction must be explicitly incoming or outgoing && tgtRelReader.relationshipType().equals(relationshipType)) { //The source must have the same relationship type to the target as the target to the source //Moreover, the source must be related to the target and vice versa in the SAME direction if (relationshipDirection.equals(tgtRelationshipDirection)) { Object target = tgtRelReader.read(tgtObject); if (target != null) { if (target instanceof Iterable) { for (Object relatedObject : (Iterable<?>) target) { if (relatedObject.equals(srcObject)) { //the target is mapped to the source as well mapBothWays = true; } } } else if (target.getClass().isArray()) { for (Object relatedObject : (Object[]) target) { if (relatedObject.equals(srcObject)) { //the target is mapped to the source as well mapBothWays = true; } } } else { if (target.equals(srcObject)) { //the target is mapped to the source as well mapBothWays = true; } } } } } } return mapBothWays; }
#vulnerable code private boolean bothWayMappingRequired(Object srcObject, String relationshipType, Object tgtObject, String relationshipDirection) { boolean mapBothWays = false; ClassInfo tgtInfo = metaData.classInfo(tgtObject); for (FieldInfo tgtRelReader : tgtInfo.relationshipFields()) { String tgtRelationshipDirection = tgtRelReader.relationshipDirection(); if ((tgtRelationshipDirection.equals(Relationship.OUTGOING) || tgtRelationshipDirection.equals(Relationship.INCOMING)) //The relationship direction must be explicitly incoming or outgoing && tgtRelReader.relationshipType().equals(relationshipType)) { //The source must have the same relationship type to the target as the target to the source //Moreover, the source must be related to the target and vice versa in the SAME direction if (relationshipDirection.equals(tgtRelationshipDirection)) { Object target = tgtRelReader.read(tgtObject); if (target != null) { if (target instanceof Iterable) { for (Object relatedObject : (Iterable<?>) target) { if (relatedObject.equals(srcObject)) { //the target is mapped to the source as well mapBothWays = true; } } } else if (target.getClass().isArray()) { for (Object relatedObject : (Object[]) target) { if (relatedObject.equals(srcObject)) { //the target is mapped to the source as well mapBothWays = true; } } } else { if (target.equals(srcObject)) { //the target is mapped to the source as well mapBothWays = true; } } } } } } return mapBothWays; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.