input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public void testToBean() throws SQLException, ParseException { int rowCount = 0; TestBean b = null; while (this.rs.next()) { b = (TestBean) processor.toBean(this.rs, TestBean.class); assertNotNull(b); rowCount++; } assertEquals(ROWS, rowCount); assertEquals("4", b.getOne()); assertEquals("5", b.getTwo()); assertEquals("6", b.getThree()); assertEquals("not set", b.getDoNotSet()); assertEquals(3, b.getIntTest()); assertEquals(new Integer(4), b.getIntegerTest()); assertEquals(null, b.getNullObjectTest()); assertEquals(0, b.getNullPrimitiveTest()); // test date -> string handling assertNotNull(b.getNotDate()); assertTrue(!"not a date".equals(b.getNotDate())); datef.parse(b.getNotDate()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public void testToBean() throws SQLException, ParseException { TestBean row = null; assertTrue(this.rs.next()); row = (TestBean) processor.toBean(this.rs, TestBean.class); assertEquals("1", row.getOne()); assertEquals("2", row.getTwo()); assertEquals("3", row.getThree()); assertEquals("not set", row.getDoNotSet()); assertTrue(this.rs.next()); row = (TestBean) processor.toBean(this.rs, TestBean.class); assertEquals("4", row.getOne()); assertEquals("5", row.getTwo()); assertEquals("6", row.getThree()); assertEquals("not set", row.getDoNotSet()); assertEquals(3, row.getIntTest()); assertEquals(new Integer(4), row.getIntegerTest()); assertEquals(null, row.getNullObjectTest()); assertEquals(0, row.getNullPrimitiveTest()); // test date -> string handling assertNotNull(row.getNotDate()); assertTrue(!"not a date".equals(row.getNotDate())); datef.parse(row.getNotDate()); assertFalse(this.rs.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initAuthEnv() { String paramUserName = getInitParameter(InitServletData.PARAM_NAME_USERNAME); if (!StringUtils.isEmpty(paramUserName)) { this.initServletData.setUsername(paramUserName); } String paramPassword = getInitParameter(InitServletData.PARAM_NAME_PASSWORD); if (!StringUtils.isEmpty(paramPassword)) { this.initServletData.setPassword(paramPassword); } try { String param = getInitParameter(InitServletData.PARAM_NAME_ALLOW); this.initServletData.setAllowList(parseStringToIP(param)); } catch (Exception e) { logger.error("initParameter config error, allow : {}", getInitParameter(InitServletData.PARAM_NAME_ALLOW), e); } try { String param = getInitParameter(InitServletData.PARAM_NAME_DENY); this.initServletData.setDenyList(parseStringToIP(param)); } catch (Exception e) { logger.error("initParameter config error, deny : {}", getInitParameter(InitServletData.PARAM_NAME_DENY), e); } // 采集缓存命中数据 redisTemplate = getRedisTemplate(); BeanFactory.getBean(StatsService.class).syncCacheStats(redisTemplate); } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code private void initAuthEnv() { String paramUserName = getInitParameter(InitServletData.PARAM_NAME_USERNAME); if (!StringUtils.isEmpty(paramUserName)) { this.initServletData.setUsername(paramUserName); } String paramPassword = getInitParameter(InitServletData.PARAM_NAME_PASSWORD); if (!StringUtils.isEmpty(paramPassword)) { this.initServletData.setPassword(paramPassword); } try { String param = getInitParameter(InitServletData.PARAM_NAME_ALLOW); this.initServletData.setAllowList(parseStringToIP(param)); } catch (Exception e) { logger.error("initParameter config error, allow : {}", getInitParameter(InitServletData.PARAM_NAME_ALLOW), e); } try { String param = getInitParameter(InitServletData.PARAM_NAME_DENY); this.initServletData.setDenyList(parseStringToIP(param)); } catch (Exception e) { logger.error("initParameter config error, deny : {}", getInitParameter(InitServletData.PARAM_NAME_DENY), e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() { MemoryIndex<String> mi = new MemoryIndex<String>(); FileIterator instanceFileIterator = IOUtil.instanceFileIterator("/home/ansj/workspace/ansj_seg/library/default.dic", IOUtil.UTF8); long start = System.currentTimeMillis(); System.out.println("begin init!"); while (instanceFileIterator.hasNext()) { String temp = instanceFileIterator.next(); temp = temp.split("\t")[0] ; // temp 是提示返回的元素 // temp 增加到搜索提示 // mi.str2QP("字符串转全拼") 比如 “中国” --》 "zhongguo" // new String(Pinyin.str2FirstCharArr(temp)) 字符串首字母拼音 比如 “中国” --》 "zg" mi.addItem(temp, temp ,mi.str2QP(temp), new String(Pinyin.str2FirstCharArr(temp))); } System.out.println("init ok use time " + (System.currentTimeMillis() - start)); System.out.println(mi.suggest("zg")); System.out.println(mi.suggest("zhongguo")); System.out.println(mi.suggest("中国")); } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test() { MemoryIndex<String> mi = new MemoryIndex<String>(); // FileIterator instanceFileIterator = IOUtil.instanceFileIterator("/home/ansj/workspace/ansj_seg/library/default.dic", IOUtil.UTF8); // long start = System.currentTimeMillis(); // System.out.println("begin init!"); // while (instanceFileIterator.hasNext()) { // String temp = instanceFileIterator.next(); // temp = temp.split("\t")[0] ; // // // temp 是提示返回的元素 // // temp 增加到搜索提示 // // mi.str2QP("字符串转全拼") 比如 “中国” --》 "zhongguo" // // new String(Pinyin.str2FirstCharArr(temp)) 字符串首字母拼音 比如 “中国” --》 "zg" // mi.addItem(temp, temp ,mi.str2QP(temp), new String(Pinyin.str2FirstCharArr(temp))); // } //增加新词 String temp = "中国" ; //生成各需要建立索引的字段 String quanpin = mi.str2QP(temp) ; //zhongguo String jianpinpin = new String(Pinyin.str2FirstCharArr(temp)) ; //zg //增加到索引中 mi.addItem(temp, temp ,quanpin,jianpinpin); System.out.println(mi.suggest("zg")); System.out.println(mi.suggest("zhongguo")); System.out.println(mi.suggest("中国")); System.out.println(mi.smartSuggest("中过")); System.out.println("init ok use time " + (System.currentTimeMillis() - start)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void saveModel(String filePath) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))) ; writeMap(bw,idWordMap) ; writeMap(bw,word2Mc) ; writeMap(bw,ww2Mc.get()) ; } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public void saveModel(String filePath) throws IOException { ObjectOutput oot = new ObjectOutputStream(new FileOutputStream(filePath)); oot.writeObject(this); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static int getIntValue(String value) { if (StringUtil.isBlank(value)) { return 0; } return castToInt(value); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public static int getIntValue(String value) { if (StringUtil.isBlank(value)) { return 0; } return castToInteger(value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void saveModel(String filePath) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))) ; writeMap(bw,idWordMap) ; writeMap(bw,word2Mc) ; writeMap(bw,ww2Mc.get()) ; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void saveModel(String filePath) throws IOException { ObjectOutput oot = new ObjectOutputStream(new FileOutputStream(filePath)); oot.writeObject(this); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); LOGGER.log(Level.FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); pod = client.pods().inNamespace(namespace).create(pod); LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); TaskListener runListener = template.getListener(); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } catch (InvalidPodTemplateException e) { LOGGER.info("Caught invalid pod template exception"); switch (e.getReason()) { case "ImagePullBackOff": runListener.getLogger().printf(e.getMessage()); PodUtils.cancelInvalidPodTemplateJob(pod, "ImagePullBackOff"); break; default: LOGGER.warning("Unknown reason for InvalidPodTemplateException : " + e.getReason()); break; } } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } } #location 51 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); LOGGER.log(Level.FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); pod = client.pods().inNamespace(namespace).create(pod); LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); TaskListener runListener = template.getListener(); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public AbstractFolderProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form == null) { return null; } // ignore modifications silently and return the unmodified object if the user // does not have the ADMINISTER Permission if (!userHasAdministerPermission()) { return this; } try { KubernetesFolderProperty newKubernetesFolderProperty = new KubernetesFolderProperty(); Set<String> inheritedGrants = new HashSet<>(); collectAllowedClouds(inheritedGrants, getOwner().getParent()); JSONArray names = form.names(); if (names != null) { for (Object name : names) { String strName = (String) name; if (strName.startsWith(PREFIX_USAGE_PERMISSION) && form.getBoolean(strName)) { String cloud = StringUtils.replaceOnce(strName, PREFIX_USAGE_PERMISSION, ""); if (isUsageRestrictedKubernetesCloud(Jenkins.getInstance().getCloud(cloud)) && !inheritedGrants.contains(cloud)) { newKubernetesFolderProperty.getPermittedClouds().add(cloud); } } } } return newKubernetesFolderProperty; } catch (JSONException jsonException) { LOGGER.severe(String.format("reconfigure failed: %s", jsonException.getMessage())); jsonException.printStackTrace(); return this; } } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public AbstractFolderProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form == null) { return null; } // ignore modifications silently and return the unmodified object if the user // does not have the ADMINISTER Permission if (!userHasAdministerPermission()) { return this; } try { Set<String> inheritedGrants = new HashSet<>(); collectAllowedClouds(inheritedGrants, getOwner().getParent()); Set<String> permittedClouds = new HashSet<>(); JSONArray names = form.names(); if (names != null) { for (Object name : names) { String strName = (String) name; if (strName.startsWith(PREFIX_USAGE_PERMISSION) && form.getBoolean(strName)) { String cloud = StringUtils.replaceOnce(strName, PREFIX_USAGE_PERMISSION, ""); if (isUsageRestrictedKubernetesCloud(Jenkins.get().getCloud(cloud)) && !inheritedGrants.contains(cloud)) { permittedClouds.add(cloud); } } } } this.permittedClouds.clear(); this.permittedClouds.addAll(permittedClouds); } catch (JSONException e) { LOGGER.log(Level.SEVERE, e, () -> "reconfigure failed: " + e.getMessage()); } return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Pod getPodTemplate(KubernetesSlave slave, Label label) { final PodTemplate template = getTemplate(label); String id = getIdForLabel(label); Pod pod = new Pod(); KubernetesHelper.setName(pod, slave.getNodeName()); pod.getMetadata().setLabels(getLabelsFor(id)); Container manifestContainer = new Container(); manifestContainer.setName(CONTAINER_NAME); manifestContainer.setImage(template.getImage()); if (template.isPrivileged()) manifestContainer.setSecurityContext(new SecurityContext(null, true, null, null)); List<EnvVar> env = new ArrayList<EnvVar>(3); // always add some env vars env.add(new EnvVar("JENKINS_SECRET", slave.getComputer().getJnlpMac(), null)); env.add(new EnvVar("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl(), null)); String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; env.add(new EnvVar("JENKINS_URL", url, null)); if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvVar("JENKINS_TUNNEL", jenkinsTunnel, null)); } url = url.endsWith("/") ? url : url + "/"; env.add(new EnvVar("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp", null)); manifestContainer.setEnv(env); // command: SECRET SLAVE_NAME List<String> cmd = parseDockerCommand(template.getCommand()); List<String> args = parseDockerCommand(template.getArgs()); args = args == null ? new ArrayList<String>(2) : args; args.add(slave.getComputer().getJnlpMac()); // secret args.add(slave.getComputer().getName()); // name manifestContainer.setCommand(cmd); manifestContainer.setArgs(args); List<Container> containers = new ArrayList<Container>(); containers.add(manifestContainer); PodSpec podSpec = new PodSpec(); pod.setSpec(podSpec); podSpec.setContainers(containers); podSpec.setRestartPolicy("Never"); return pod; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code private Pod getPodTemplate(KubernetesSlave slave, Label label) { final PodTemplate template = getTemplate(label); String id = getIdForLabel(label); List<EnvVar> env = new ArrayList<EnvVar>(3); // always add some env vars env.add(new EnvVar("JENKINS_SECRET", slave.getComputer().getJnlpMac(), null)); env.add(new EnvVar("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl(), null)); String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; env.add(new EnvVar("JENKINS_URL", url, null)); if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvVar("JENKINS_TUNNEL", jenkinsTunnel, null)); } url = url.endsWith("/") ? url : url + "/"; env.add(new EnvVar("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp", null)); return new PodBuilder() .withNewMetadata() .withName(slave.getNodeName()) .withLabels(getLabelsFor(id)) .endMetadata() .withNewSpec() .addNewContainer() .withName(CONTAINER_NAME) .withImage(template.getImage()) .withNewSecurityContext() .withPrivileged(template.isPrivileged()) .endSecurityContext() .withEnv(env) .withCommand(parseDockerCommand(template.getCommand())) .addToArgs(slave.getComputer().getJnlpMac()) .addToArgs(slave.getComputer().getName()) .endContainer() .withRestartPolicy("Never") .endSpec() .build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException { LOGGER.log(Level.FINE, "Building connection to Kubernetes host " + getDisplayName() + " URL " + serverUrl); if (client == null) { synchronized (this) { if (client == null) { client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout) .createClient(); } } } return client; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException { LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1}" + serverUrl, new String[] { getDisplayName(), serverUrl }); client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout).createClient(); LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}" + serverUrl, new String[] { getDisplayName(), serverUrl }); return client; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Pod getPodTemplate(KubernetesSlave slave, Label label) { DockerTemplate template = getTemplate(label); String id = getIdForLabel(label); Pod podTemplate = new Pod(); podTemplate.setId(slave.getNodeName()); // labels podTemplate.setLabels(getLabelsFor(id)); Container container = new Container(); container.setName(CONTAINER_NAME); container.setImage(template.image); // environment // List<EnvironmentVariable> env = new // ArrayList<EnvironmentVariable>(template.environment.length + 3); List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3); // always add some env vars env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac())); env.add(new EnvironmentVariable("JENKINS_URL", JenkinsLocationConfiguration.get().getUrl())); String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; url = url.endsWith("/") ? url : url + "/"; env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp")); if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel)); } // for (int i = 0; i < template.environment.length; i++) { // String[] split = template.environment[i].split("="); // env.add(new EnvironmentVariable(split[0], split[1])); // } container.setEnv(env); // ports // TODO open ports defined in template // container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) + // 49152)); // command: SECRET SLAVE_NAME List<String> cmd = parseDockerCommand(template.dockerCommand); cmd.addAll(ImmutableList.of(slave.getComputer().getJnlpMac(), slave.getComputer().getName())); container.setCommand(cmd); Manifest manifest = new Manifest(Collections.singletonList(container), null); podTemplate.setDesiredState(new State(manifest)); return podTemplate; } #location 40 #vulnerability type NULL_DEREFERENCE
#fixed code private Pod getPodTemplate(KubernetesSlave slave, Label label) { DockerTemplate template = getTemplate(label); String id = getIdForLabel(label); Pod podTemplate = new Pod(); podTemplate.setId(slave.getNodeName()); // labels podTemplate.setLabels(getLabelsFor(id)); Container container = new Container(); container.setName(CONTAINER_NAME); container.setImage(template.image); // environment // List<EnvironmentVariable> env = new // ArrayList<EnvironmentVariable>(template.environment.length + 3); List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3); // always add some env vars env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac())); env.add(new EnvironmentVariable("JENKINS_URL", JenkinsLocationConfiguration.get().getUrl())); String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; url = url.endsWith("/") ? url : url + "/"; env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp")); if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel)); } // for (int i = 0; i < template.environment.length; i++) { // String[] split = template.environment[i].split("="); // env.add(new EnvironmentVariable(split[0], split[1])); // } container.setEnv(env); // ports // TODO open ports defined in template // container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) + // 49152)); // command: SECRET SLAVE_NAME List<String> cmd = parseDockerCommand(template.dockerCommand); cmd = cmd == null ? new ArrayList<String>(2) : cmd; cmd.add(slave.getComputer().getJnlpMac()); // secret cmd.add(slave.getComputer().getName()); // name container.setCommand(cmd); Manifest manifest = new Manifest(Collections.singletonList(container), null); podTemplate.setDesiredState(new State(manifest)); return podTemplate; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void validatePod(Pod pod) { assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels()); // check containers Map<String, Container> containers = new HashMap<>(); for (Container c : pod.getSpec().getContainers()) { containers.put(c.getName(), c); } assertEquals(2, containers.size()); assertEquals("busybox", containers.get("busybox").getImage()); assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage()); // check volumes and volume mounts Map<String, Volume> volumes = new HashMap<>(); for (Volume v : pod.getSpec().getVolumes()) { volumes.put(v.getName(), v); } assertEquals(2, volumes.size()); assertNotNull(volumes.get("workspace-volume")); assertNotNull(volumes.get("empty-volume")); List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts(); assertEquals(1, mounts.size()); mounts = containers.get("jnlp").getVolumeMounts(); assertEquals(1, mounts.size()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code private void validatePod(Pod pod) { assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels()); // check containers Map<String, Container> containers = pod.getSpec().getContainers().stream() .collect(Collectors.toMap(Container::getName, Function.identity())); assertEquals(2, containers.size()); assertEquals("busybox", containers.get("busybox").getImage()); assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage()); // check volumes and volume mounts Map<String, Volume> volumes = pod.getSpec().getVolumes().stream() .collect(Collectors.toMap(Volume::getName, Function.identity())); assertEquals(3, volumes.size()); assertNotNull(volumes.get("workspace-volume")); assertNotNull(volumes.get("empty-volume")); assertNotNull(volumes.get("host-volume")); List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts(); assertEquals(2, mounts.size()); assertEquals(new VolumeMount("/container/data", "host-volume", null, null), mounts.get(0)); assertEquals(new VolumeMount("/home/jenkins", "workspace-volume", false, null), mounts.get(1)); mounts = containers.get("jnlp").getVolumeMounts(); assertEquals(1, mounts.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException { LOGGER.log(Level.FINE, "Building connection to Kubernetes host " + getDisplayName() + " URL " + serverUrl); if (client == null) { synchronized (this) { if (client == null) { client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout) .createClient(); } } } return client; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException { LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1}" + serverUrl, new String[] { getDisplayName(), serverUrl }); client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout).createClient(); LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}" + serverUrl, new String[] { getDisplayName(), serverUrl }); return client; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void validatePod(Pod pod) { assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels()); // check containers Map<String, Container> containers = new HashMap<>(); for (Container c : pod.getSpec().getContainers()) { containers.put(c.getName(), c); } assertEquals(2, containers.size()); assertEquals("busybox", containers.get("busybox").getImage()); assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage()); // check volumes and volume mounts Map<String, Volume> volumes = new HashMap<>(); for (Volume v : pod.getSpec().getVolumes()) { volumes.put(v.getName(), v); } assertEquals(2, volumes.size()); assertNotNull(volumes.get("workspace-volume")); assertNotNull(volumes.get("empty-volume")); List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts(); assertEquals(1, mounts.size()); mounts = containers.get("jnlp").getVolumeMounts(); assertEquals(1, mounts.size()); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private void validatePod(Pod pod) { assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels()); // check containers Map<String, Container> containers = pod.getSpec().getContainers().stream() .collect(Collectors.toMap(Container::getName, Function.identity())); assertEquals(2, containers.size()); assertEquals("busybox", containers.get("busybox").getImage()); assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage()); // check volumes and volume mounts Map<String, Volume> volumes = pod.getSpec().getVolumes().stream() .collect(Collectors.toMap(Volume::getName, Function.identity())); assertEquals(3, volumes.size()); assertNotNull(volumes.get("workspace-volume")); assertNotNull(volumes.get("empty-volume")); assertNotNull(volumes.get("host-volume")); List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts(); assertEquals(2, mounts.size()); assertEquals(new VolumeMount("/container/data", "host-volume", null, null), mounts.get(0)); assertEquals(new VolumeMount("/home/jenkins", "workspace-volume", false, null), mounts.get(1)); mounts = containers.get("jnlp").getVolumeMounts(); assertEquals(1, mounts.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException, ExecutionException { LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}", new String[] { getDisplayName(), serverUrl, namespace }); client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout, maxRequestsPerHost); LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl }); return client; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException, ExecutionException { LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}", new String[] { getDisplayName(), serverUrl, namespace }); KubernetesClient client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout, maxRequestsPerHost); LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl }); return client; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static List<KubernetesCloud> getUsageRestrictedKubernetesClouds() { List<KubernetesCloud> clouds = new ArrayList<>(); for (Cloud cloud : Jenkins.getInstance().clouds) { if(cloud instanceof KubernetesCloud) { if (((KubernetesCloud) cloud).isUsageRestricted()) { clouds.add((KubernetesCloud) cloud); } } } Collections.sort(clouds, CLOUD_BY_NAME); return clouds; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private static List<KubernetesCloud> getUsageRestrictedKubernetesClouds() { List<KubernetesCloud> clouds = Jenkins.get().clouds .getAll(KubernetesCloud.class) .stream() .filter(KubernetesCloud::isUsageRestricted) .collect(Collectors.toList()); Collections.sort(clouds, Comparator.<Cloud, String>comparing(o -> o.name)); return clouds; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); TaskListener runListener = template.getListener(); LOGGER.log(FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); try { pod = client.pods().inNamespace(namespace).create(pod); } catch (KubernetesClientException e) { int k8sCode = e.getCode(); if (k8sCode >= 400 && k8sCode < 500) { // 4xx runListener.getLogger().printf("ERROR: Unable to create pod. " + e.getMessage()); PodUtils.cancelQueueItemFor(pod, e.getMessage()); } else if (k8sCode >= 500 && k8sCode < 600) { // 5xx LOGGER.log(FINE,"Kubernetes code {0}. Retrying...", e.getCode()); } else { LOGGER.log(WARNING, "Unknown Kubernetes code {0}", e.getCode()); } throw e; } LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } } #location 42 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); TaskListener runListener = template.getListener(); LOGGER.log(FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); try { pod = client.pods().inNamespace(namespace).create(pod); } catch (KubernetesClientException e) { int httpCode = e.getCode(); if (400 <= httpCode && httpCode < 500) { // 4xx runListener.getLogger().printf("ERROR: Unable to create pod %s/%s.%n%s%n", namespace, pod.getMetadata().getName(), e.getMessage()); PodUtils.cancelQueueItemFor(pod, e.getMessage()); } else if (500 <= httpCode && httpCode < 600) { // 5xx LOGGER.log(FINE,"Kubernetes returned HTTP code {0} {1}. Retrying...", new Object[] {e.getCode(), e.getStatus()}); } else { LOGGER.log(WARNING, "Kubernetes returned unhandled HTTP code {0} {1}", new Object[] {e.getCode(), e.getStatus()}); } throw e; } LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Nonnull public KubernetesCloud getKubernetesCloud() { Cloud cloud = Jenkins.getInstance().getCloud(getCloudName()); if (cloud instanceof KubernetesCloud) { return (KubernetesCloud) cloud; } else { throw new IllegalStateException(getClass().getName() + " can be launched only by instances of " + KubernetesCloud.class.getName()); } } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Nonnull public KubernetesCloud getKubernetesCloud() { return getKubernetesCloud(getCloudName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void push(String item) throws IOException { if (getRun() == null) { LOGGER.warning("run is null, cannot push"); return; } synchronized (getRun()) { BulkChange bc = new BulkChange(getRun()); try { AbstractInvisibleRunAction2 action = getRun().getAction(AbstractInvisibleRunAction2.class); if (action == null) { action = new AbstractInvisibleRunAction2(getRun()); getRun().addAction(action); } action.stack.push(item); bc.commit(); } finally { bc.abort(); } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void push(String item) throws IOException { if (run == null) { LOGGER.warning("run is null, cannot push"); return; } synchronized (run) { BulkChange bc = new BulkChange(run); try { AbstractInvisibleRunAction2 action = run.getAction(this.getClass()); if (action == null) { action = createAction(run); run.addAction(action); } LOGGER.log(Level.INFO, "Pushing item {0} to action {1} in run {2}", new Object[] { item, action, run }); action.stack.push(item); bc.commit(); } finally { bc.abort(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onResume() { super.onResume(); Cloud cloud = Jenkins.getInstance().getCloud(cloudName); if (cloud == null) { throw new RuntimeException(String.format("Cloud does not exist: %s", cloudName)); } if (!(cloud instanceof KubernetesCloud)) { throw new RuntimeException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName, cloud.getClass().getName())); } KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; kubernetesCloud.addDynamicTemplate(newTemplate); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onResume() { super.onResume(); Cloud cloud = Jenkins.get().getCloud(cloudName); if (cloud == null) { throw new RuntimeException(String.format("Cloud does not exist: %s", cloudName)); } if (!(cloud instanceof KubernetesCloud)) { throw new RuntimeException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName, cloud.getClass().getName())); } KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; kubernetesCloud.addDynamicTemplate(newTemplate); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static boolean userHasAdministerPermission() { return Jenkins.getInstance().getACL().hasPermission(Jenkins.ADMINISTER); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private static boolean userHasAdministerPermission() { return Jenkins.get().hasPermission(Jenkins.ADMINISTER); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException, ExecutionException { LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}", new String[] { getDisplayName(), serverUrl, namespace }); client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout, maxRequestsPerHost); LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl }); return client; } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" }) public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateEncodingException, ExecutionException { LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}", new String[] { getDisplayName(), serverUrl, namespace }); KubernetesClient client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout, maxRequestsPerHost); LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl }); return client; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Node call() throws Exception { RetentionStrategy retentionStrategy; if (t.getIdleMinutes() == 0) { retentionStrategy = new OnceRetentionStrategy(cloud.getRetentionTimeout()); } else { retentionStrategy = new CloudRetentionStrategy(t.getIdleMinutes()); } final PodTemplate unwrappedTemplate = PodTemplateUtils.unwrap(cloud.getTemplate(label), cloud.getDefaultsProviderTemplate(), cloud.getTemplates()); return new KubernetesSlave(unwrappedTemplate, unwrappedTemplate.getName(), cloud.name, unwrappedTemplate.getLabel(), retentionStrategy); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public Node call() throws Exception { return KubernetesSlave .builder() .podTemplate(cloud.getUnwrappedTemplate(t)) .cloud(cloud) .build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void runWithDeadlineSeconds() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "Deadline"); p.setDefinition(new CpsFlowDefinition(loadPipelineScript("runWithDeadlineSeconds.groovy") , true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); assertNotNull(b); r.waitForMessage("podTemplate", b); PodTemplate deadlineTemplate = null; for (Iterator<PodTemplate> iterator = cloud.getTemplates().iterator(); iterator.hasNext(); ) { PodTemplate template = iterator.next(); if (template.getLabel() == "deadline") { deadlineTemplate = template; } } assertNotNull(deadlineTemplate); assertEquals(3600, deadlineTemplate.getDeadlineSeconds()); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void runWithDeadlineSeconds() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "Deadline"); p.setDefinition(new CpsFlowDefinition(loadPipelineScript("runWithDeadlineSeconds.groovy") , true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); assertNotNull(b); r.waitForMessage("podTemplate", b); PodTemplate deadlineTemplate = cloud.getTemplates().stream().filter(x -> x.getLabel() == "deadline").findAny().get(); assertEquals(10, deadlineTemplate.getDeadlineSeconds()); assertNotNull(deadlineTemplate); r.assertLogNotContains("Hello from container!", b); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean start() throws Exception { Cloud cloud = Jenkins.getInstance().getCloud(cloudName); if (cloud == null) { throw new AbortException(String.format("Cloud does not exist: %s", cloudName)); } if (!(cloud instanceof KubernetesCloud)) { throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName, cloud.getClass().getName())); } KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; Run<?, ?> run = getContext().get(Run.class); if (kubernetesCloud.isUsageRestricted()) { checkAccess(run, kubernetesCloud); } PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class); String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null; String label = step.getLabel(); if (label == null) { label = labelify(run.getExternalizableId()); } //Let's generate a random name based on the user specified to make sure that we don't have //issues with concurrent builds, or messing with pre-existing configuration String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789"); String stepName = step.getName(); if (stepName == null) { stepName = label; } String name = String.format(NAME_FORMAT, stepName, randString); String namespace = checkNamespace(kubernetesCloud, podTemplateContext); newTemplate = new PodTemplate(); newTemplate.setName(name); newTemplate.setNamespace(namespace); if (step.getInheritFrom() == null) { newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates)); } else { newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom())); } newTemplate.setInstanceCap(step.getInstanceCap()); newTemplate.setIdleMinutes(step.getIdleMinutes()); newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout()); newTemplate.setLabel(label); newTemplate.setEnvVars(step.getEnvVars()); newTemplate.setVolumes(step.getVolumes()); if (step.getWorkspaceVolume() != null) { newTemplate.setWorkspaceVolume(step.getWorkspaceVolume()); } newTemplate.setContainers(step.getContainers()); newTemplate.setNodeSelector(step.getNodeSelector()); newTemplate.setNodeUsageMode(step.getNodeUsageMode()); newTemplate.setServiceAccount(step.getServiceAccount()); newTemplate.setAnnotations(step.getAnnotations()); newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy()); if(run!=null) { String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull(); if(url != null) { newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl())); } } newTemplate.setImagePullSecrets( step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList())); newTemplate.setYaml(step.getYaml()); if (step.isShowRawYamlSet()) { newTemplate.setShowRawYaml(step.isShowRawYaml()); } newTemplate.setPodRetention(step.getPodRetention()); if(step.getActiveDeadlineSeconds() != 0) { newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds()); } for (ContainerTemplate container : newTemplate.getContainers()) { if (!PodTemplateUtils.validateContainerName(container.getName())) { throw new AbortException(Messages.RFC1123_error(container.getName())); } } Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls()); if (!errors.isEmpty()) { throw new AbortException(Messages.RFC1123_error(String.join(", ", errors))); } // Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally. if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) { throw new AbortException(Messages.label_error(newTemplate.getLabel())); } kubernetesCloud.addDynamicTemplate(newTemplate); BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate)); if (step.getLabel() == null) { invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label)))); } invoker.start(); return false; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean start() throws Exception { Cloud cloud = Jenkins.get().getCloud(cloudName); if (cloud == null) { throw new AbortException(String.format("Cloud does not exist: %s", cloudName)); } if (!(cloud instanceof KubernetesCloud)) { throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName, cloud.getClass().getName())); } KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; Run<?, ?> run = getContext().get(Run.class); if (kubernetesCloud.isUsageRestricted()) { checkAccess(run, kubernetesCloud); } PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class); String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null; String label = step.getLabel(); if (label == null) { label = labelify(run.getExternalizableId()); } //Let's generate a random name based on the user specified to make sure that we don't have //issues with concurrent builds, or messing with pre-existing configuration String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789"); String stepName = step.getName(); if (stepName == null) { stepName = label; } String name = String.format(NAME_FORMAT, stepName, randString); String namespace = checkNamespace(kubernetesCloud, podTemplateContext); newTemplate = new PodTemplate(); newTemplate.setName(name); newTemplate.setNamespace(namespace); if (step.getInheritFrom() == null) { newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates)); } else { newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom())); } newTemplate.setInstanceCap(step.getInstanceCap()); newTemplate.setIdleMinutes(step.getIdleMinutes()); newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout()); newTemplate.setLabel(label); newTemplate.setEnvVars(step.getEnvVars()); newTemplate.setVolumes(step.getVolumes()); if (step.getWorkspaceVolume() != null) { newTemplate.setWorkspaceVolume(step.getWorkspaceVolume()); } newTemplate.setContainers(step.getContainers()); newTemplate.setNodeSelector(step.getNodeSelector()); newTemplate.setNodeUsageMode(step.getNodeUsageMode()); newTemplate.setServiceAccount(step.getServiceAccount()); newTemplate.setAnnotations(step.getAnnotations()); newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy()); if(run!=null) { String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull(); if(url != null) { newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl())); } } newTemplate.setImagePullSecrets( step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList())); newTemplate.setYaml(step.getYaml()); if (step.isShowRawYamlSet()) { newTemplate.setShowRawYaml(step.isShowRawYaml()); } newTemplate.setPodRetention(step.getPodRetention()); if(step.getActiveDeadlineSeconds() != 0) { newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds()); } for (ContainerTemplate container : newTemplate.getContainers()) { if (!PodTemplateUtils.validateContainerName(container.getName())) { throw new AbortException(Messages.RFC1123_error(container.getName())); } } Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls()); if (!errors.isEmpty()) { throw new AbortException(Messages.RFC1123_error(String.join(", ", errors))); } // Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally. if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) { throw new AbortException(Messages.label_error(newTemplate.getLabel())); } kubernetesCloud.addDynamicTemplate(newTemplate); BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate)); if (step.getLabel() == null) { invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label)))); } invoker.start(); return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean addProvisionedSlave(@Nonnull PodTemplate template, @CheckForNull Label label) throws Exception { if (containerCap == 0) { return true; } KubernetesClient client = connect(); String templateNamespace = template.getNamespace(); // If template's namespace is not defined, take the // Kubernetes Namespace. if (Strings.isNullOrEmpty(templateNamespace)) { templateNamespace = client.getNamespace(); } PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(getLabels()).list(); List<Pod> allActiveSlavePods = null; // JENKINS-53370 check for nulls if (slaveList != null && slaveList.getItems() != null) { allActiveSlavePods = slaveList.getItems().stream() // .filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)")) .collect(Collectors.toList()); } Map<String, String> labelsMap = new HashMap<>(this.getLabels()); labelsMap.putAll(template.getLabelsMap()); PodList templateSlaveList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list(); List<Pod> activeTemplateSlavePods = templateSlaveList.getItems().stream() .filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)")) .collect(Collectors.toList()); if (allActiveSlavePods != null && containerCap <= allActiveSlavePods.size()) { LOGGER.log(Level.INFO, "Total container cap of {0} reached, not provisioning: {1} running or pending in namespace {2} with Kubernetes labels {3}", new Object[] { containerCap, allActiveSlavePods.size(), templateNamespace, getLabels() }); return false; } if (activeTemplateSlavePods != null && allActiveSlavePods != null && template.getInstanceCap() <= activeTemplateSlavePods.size()) { LOGGER.log(Level.INFO, "Template instance cap of {0} reached for template {1}, not provisioning: {2} running or pending in namespace {3} with label \"{4}\" and Kubernetes labels {5}", new Object[] { template.getInstanceCap(), template.getName(), allActiveSlavePods.size(), templateNamespace, label == null ? "" : label.toString(), labelsMap }); return false; } return true; } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean addProvisionedSlave(@Nonnull PodTemplate template, @CheckForNull Label label) throws Exception { if (containerCap == 0) { return true; } KubernetesClient client = connect(); String templateNamespace = template.getNamespace(); // If template's namespace is not defined, take the // Kubernetes Namespace. if (Strings.isNullOrEmpty(templateNamespace)) { templateNamespace = client.getNamespace(); } PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(getLabels()).list(); List<Pod> allActiveSlavePods = null; // JENKINS-53370 check for nulls if (slaveList != null && slaveList.getItems() != null) { allActiveSlavePods = slaveList.getItems().stream() // .filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)")) .collect(Collectors.toList()); } Map<String, String> labelsMap = new HashMap<>(this.getLabels()); labelsMap.putAll(template.getLabelsMap()); PodList templateSlaveList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list(); // JENKINS-53370 check for nulls List<Pod> activeTemplateSlavePods = null; if (templateSlaveList != null && templateSlaveList.getItems() != null) { activeTemplateSlavePods = templateSlaveList.getItems().stream() .filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)")) .collect(Collectors.toList()); } if (allActiveSlavePods != null && containerCap <= allActiveSlavePods.size()) { LOGGER.log(Level.INFO, "Total container cap of {0} reached, not provisioning: {1} running or pending in namespace {2} with Kubernetes labels {3}", new Object[] { containerCap, allActiveSlavePods.size(), templateNamespace, getLabels() }); return false; } if (activeTemplateSlavePods != null && allActiveSlavePods != null && template.getInstanceCap() <= activeTemplateSlavePods.size()) { LOGGER.log(Level.INFO, "Template instance cap of {0} reached for template {1}, not provisioning: {2} running or pending in namespace {3} with label \"{4}\" and Kubernetes labels {5}", new Object[] { template.getInstanceCap(), template.getName(), allActiveSlavePods.size(), templateNamespace, label == null ? "" : label.toString(), labelsMap }); return false; } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String pop() throws IOException { if (getRun() == null) { LOGGER.warning("run is null, cannot pop"); return null; } synchronized (getRun()) { BulkChange bc = new BulkChange(getRun()); try { AbstractInvisibleRunAction2 action = getRun().getAction(AbstractInvisibleRunAction2.class); if (action == null) { action = new AbstractInvisibleRunAction2(getRun()); getRun().addAction(action); } String template = action.stack.pop(); bc.commit(); return template; } finally { bc.abort(); } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public String pop() throws IOException { if (run == null) { LOGGER.warning("run is null, cannot pop"); return null; } synchronized (getRun()) { BulkChange bc = new BulkChange(getRun()); try { AbstractInvisibleRunAction2 action = getRun().getAction(this.getClass()); if (action == null) { action = createAction(getRun()); getRun().addAction(action); } String item = action.stack.pop(); LOGGER.log(Level.INFO, "Popped item {0} from action {1} in run {2}", new Object[] { item, action, run }); bc.commit(); return item; } finally { bc.abort(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void runInPod() throws Exception { List<PodTemplate> templates = null; while (b.isBuilding() && (templates = podTemplatesWithLabel(name.getMethodName(), cloud.getAllTemplates())).isEmpty()) { LOGGER.log(Level.INFO, "Waiting for runInPod template to be created"); Thread.sleep(1000); } // check if build failed assertTrue("Build has failed early: " + b.getResult(), b.isBuilding() || Result.SUCCESS.equals(b.getResult())); LOGGER.log(Level.INFO, "Found templates with label runInPod: {0}", templates); for (PodTemplate template : cloud.getAllTemplates()) { LOGGER.log(Level.INFO, "Cloud template \"{0}\" labels: {1}", new Object[] { template.getName(), template.getLabelSet() }); } Map<String, String> labels = getLabels(cloud, this, name); PodList pods = new PodListBuilder().withItems(Collections.emptyList()).build(); while (pods.getItems().isEmpty()) { LOGGER.log(Level.INFO, "Waiting for pods to be created with labels: {0}", labels); pods = cloud.connect().pods().withLabels(labels).list(); Thread.sleep(1000); } for (String msg : logs.getMessages()) { System.out.println(msg); } assertThat(templates, hasSize(1)); PodTemplate template = templates.get(0); List<PodAnnotation> annotations = template.getAnnotations(); assertNotNull(annotations); boolean foundBuildUrl=false; for(PodAnnotation pd : annotations) { if(pd.getKey().equals("buildUrl")) { assertTrue(pd.getValue().contains(p.getUrl())); foundBuildUrl=true; } } assertTrue(foundBuildUrl); assertEquals(Integer.MAX_VALUE, template.getInstanceCap()); assertThat(template.getLabelsMap(), hasEntry("jenkins/" + name.getMethodName(), "true")); assertThat( "Expected one pod with labels " + labels + " but got: " + pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()), pods.getItems(), hasSize(1)); Pod pod = pods.getItems().get(0); LOGGER.log(Level.INFO, "One pod found: {0}", pod); assertThat(pod.getMetadata().getLabels(), hasEntry("jenkins", "slave")); assertThat("Pod labels are wrong: " + pod, pod.getMetadata().getLabels(), hasEntry("jenkins/" + name.getMethodName(), "true")); r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("script file contents: ", b); assertFalse("There are pods leftover after test execution, see previous logs", deletePods(cloud.connect(), getLabels(cloud, this, name), true)); } #location 31 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void runInPod() throws Exception { SemaphoreStep.waitForStart("podTemplate/1", b); List<PodTemplate> templates = podTemplatesWithLabel(name.getMethodName(), cloud.getAllTemplates()); assertThat(templates, hasSize(1)); SemaphoreStep.success("podTemplate/1", null); // check if build failed assertTrue("Build has failed early: " + b.getResult(), b.isBuilding() || Result.SUCCESS.equals(b.getResult())); LOGGER.log(Level.INFO, "Found templates with label runInPod: {0}", templates); for (PodTemplate template : cloud.getAllTemplates()) { LOGGER.log(Level.INFO, "Cloud template \"{0}\" labels: {1}", new Object[] { template.getName(), template.getLabelSet() }); } Map<String, String> labels = getLabels(cloud, this, name); SemaphoreStep.waitForStart("pod/1", b); PodList pods = cloud.connect().pods().withLabels(labels).list(); assertThat( "Expected one pod with labels " + labels + " but got: " + pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()), pods.getItems(), hasSize(1)); SemaphoreStep.success("pod/1", null); for (String msg : logs.getMessages()) { System.out.println(msg); } PodTemplate template = templates.get(0); List<PodAnnotation> annotations = template.getAnnotations(); assertNotNull(annotations); boolean foundBuildUrl=false; for(PodAnnotation pd : annotations) { if(pd.getKey().equals("buildUrl")) { assertTrue(pd.getValue().contains(p.getUrl())); foundBuildUrl=true; } } assertTrue(foundBuildUrl); assertEquals(Integer.MAX_VALUE, template.getInstanceCap()); assertThat(template.getLabelsMap(), hasEntry("jenkins/" + name.getMethodName(), "true")); Pod pod = pods.getItems().get(0); LOGGER.log(Level.INFO, "One pod found: {0}", pod); assertThat(pod.getMetadata().getLabels(), hasEntry("jenkins", "slave")); assertThat("Pod labels are wrong: " + pod, pod.getMetadata().getLabels(), hasEntry("jenkins/" + name.getMethodName(), "true")); r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("script file contents: ", b); assertFalse("There are pods leftover after test execution, see previous logs", deletePods(cloud.connect(), getLabels(cloud, this, name), true)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Pod getPodTemplate(KubernetesSlave slave, Label label) { DockerTemplate template = getTemplate(label); String id = getIdForLabel(label); Pod podTemplate = new Pod(); podTemplate.setId(slave.getNodeName()); // labels podTemplate.setLabels(getLabelsFor(id)); Container container = new Container(); container.setName(CONTAINER_NAME); container.setImage(template.getImage()); // environment // List<EnvironmentVariable> env = new // ArrayList<EnvironmentVariable>(template.environment.length + 3); List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3); // always add some env vars env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac())); env.add(new EnvironmentVariable("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl())); if (!StringUtils.isBlank(jenkinsUrl)) { env.add(new EnvironmentVariable("JENKINS_URL", jenkinsUrl)); } if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel)); } String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; url = url.endsWith("/") ? url : url + "/"; env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp")); // for (int i = 0; i < template.environment.length; i++) { // String[] split = template.environment[i].split("="); // env.add(new EnvironmentVariable(split[0], split[1])); // } container.setEnv(env); // ports // TODO open ports defined in template // container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) + // 49152)); // command: SECRET SLAVE_NAME List<String> cmd = parseDockerCommand(template.dockerCommand); cmd = cmd == null ? new ArrayList<String>(2) : cmd; cmd.add(slave.getComputer().getJnlpMac()); // secret cmd.add(slave.getComputer().getName()); // name container.setCommand(cmd); Manifest manifest = new Manifest(Collections.singletonList(container), null); podTemplate.setDesiredState(new State(manifest)); return podTemplate; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code private Pod getPodTemplate(KubernetesSlave slave, Label label) { DockerTemplate template = getTemplate(label); String id = getIdForLabel(label); Pod podTemplate = new Pod(); /* podTemplate.setId(slave.getNodeName()); // labels podTemplate.setLabels(getLabelsFor(id)); Container container = new Container(); container.setName(CONTAINER_NAME); container.setImage(template.getImage()); // environment // List<EnvironmentVariable> env = new // ArrayList<EnvironmentVariable>(template.environment.length + 3); List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3); // always add some env vars env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac())); env.add(new EnvironmentVariable("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl())); if (!StringUtils.isBlank(jenkinsUrl)) { env.add(new EnvironmentVariable("JENKINS_URL", jenkinsUrl)); } if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel)); } String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; url = url.endsWith("/") ? url : url + "/"; env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp")); // for (int i = 0; i < template.environment.length; i++) { // String[] split = template.environment[i].split("="); // env.add(new EnvironmentVariable(split[0], split[1])); // } container.setEnv(env); // ports // TODO open ports defined in template // container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) + // 49152)); // command: SECRET SLAVE_NAME List<String> cmd = parseDockerCommand(template.dockerCommand); cmd = cmd == null ? new ArrayList<String>(2) : cmd; cmd.add(slave.getComputer().getJnlpMac()); // secret cmd.add(slave.getComputer().getName()); // name container.setCommand(cmd); Manifest manifest = new Manifest(Collections.singletonList(container), null); podTemplate.setDesiredState(new State(manifest)); */ return podTemplate; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public InputStream getData(String resourceId) throws IOException { LoadableResource load = this.resources.get(resourceId); if (Objects.nonNull(load)) { load.getDataStream(); } throw new IllegalArgumentException("No such resource: " + resourceId); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Override public InputStream getData(String resourceId) throws IOException { LoadableResource load = this.resources.get(resourceId); if (Objects.nonNull(load)) { return load.getDataStream(); } throw new IllegalArgumentException("No such resource: " + resourceId); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { if (!isAvailable(conversionQuery)) { return null; } CurrencyUnit base = conversionQuery.getBaseCurrency(); CurrencyUnit term = conversionQuery.getCurrency(); LocalDate timestamp = conversionQuery.get(LocalDate.class); if (timestamp == null) { LocalDateTime dateTime = conversionQuery.get(LocalDateTime.class); if (dateTime != null) { timestamp = dateTime.toLocalDate(); } } ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp); ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp); if (base.equals(SDR)) { return rate2; } else if (term.equals(SDR)) { return rate1; } if (Objects.isNull(rate1) || Objects.isNull(rate2)) { return null; } ExchangeRateBuilder builder = new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC)); builder.setBase(base); builder.setTerm(term); builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor())); builder.setRateChain(rate1, rate2); return builder.build(); } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { if (!isAvailable(conversionQuery)) { return null; } CurrencyUnit base = conversionQuery.getBaseCurrency(); CurrencyUnit term = conversionQuery.getCurrency(); LocalDate timestamp = getTimeStamp(conversionQuery); ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp); ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp); if (base.equals(SDR)) { return rate2; } else if (term.equals(SDR)) { return rate1; } if (Objects.isNull(rate1) || Objects.isNull(rate2)) { return null; } ExchangeRateBuilder builder = new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC)); builder.setBase(base); builder.setTerm(term); builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor())); builder.setRateChain(rate1, rate2); return builder.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected boolean load(URI itemToLoad, boolean fallbackLoad) { InputStream is = null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { URLConnection conn = itemToLoad.toURL().openConnection(); byte[] data = new byte[4096]; is = conn.getInputStream(); int read = is.read(data); while (read > 0) { stream.write(data, 0, read); read = is.read(data); } setData(stream.toByteArray()); if (!fallbackLoad) { writeCache(); lastLoaded = System.currentTimeMillis(); loadCount.incrementAndGet(); } return true; } catch (Exception e) { LOG.log(Level.INFO, "Failed to load resource input for " + resourceId + " from " + itemToLoad, e); } finally { if (Objects.nonNull(is)) { try { is.close(); } catch (Exception e) { LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e); } } try { stream.close(); } catch (IOException e) { LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e); } } return false; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code protected boolean load(URI itemToLoad, boolean fallbackLoad) { InputStream is = null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); try{ URLConnection conn; String proxyPort = this.properties.get("proxy.port"); String proxyHost = this.properties.get("proxy.host"); String proxyType = this.properties.get("procy.type"); if(proxyType!=null){ Proxy proxy = new Proxy(Proxy.Type.valueOf(proxyType.toUpperCase()), InetSocketAddress.createUnresolved(proxyHost, Integer.parseInt(proxyPort))); conn = itemToLoad.toURL().openConnection(proxy); }else{ conn = itemToLoad.toURL().openConnection(); } byte[] data = new byte[4096]; is = conn.getInputStream(); int read = is.read(data); while (read > 0) { stream.write(data, 0, read); read = is.read(data); } setData(stream.toByteArray()); if (!fallbackLoad) { writeCache(); lastLoaded = System.currentTimeMillis(); loadCount.incrementAndGet(); } return true; } catch (Exception e) { LOG.log(Level.INFO, "Failed to load resource input for " + resourceId + " from " + itemToLoad, e); } finally { if (Objects.nonNull(is)) { try { is.close(); } catch (Exception e) { LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e); } } try { stream.close(); } catch (IOException e) { LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { if (!isAvailable(conversionQuery)) { return null; } CurrencyUnit base = conversionQuery.getBaseCurrency(); CurrencyUnit term = conversionQuery.getCurrency(); LocalDate timestamp = conversionQuery.get(LocalDate.class); if (timestamp == null) { LocalDateTime dateTime = conversionQuery.get(LocalDateTime.class); if (dateTime != null) { timestamp = dateTime.toLocalDate(); } } ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp); ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp); if (base.equals(SDR)) { return rate2; } else if (term.equals(SDR)) { return rate1; } if (Objects.isNull(rate1) || Objects.isNull(rate2)) { return null; } ExchangeRateBuilder builder = new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC)); builder.setBase(base); builder.setTerm(term); builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor())); builder.setRateChain(rate1, rate2); return builder.build(); } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { if (!isAvailable(conversionQuery)) { return null; } CurrencyUnit base = conversionQuery.getBaseCurrency(); CurrencyUnit term = conversionQuery.getCurrency(); LocalDate timestamp = getTimeStamp(conversionQuery); ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp); ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp); if (base.equals(SDR)) { return rate2; } else if (term.equals(SDR)) { return rate1; } if (Objects.isNull(rate1) || Objects.isNull(rate2)) { return null; } ExchangeRateBuilder builder = new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC)); builder.setBase(base); builder.setTerm(term); builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor())); builder.setRateChain(rate1, rate2); return builder.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void copy(InputStream source, File dest) throws IOException { FileOutputStream fos = new FileOutputStream(dest); copy(source, fos); fos.close(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static void copy(InputStream source, File dest) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(dest); copy(source, fos); } finally { if (fos != null) try {fos.close();} catch (Exception e) {} } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void deleteNode(Handle handle) throws IOException { if (cachesize != 0) { Node n = (Node) cache.get(handle); if (n != null) { cacheScore.deleteScore(handle); cache.remove(handle); } } dispose(handle); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void deleteNode(Handle handle) throws IOException { if (cachesize != 0) { Node n = (Node) cache.get(handle); if (n != null) synchronized (cache) { cacheScore.deleteScore(handle); cache.remove(handle); } } dispose(handle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { serverLog.logSystem("PLASMA INDEXING", "started word cache management"); int check; // permanently flush cache elements while (!(terminate)) { if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {} while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try { //check = hashScore.size(); flushSpecific(false); //serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size()); try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {} } catch (IOException e) { serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage()); e.printStackTrace(); terminate = true; cache = null; } } serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush"); // close all; try { // first flush everything while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) { flushSpecific(false); } // then close file cache: pic.close(); } catch (IOException e) { serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString()); } // report if (hashScore.size() == 0) serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words"); else serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost"); // delete data cache = null; hashScore = null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { serverLog.logSystem("PLASMA INDEXING", "started word cache management"); int check; // permanently flush cache elements while (!(terminate)) { if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {} while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try { check = hashScore.size(); flushSpecific(false); //serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size()); try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {} } catch (IOException e) { serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage()); e.printStackTrace(); terminate = true; cache = null; } } serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush"); // close all; try { // first flush everything while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) { flushSpecific(false); } // then close file cache: pic.close(); } catch (IOException e) { serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString()); } // report if (hashScore.size() == 0) serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words"); else serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost"); // delete data cache = null; hashScore = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String readLine() throws IOException { // with these functions, we consider a line as always terminated by CRLF serverByteBuffer sb = new serverByteBuffer(); int c; while (true) { c = read(); if (c < 0) { if (sb.length() == 0) return null; else return sb.toString(); } if (c == cr) continue; if (c == lf) return sb.toString(); sb.append((byte) c); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public String readLine() throws IOException { // with these functions, we consider a line as always terminated by CRLF byte[] bb = new byte[80]; int bbsize = 0; int c; while (true) { c = read(); if (c < 0) { if (bbsize == 0) return null; else return new String(bb, 0, bbsize); } if (c == cr) continue; if (c == lf) return new String(bb, 0, bbsize); // append to bb if (bbsize == bb.length) { // extend bb size byte[] newbb = new byte[bb.length * 2]; System.arraycopy(bb, 0, newbb, 0, bb.length); bb = newbb; newbb = null; } bb[bbsize++] = (byte) c; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void respondError(OutputStream respond, String origerror, int errorcase, String url) { try { // set rewrite values serverObjects tp = new serverObjects(); tp.put("errormessage", errorcase); tp.put("httperror", origerror); tp.put("url", url); // rewrite the file File file = new File(htRootPath, "/proxymsg/error.html"); byte[] result; ByteArrayOutputStream o = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(file); httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes()); o.close(); result = o.toByteArray(); // return header httpHeader header = new httpHeader(); header.put("Date", httpc.dateString(httpc.nowDate())); header.put("Content-type", "text/html"); header.put("Content-length", "" + o.size()); header.put("Pragma", "no-cache"); // write the array to the client respondHeader(respond, origerror, header); serverFileUtils.write(result, respond); respond.flush(); } catch (IOException e) { } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code private void respondError(OutputStream respond, String origerror, int errorcase, String url) { FileInputStream fis = null; try { // set rewrite values serverObjects tp = new serverObjects(); tp.put("errormessage", errorcase); tp.put("httperror", origerror); tp.put("url", url); // rewrite the file File file = new File(htRootPath, "/proxymsg/error.html"); byte[] result; ByteArrayOutputStream o = new ByteArrayOutputStream(); fis = new FileInputStream(file); httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes()); o.close(); result = o.toByteArray(); // return header httpHeader header = new httpHeader(); header.put("Date", httpc.dateString(httpc.nowDate())); header.put("Content-type", "text/html"); header.put("Content-length", "" + o.size()); header.put("Pragma", "no-cache"); // write the array to the client respondHeader(respond, origerror, header); serverFileUtils.write(result, respond); respond.flush(); } catch (IOException e) { } finally { if (fis != null) try { fis.close(); } catch (Exception e) {} } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { serverLog.logSystem("PLASMA INDEXING", "started word cache management"); int check; // permanently flush cache elements while (!(terminate)) { if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {} while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try { //check = hashScore.size(); flushSpecific(false); //serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size()); try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {} } catch (IOException e) { serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage()); e.printStackTrace(); terminate = true; cache = null; } } serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush"); // close all; try { // first flush everything while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) { flushSpecific(false); } // then close file cache: pic.close(); } catch (IOException e) { serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString()); } // report if (hashScore.size() == 0) serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words"); else serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost"); // delete data cache = null; hashScore = null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { serverLog.logSystem("PLASMA INDEXING", "started word cache management"); int check; // permanently flush cache elements while (!(terminate)) { if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {} while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try { check = hashScore.size(); flushSpecific(false); //serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size()); try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {} } catch (IOException e) { serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage()); e.printStackTrace(); terminate = true; cache = null; } } serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush"); // close all; try { // first flush everything while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) { flushSpecific(false); } // then close file cache: pic.close(); } catch (IOException e) { serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString()); } // report if (hashScore.size() == 0) serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words"); else serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost"); // delete data cache = null; hashScore = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static TreeMap loadMap(String mapname, String filename, String sep) { TreeMap map = new TreeMap(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; int pos; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0)) map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim()); } br.close(); serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename); } catch (IOException e) {} return map; } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code private static TreeMap loadMap(String mapname, String filename, String sep) { TreeMap map = new TreeMap(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; int pos; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0)) map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim()); } serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename); } catch (IOException e) { } finally { if (br != null) try { br.close(); } catch (Exception e) {} } return map; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private int flushFromMemToLimit() { if ((hashScore.size() == 0) && (cache.size() == 0)) { serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty"); return 0; } if ((hashScore.size() == 0) && (cache.size() != 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size()); return 0; } if ((hashScore.size() != 0) && (cache.size() == 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0"); return 0; } //serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size()); int total = 0; synchronized (hashScore) { String key; int count; Long createTime; // flush high-scores while ((total < 100) && (hashScore.size() >= maxWords)) { key = (String) hashScore.getMaxObject(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count < 5) { log.logWarning("flushing of high-key " + key + " not appropriate (too less entries, count=" + count + "): increase cache size"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) { //log.logDebug("high-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); break; } //log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); total += flushFromMem(key); } // flush singletons while ((total < 200) && (hashScore.size() >= maxWords)) { key = (String) hashScore.getMinObject(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count > 1) { //log.logDebug("flush of singleton-key " + key + ": count too high (count=" + count + ")"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) { //log.logDebug("singleton-key " + key + " is too fresh, interruptiong flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); break; } //log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); total += flushFromMem(key); } } return total; } #location 36 #vulnerability type NULL_DEREFERENCE
#fixed code private int flushFromMemToLimit() { if ((hashScore.size() == 0) && (cache.size() == 0)) { serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty"); return 0; } if ((hashScore.size() == 0) && (cache.size() != 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size()); return 0; } if ((hashScore.size() != 0) && (cache.size() == 0)) { serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0"); return 0; } //serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size()); int total = 0; synchronized (hashScore) { String key; int count; Long createTime; // flush high-scores while ((total < 100) && (hashScore.size() >= maxWords)) { key = (String) hashScore.getMaxObject(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count < 5) { log.logWarning("flushing of high-key " + key + " not appropriate (too less entries, count=" + count + "): increase cache size"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) { //log.logDebug("high-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); break; } //log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); total += flushFromMem(key, false); } // flush singletons Iterator i = hashScore.scores(true); ArrayList al = new ArrayList(); while ((i.hasNext()) && (total < 200)) { key = (String) i.next(); createTime = (Long) hashDate.get(key); count = hashScore.getScore(key); if (count > 1) { //log.logDebug("flush of singleton-key " + key + ": count too high (count=" + count + ")"); break; } if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 90000)) { //log.logDebug("singleton-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")"); continue; } //log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size()); al.add(key); total++; } for (int k = 0; k < al.size(); k++) flushFromMem((String) al.get(k), true); } return total; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void copy(File source, OutputStream dest) throws IOException { InputStream fis = new FileInputStream(source); copy(fis, dest); fis.close(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static void copy(File source, OutputStream dest) throws IOException { InputStream fis = null; try { fis = new FileInputStream(source); copy(fis, dest); } finally { if (fis != null) try { fis.close(); } catch (Exception e) {} } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] read(File source) throws IOException { byte[] buffer = new byte[(int) source.length()]; InputStream fis = new FileInputStream(source); int p = 0; int c; while ((c = fis.read(buffer, p, buffer.length - p)) > 0) p += c; fis.close(); return buffer; } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] read(File source) throws IOException { byte[] buffer = new byte[(int) source.length()]; InputStream fis = null; try { fis = new FileInputStream(source); int p = 0, c; while ((c = fis.read(buffer, p, buffer.length - p)) > 0) p += c; } finally { if (fis != null) try { fis.close(); } catch (Exception e) {} } return buffer; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException { // make space for new words int flushc = 0; //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size()); synchronized (hashScore) { while (hashScore.size() > maxWords) flushc += flushSpecific(true); } //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries"); // put new words into cache Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null if (v == null) v = new Vector(); v.add(entry); cache.put(wordHash, v); hashScore.incScore(wordHash); return flushc; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException { // make space for new words int flushc = 0; //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size()); synchronized (hashScore) { while (hashScore.size() > maxWords) flushc += flushSpecific(true); } //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries"); // put new words into cache synchronized (cache) { Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null if (v == null) v = new Vector(); v.add(entry); cache.put(wordHash, v); hashScore.incScore(wordHash); } return flushc; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void copy(File source, File dest) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(dest); copy(fis, fos); fis.close(); fos.close(); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public static void copy(File source, File dest) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); copy(fis, fos); } finally { if (fis != null) try {fis.close();} catch (Exception e) {} if (fos != null) try {fos.close();} catch (Exception e) {} } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { // return variable that accumulates replacements serverObjects prop = new serverObjects(); //if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString()); prop.put("port", env.getConfig("port", "8080")); prop.put("peerName", env.getConfig("peerName", "nameless")); // set values String s; int pos; // admin password if (env.getConfig("adminAccountBase64", "").length() == 0) { // no password has been specified prop.put("adminuser","admin"); } else { s = env.getConfig("adminAccount", "admin:void"); pos = s.indexOf(":"); if (pos < 0) { prop.put("adminuser","admin"); } else { prop.put("adminuser",s.substring(0, pos)); } } // remote proxy prop.put("remoteProxyHost", env.getConfig("remoteProxyHost", "")); prop.put("remoteProxyPort", env.getConfig("remoteProxyPort", "")); prop.put("remoteProxyNoProxy", env.getConfig("remoteProxyNoProxy", "")); prop.put("remoteProxyUseChecked", ((String) env.getConfig("remoteProxyUse", "false")).equals("true") ? 1 : 0); // proxy access filter prop.put("proxyfilter", env.getConfig("proxyClient", "*")); // proxy password if (env.getConfig("proxyAccountBase64", "").length() == 0) { // no password has been specified prop.put("proxyuser","proxy"); } else { s = env.getConfig("proxyAccount", "proxy:void"); pos = s.indexOf(":"); if (pos < 0) { prop.put("proxyuser","proxy"); } else { prop.put("proxyuser",s.substring(0, pos)); } } // server access filter prop.put("serverfilter", env.getConfig("serverClient", "*")); // server password if (env.getConfig("serverAccountBase64", "").length() == 0) { // no password has been specified prop.put("serveruser","server"); } else { s = env.getConfig("serverAccount", "server:void"); pos = s.indexOf(":"); if (pos < 0) { prop.put("serveruser","server"); } else { prop.put("serveruser",s.substring(0, pos)); } } // clientIP prop.put("clientIP", (String) header.get("CLIENTIP", "<unknown>")); // read an artificial header addendum //seedFTPSettings prop.put("seedFTPServer", env.getConfig("seedFTPServer", "")); prop.put("seedFTPPath", env.getConfig("seedFTPPath", "")); prop.put("seedFTPAccount", env.getConfig("seedFTPAccount", "")); prop.put("seedFTPPassword", env.getConfig("seedFTPPassword", "")); prop.put("seedURL", env.getConfig("seedURL", "")); /* * Parser Configuration */ plasmaSwitchboard sb = (plasmaSwitchboard)env; Hashtable enabledParsers = sb.parser.getEnabledParserList(); Hashtable availableParsers = sb.parser.getAvailableParserList(); // fetching a list of all available mimetypes List availableParserKeys = Arrays.asList(availableParsers.keySet().toArray(new String[availableParsers.size()])); // sort it Collections.sort(availableParserKeys); // loop through the mimeTypes and add it to the properties int parserIdx = 0; Iterator availableParserIter = availableParserKeys.iterator(); while (availableParserIter.hasNext()) { String mimeType = (String) availableParserIter.next(); prop.put("parser_" + parserIdx + "_mime", mimeType); prop.put("parser_" + parserIdx + "_name", availableParsers.get(mimeType)); prop.put("parser_" + parserIdx + "_status", enabledParsers.containsKey(mimeType) ? 1:0); parserIdx++; } prop.put("parser", parserIdx); // return rewrite properties return prop; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { // return variable that accumulates replacements serverObjects prop = new serverObjects(); //if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString()); prop.put("port", env.getConfig("port", "8080")); prop.put("peerName", env.getConfig("peerName", "nameless")); prop.put("isTransparentProxy", env.getConfig("isTransparentProxy", "false").equals("true") ? 1 : 0); // set values String s; int pos; // admin password if (env.getConfig("adminAccountBase64", "").length() == 0) { // no password has been specified prop.put("adminuser","admin"); } else { s = env.getConfig("adminAccount", "admin:void"); pos = s.indexOf(":"); if (pos < 0) { prop.put("adminuser","admin"); } else { prop.put("adminuser",s.substring(0, pos)); } } // remote proxy prop.put("remoteProxyHost", env.getConfig("remoteProxyHost", "")); prop.put("remoteProxyPort", env.getConfig("remoteProxyPort", "")); prop.put("remoteProxyNoProxy", env.getConfig("remoteProxyNoProxy", "")); prop.put("remoteProxyUseChecked", ((String) env.getConfig("remoteProxyUse", "false")).equals("true") ? 1 : 0); // proxy access filter prop.put("proxyfilter", env.getConfig("proxyClient", "*")); // proxy password if (env.getConfig("proxyAccountBase64", "").length() == 0) { // no password has been specified prop.put("proxyuser","proxy"); } else { s = env.getConfig("proxyAccount", "proxy:void"); pos = s.indexOf(":"); if (pos < 0) { prop.put("proxyuser","proxy"); } else { prop.put("proxyuser",s.substring(0, pos)); } } // server access filter prop.put("serverfilter", env.getConfig("serverClient", "*")); // server password if (env.getConfig("serverAccountBase64", "").length() == 0) { // no password has been specified prop.put("serveruser","server"); } else { s = env.getConfig("serverAccount", "server:void"); pos = s.indexOf(":"); if (pos < 0) { prop.put("serveruser","server"); } else { prop.put("serveruser",s.substring(0, pos)); } } // clientIP prop.put("clientIP", (String) header.get("CLIENTIP", "<unknown>")); // read an artificial header addendum //seedFTPSettings prop.put("seedFTPServer", env.getConfig("seedFTPServer", "")); prop.put("seedFTPPath", env.getConfig("seedFTPPath", "")); prop.put("seedFTPAccount", env.getConfig("seedFTPAccount", "")); prop.put("seedFTPPassword", env.getConfig("seedFTPPassword", "")); prop.put("seedURL", env.getConfig("seedURL", "")); /* * Parser Configuration */ plasmaSwitchboard sb = (plasmaSwitchboard)env; Hashtable enabledParsers = sb.parser.getEnabledParserList(); Hashtable availableParsers = sb.parser.getAvailableParserList(); // fetching a list of all available mimetypes List availableParserKeys = Arrays.asList(availableParsers.keySet().toArray(new String[availableParsers.size()])); // sort it Collections.sort(availableParserKeys); // loop through the mimeTypes and add it to the properties int parserIdx = 0; Iterator availableParserIter = availableParserKeys.iterator(); while (availableParserIter.hasNext()) { String mimeType = (String) availableParserIter.next(); prop.put("parser_" + parserIdx + "_mime", mimeType); prop.put("parser_" + parserIdx + "_name", availableParsers.get(mimeType)); prop.put("parser_" + parserIdx + "_status", enabledParsers.containsKey(mimeType) ? 1:0); parserIdx++; } prop.put("parser", parserIdx); // return rewrite properties return prop; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static HashSet loadSet(String setname, String filename) { HashSet set = new HashSet(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase()); } br.close(); serverLog.logInfo("PROXY", "read " + setname + " set from file " + filename); } catch (IOException e) {} return set; } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private static HashSet loadSet(String setname, String filename) { HashSet set = new HashSet(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase()); } br.close(); serverLog.logInfo("PROXY", "read " + setname + " set from file " + filename); } catch (IOException e) { } finally { if (br != null) try { br.close(); } catch (Exception e) {} } return set; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean job() throws Exception { // prepare for new connection // idleThreadCheck(); this.switchboard.handleBusyState(this.theSessionPool.getNumActive() /*activeThreads.size() */); log.logDebug( "* waiting for connections, " + this.theSessionPool.getNumActive() + " sessions running, " + this.theSessionPool.getNumIdle() + " sleeping"); // list all connection (debug) /* if (activeThreads.size() > 0) { Enumeration threadEnum = activeThreads.keys(); Session se; long time; while (threadEnum.hasMoreElements()) { se = (Session) threadEnum.nextElement(); time = System.currentTimeMillis() - ((Long) activeThreads.get(se)).longValue(); log.logDebug("* ACTIVE SESSION (" + ((se.isAlive()) ? "alive" : "dead") + ", " + time + "): " + se.request); } } */ // wait for new connection announceThreadBlockApply(); Socket controlSocket = this.socket.accept(); announceThreadBlockRelease(); if ((this.denyHost == null) || (this.denyHost.get((""+controlSocket.getInetAddress().getHostAddress())) == null)) { //log.logDebug("* catched request from " + controlSocket.getInetAddress().getHostAddress()); controlSocket.setSoTimeout(this.timeout); Session connection = (Session) this.theSessionPool.borrowObject(); connection.execute(controlSocket); //try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {} // wait for debug // activeThreads.put(connection, new Long(System.currentTimeMillis())); //log.logDebug("* NEW SESSION: " + connection.request); } else { System.out.println("ACCESS FROM " + controlSocket.getInetAddress().getHostAddress() + " DENIED"); } // idle until number of maximal threads is (again) reached //synchronized(this) { // while ((maxSessions > 0) && (activeThreads.size() >= maxSessions)) try { // log.logDebug("* Waiting for activeThreads=" + activeThreads.size() + " < maxSessions=" + maxSessions); // Thread.currentThread().sleep(2000); // idleThreadCheck(); // } catch (InterruptedException e) {} return true; } #location 40 #vulnerability type RESOURCE_LEAK
#fixed code public boolean job() throws Exception { // prepare for new connection // idleThreadCheck(); this.switchboard.handleBusyState(this.theSessionPool.getNumActive() /*activeThreads.size() */); log.logDebug( "* waiting for connections, " + this.theSessionPool.getNumActive() + " sessions running, " + this.theSessionPool.getNumIdle() + " sleeping"); // list all connection (debug) /* if (activeThreads.size() > 0) { Enumeration threadEnum = activeThreads.keys(); Session se; long time; while (threadEnum.hasMoreElements()) { se = (Session) threadEnum.nextElement(); time = System.currentTimeMillis() - ((Long) activeThreads.get(se)).longValue(); log.logDebug("* ACTIVE SESSION (" + ((se.isAlive()) ? "alive" : "dead") + ", " + time + "): " + se.request); } } */ // wait for new connection announceThreadBlockApply(); Socket controlSocket = this.socket.accept(); announceThreadBlockRelease(); String clientIP = ""+controlSocket.getInetAddress().getHostAddress(); if (bfHost.get(clientIP) != null) { log.logInfo("SLOWING DOWN ACCESS FOR BRUTE-FORCE PREVENTION FROM " + clientIP); // add a delay to make brute-force harder try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {} } if ((this.denyHost == null) || (this.denyHost.get(clientIP) == null)) { controlSocket.setSoTimeout(this.timeout); Session connection = (Session) this.theSessionPool.borrowObject(); connection.execute(controlSocket); //log.logDebug("* NEW SESSION: " + connection.request + " from " + clientIP); } else { System.out.println("ACCESS FROM " + clientIP + " DENIED"); } // idle until number of maximal threads is (again) reached //synchronized(this) { // while ((maxSessions > 0) && (activeThreads.size() >= maxSessions)) try { // log.logDebug("* Waiting for activeThreads=" + activeThreads.size() + " < maxSessions=" + maxSessions); // Thread.currentThread().sleep(2000); // idleThreadCheck(); // } catch (InterruptedException e) {} return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int size() { return java.lang.Math.max(singletons.size(), java.lang.Math.max(backend.size(), cache.size())); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int size() { return java.lang.Math.max(assortmentCluster.sizeTotal(), java.lang.Math.max(backend.size(), cache.size())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void copy(File source, File dest) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(dest); copy(fis, fos); fis.close(); fos.close(); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public static void copy(File source, File dest) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); copy(fis, fos); } finally { if (fis != null) try {fis.close();} catch (Exception e) {} if (fos != null) try {fos.close();} catch (Exception e) {} } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException { // make space for new words int flushc = 0; //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size()); synchronized (hashScore) { while (hashScore.size() > maxWords) flushc += flushSpecific(true); } //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries"); // put new words into cache Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null if (v == null) v = new Vector(); v.add(entry); cache.put(wordHash, v); hashScore.incScore(wordHash); return flushc; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException { // make space for new words int flushc = 0; //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size()); synchronized (hashScore) { while (hashScore.size() > maxWords) flushc += flushSpecific(true); } //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries"); // put new words into cache synchronized (cache) { Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null if (v == null) v = new Vector(); v.add(entry); cache.put(wordHash, v); hashScore.incScore(wordHash); } return flushc; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public serverObjects searchFromRemote(Set hashes, int count, boolean global, long duetime) { if (hashes == null) hashes = new HashSet(); serverObjects prop = new serverObjects(); try { log.logInfo("INIT HASH SEARCH: " + hashes + " - " + count + " links"); long timestamp = System.currentTimeMillis(); plasmaWordIndexEntity idx = searchManager.searchHashes(hashes, duetime * 8 / 10); // a nameless temporary index, not sorted by special order but by hash long remainingTime = duetime - (System.currentTimeMillis() - timestamp); plasmaSearch.result acc = searchManager.order(idx, hashes, stopwords, new char[]{plasmaSearch.O_QUALITY, plasmaSearch.O_AGE}, remainingTime, 10); // result is a List of urlEntry elements if (acc == null) { prop.put("totalcount", "0"); prop.put("linkcount", "0"); prop.put("references", ""); } else { prop.put("totalcount", "" + acc.sizeOrdered()); int i = 0; String links = ""; String resource = ""; //plasmaIndexEntry pie; plasmaCrawlLURL.entry urlentry; while ((acc.hasMoreElements()) && (i < count)) { urlentry = acc.nextElement(); resource = urlentry.toString(); if (resource != null) { links += "resource" + i + "=" + resource + serverCore.crlfString; i++; } } prop.put("links", links); prop.put("linkcount", "" + i); // prepare reference hints Object[] ws = acc.getReferences(16); String refstr = ""; for (int j = 0; j < ws.length; j++) refstr += "," + (String) ws[j]; if (refstr.length() > 0) refstr = refstr.substring(1); prop.put("references", refstr); } // add information about forward peers prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result prop.put("fwsrc", ""); // peers that helped to construct this result prop.put("fwrec", ""); // peers that would have helped to construct this result (recommendations) // log log.logInfo("EXIT HASH SEARCH: " + hashes + " - " + ((idx == null) ? "0" : (""+idx.size())) + " links, " + ((System.currentTimeMillis() - timestamp) / 1000) + " seconds"); if (idx != null) idx.close(); return prop; } catch (IOException e) { return null; } } #location 39 #vulnerability type NULL_DEREFERENCE
#fixed code public serverObjects searchFromRemote(Set hashes, int count, boolean global, long duetime) { if (hashes == null) hashes = new HashSet(); serverObjects prop = new serverObjects(); try { log.logInfo("INIT HASH SEARCH: " + hashes + " - " + count + " links"); long timestamp = System.currentTimeMillis(); plasmaWordIndexEntity idx = searchManager.searchHashes(hashes, duetime * 8 / 10); // a nameless temporary index, not sorted by special order but by hash long remainingTime = duetime - (System.currentTimeMillis() - timestamp); plasmaSearch.result acc = searchManager.order(idx, hashes, stopwords, new char[]{plasmaSearch.O_QUALITY, plasmaSearch.O_AGE}, remainingTime, 10); // result is a List of urlEntry elements if (acc == null) { prop.put("totalcount", "0"); prop.put("linkcount", "0"); prop.put("references", ""); } else { prop.put("totalcount", "" + acc.sizeOrdered()); int i = 0; StringBuffer links = new StringBuffer(); String resource = ""; //plasmaIndexEntry pie; plasmaCrawlLURL.entry urlentry; while ((acc.hasMoreElements()) && (i < count)) { urlentry = acc.nextElement(); resource = urlentry.toString(); if (resource != null) { links.append(resource).append(i).append("=").append(resource).append(serverCore.crlfString); i++; } } prop.put("links", links.toString()); prop.put("linkcount", "" + i); // prepare reference hints Object[] ws = acc.getReferences(16); StringBuffer refstr = new StringBuffer(); for (int j = 0; j < ws.length; j++) refstr.append(",").append((String) ws[j]); prop.put("references", (refstr.length() > 0)?refstr.substring(1):refstr.toString()); } // add information about forward peers prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result prop.put("fwsrc", ""); // peers that helped to construct this result prop.put("fwrec", ""); // peers that would have helped to construct this result (recommendations) // log log.logInfo("EXIT HASH SEARCH: " + hashes + " - " + ((idx == null) ? "0" : (""+idx.size())) + " links, " + ((System.currentTimeMillis() - timestamp) / 1000) + " seconds"); if (idx != null) idx.close(); return prop; } catch (IOException e) { return null; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String readLine() throws IOException { // with these functions, we consider a line as always terminated by CRLF serverByteBuffer sb = new serverByteBuffer(); int c; while (true) { c = read(); if (c < 0) { if (sb.length() == 0) return null; else return sb.toString(); } if (c == cr) continue; if (c == lf) return sb.toString(); sb.append((byte) c); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public String readLine() throws IOException { // with these functions, we consider a line as always terminated by CRLF byte[] bb = new byte[80]; int bbsize = 0; int c; while (true) { c = read(); if (c < 0) { if (bbsize == 0) return null; else return new String(bb, 0, bbsize); } if (c == cr) continue; if (c == lf) return new String(bb, 0, bbsize); // append to bb if (bbsize == bb.length) { // extend bb size byte[] newbb = new byte[bb.length * 2]; System.arraycopy(bb, 0, newbb, 0, bb.length); bb = newbb; newbb = null; } bb[bbsize++] = (byte) c; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void initDataComposer(IDataComposer dataComposer, HttpServletRequest request) { String paramName = (String) request.getSession().getAttribute(Constants.MODIFY_STATE_HDIV_PARAMETER); String preState = paramName != null ? request.getParameter(paramName) : null; if (preState != null && preState.length() > 0) { // We are modifying an existing state, preload dataComposer with it IState state = this.stateUtil.restoreState(preState); if (state.getPageId() > 0) { IPage page = this.session.getPage(state.getPageId() + ""); if (page != null) { dataComposer.startPage(page); } } if (state != null) { dataComposer.beginRequest(state); } } else if (this.config.isReuseExistingPageInAjaxRequest() && isAjaxRequest(request)) { String hdivStateParamName = (String) request.getSession().getAttribute(Constants.HDIV_PARAMETER); String hdivState = request.getParameter(hdivStateParamName); IState state = this.stateUtil.restoreState(hdivState); IPage page = this.session.getPage(Integer.toString(state.getPageId())); dataComposer.startPage(page); } else { dataComposer.startPage(); } // Detect if request url is configured as a long living page String url = request.getRequestURI().substring(request.getContextPath().length()); String scope = this.config.isLongLivingPages(url); if (scope != null) { dataComposer.startScope(scope); } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code protected void initDataComposer(IDataComposer dataComposer, HttpServletRequest request) { String paramName = (String) request.getSession().getAttribute(Constants.MODIFY_STATE_HDIV_PARAMETER); String preState = paramName != null ? request.getParameter(paramName) : null; if (preState != null && preState.length() > 0) { // We are modifying an existing state, preload dataComposer with it IState state = this.stateUtil.restoreState(preState); if (state.getPageId() > 0) { IPage page = this.session.getPage(state.getPageId() + ""); if (page != null) { dataComposer.startPage(page); } } if (state != null) { dataComposer.beginRequest(state); } } else if (this.config.isReuseExistingPageInAjaxRequest() && isAjaxRequest(request)) { String hdivStateParamName = (String) request.getSession().getAttribute(Constants.HDIV_PARAMETER); String hdivState = request.getParameter(hdivStateParamName); if (hdivState != null) { IState state = this.stateUtil.restoreState(hdivState); if (state.getPageId() > 0) { IPage page = this.session.getPage(Integer.toString(state.getPageId())); dataComposer.startPage(page); } else { dataComposer.startPage(); } } else { dataComposer.startPage(); } } else { dataComposer.startPage(); } // Detect if request url is configured as a long living page String url = request.getRequestURI().substring(request.getContextPath().length()); String scope = this.config.isLongLivingPages(url); if (scope != null) { dataComposer.startScope(scope); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public StatusEnum process(String optType, String optId, StatusEnum initStatus, long expireMs) { if (Dew.cluster.cache.setnx(CACHE_KEY + optType + ":" + optId, initStatus.toString(), expireMs / 1000)) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { // 设置不成功,表示之前存在,返回存在的值 String status = Dew.cluster.cache.get(CACHE_KEY + optType + ":" + optId); if (status == null && status.isEmpty()) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { return StatusEnum.valueOf(status); } } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public StatusEnum process(String optType, String optId, StatusEnum initStatus, long expireMs) { if (Dew.cluster.cache.setnx(CACHE_KEY + optType + ":" + optId, initStatus.toString(), expireMs / 1000)) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { // 设置不成功,表示之前存在,返回存在的值 String status = Dew.cluster.cache.get(CACHE_KEY + optType + ":" + optId); if (status == null || status.isEmpty()) { // 设置成功,表示之前不存在 return StatusEnum.NOT_EXIST; } else { return StatusEnum.valueOf(status); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void register(final DynamicConfig config) { final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); BrokerRole role = BrokerConfig.getBrokerRole(); IndexLog log; if (role == BrokerRole.BACKUP) { final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); bus.subscribe(MessageQueryIndex.class, getConstructIndexListener(keyGenerator , messageQueryIndex -> log.setDeleteTo(messageQueryIndex.getCurrentOffset()))); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); } else if (role == BrokerRole.DELAY_BACKUP) { throw new RuntimeException("check the role is correct, only backup is allowed."); } else { throw new RuntimeException("check the role is correct, only backup is allowed."); } IndexLogIterateService iterateService = new IndexLogIterateService(config, log, checkpointManager, bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, iterateService, masterSlaveSyncManager); } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code private void register(final DynamicConfig config) { BrokerRole role = BrokerConfig.getBrokerRole(); if(role != BrokerRole.BACKUP) throw new RuntimeException("Only support backup"); final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); IndexLog log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); FixedExecOrderEventBus.Listener<MessageQueryIndex> indexProcessor = getConstructIndexListener(keyGenerator , messageQueryIndex -> log.commit(messageQueryIndex.getCurrentOffset())); bus.subscribe(MessageQueryIndex.class, indexProcessor); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); LogIterateService<MessageQueryIndex> iterateService = new LogIterateService<>("index", new StorageConfigImpl(config), log, checkpointManager.getIndexIterateCheckpoint(), bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, masterSlaveSyncManager); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void recover() { if (segments.isEmpty()) { return; } LOG.info("Recovering logs."); final List<Long> baseOffsets = new ArrayList<>(segments.navigableKeySet()); final int offsetCount = baseOffsets.size(); long offset = -1; for (int i = offsetCount - 2; i < offsetCount; i++) { if (i < 0) continue; final LogSegment segment = segments.get(baseOffsets.get(i)); offset = segment.getBaseOffset(); final LogSegmentValidator.ValidateResult result = segmentValidator.validate(segment); offset += result.getValidatedSize(); if (result.getStatus() == LogSegmentValidator.ValidateStatus.COMPLETE) { segment.setWrotePosition(segment.getFileSize()); } else { break; } } flushedOffset = offset; final long maxOffset = latestSegment().getBaseOffset() + latestSegment().getFileSize(); final int relativeOffset = (int) (offset % fileSize); final LogSegment segment = locateSegment(offset); if (segment != null && maxOffset != offset) { segment.setWrotePosition(relativeOffset); LOG.info("recover wrote offset to {}:{}", segment, segment.getWrotePosition()); // TODO(keli.wang): should delete crash file } LOG.info("Recover done."); } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code private void recover() { if (segments.isEmpty()) { return; } LOG.info("Recovering logs."); final List<Long> baseOffsets = new ArrayList<>(segments.navigableKeySet()); final int offsetCount = baseOffsets.size(); long offset = -1; for (int i = offsetCount - 2; i < offsetCount; i++) { if (i < 0) continue; final LogSegment segment = segments.get(baseOffsets.get(i)); offset = segment.getBaseOffset(); final LogSegmentValidator.ValidateResult result = segmentValidator.validate(segment); offset += result.getValidatedSize(); if (result.getStatus() == LogSegmentValidator.ValidateStatus.COMPLETE) { segment.setWrotePosition(segment.getFileSize()); } else { break; } } flushedOffset = offset; final LogSegment latestSegment = latestSegment(); final long maxOffset = latestSegment.getBaseOffset() + latestSegment.getFileSize(); final int relativeOffset = (int) (offset % fileSize); final LogSegment segment = locateSegment(offset); if (segment != null && maxOffset != offset) { segment.setWrotePosition(relativeOffset); LOG.info("recover wrote offset to {}:{}", segment, segment.getWrotePosition()); if (segment.getBaseOffset() != latestSegment.getBaseOffset()) { LOG.info("will remove all segment after max wrote position. current base offset: {}, max base offset: {}", segment.getBaseOffset(), latestSegment.getBaseOffset()); deleteSegmentsAfterOffset(offset); } } LOG.info("Recover done."); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void register(final DynamicConfig config) { final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); BrokerRole role = BrokerConfig.getBrokerRole(); IndexLog log; if (role == BrokerRole.BACKUP) { final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); bus.subscribe(MessageQueryIndex.class, getConstructIndexListener(keyGenerator , messageQueryIndex -> log.setDeleteTo(messageQueryIndex.getCurrentOffset()))); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); } else if (role == BrokerRole.DELAY_BACKUP) { throw new RuntimeException("check the role is correct, only backup is allowed."); } else { throw new RuntimeException("check the role is correct, only backup is allowed."); } IndexLogIterateService iterateService = new IndexLogIterateService(config, log, checkpointManager, bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, iterateService, masterSlaveSyncManager); } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code private void register(final DynamicConfig config) { BrokerRole role = BrokerConfig.getBrokerRole(); if(role != BrokerRole.BACKUP) throw new RuntimeException("Only support backup"); final SlaveSyncClient slaveSyncClient = new SlaveSyncClient(config); final MasterSlaveSyncManager masterSlaveSyncManager = new MasterSlaveSyncManager(slaveSyncClient); StorageConfig storageConfig = dummyConfig(config); final CheckpointManager checkpointManager = new CheckpointManager(BrokerConfig.getBrokerRole(), storageConfig, null); final FixedExecOrderEventBus bus = new FixedExecOrderEventBus(); final BackupKeyGenerator keyGenerator = new BackupKeyGenerator(dicService); final KvStore.StoreFactory factory = new FactoryStoreImpl().createStoreFactory(config, dicService, keyGenerator); this.indexStore = factory.createMessageIndexStore(); this.recordStore = factory.createRecordStore(); this.deadMessageStore = factory.createDeadMessageStore(); IndexLog log = new IndexLog(storageConfig, checkpointManager); final IndexLogSyncDispatcher dispatcher = new IndexLogSyncDispatcher(log); FixedExecOrderEventBus.Listener<MessageQueryIndex> indexProcessor = getConstructIndexListener(keyGenerator , messageQueryIndex -> log.commit(messageQueryIndex.getCurrentOffset())); bus.subscribe(MessageQueryIndex.class, indexProcessor); masterSlaveSyncManager.registerProcessor(dispatcher.getSyncType(), new BackupMessageLogSyncProcessor(dispatcher)); // action final RocksDBStore rocksDBStore = new RocksDBStoreImpl(config); final BatchBackup<ActionRecord> recordBackup = new RecordBatchBackup(this.config, keyGenerator, rocksDBStore, recordStore); backupManager.registerBatchBackup(recordBackup); final SyncLogIterator<Action, ByteBuf> actionIterator = new ActionSyncLogIterator(); BackupActionLogSyncProcessor actionLogSyncProcessor = new BackupActionLogSyncProcessor(checkpointManager, config, actionIterator, recordBackup); masterSlaveSyncManager.registerProcessor(SyncType.action, actionLogSyncProcessor); scheduleFlushManager.register(actionLogSyncProcessor); masterSlaveSyncManager.registerProcessor(SyncType.heartbeat, new HeartBeatProcessor(checkpointManager)); LogIterateService<MessageQueryIndex> iterateService = new LogIterateService<>("index", new StorageConfigImpl(config), log, checkpointManager.getIndexIterateCheckpoint(), bus); IndexFileStore indexFileStore = new IndexFileStore(log, config); scheduleFlushManager.register(indexFileStore); messageService = new MessageServiceImpl(config, indexStore, deadMessageStore, recordStore); scheduleFlushManager.scheduleFlush(); backupManager.start(); iterateService.start(); masterSlaveSyncManager.startSync(); addResourcesInOrder(scheduleFlushManager, backupManager, masterSlaveSyncManager); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static MemoryLayoutSpecification getEffectiveMemoryLayoutSpecification() { final String dataModel = System.getProperty("sun.arch.data.model"); if ("32".equals(dataModel)) { // Running with 32-bit data model return new MemoryLayoutSpecification() { public int getArrayHeaderSize() { return 12; } public int getObjectHeaderSize() { return 8; } public int getObjectPadding() { return 8; } public int getReferenceSize() { return 4; } public int getSuperclassFieldPadding() { return 4; } }; } final String strVmVersion = System.getProperty("java.vm.version"); final int vmVersion = Integer.parseInt(strVmVersion.substring(0, strVmVersion.indexOf('.'))); final int alignment = getAlignment(); if (vmVersion >= 17) { long maxMemory = 0; for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) { maxMemory += mp.getUsage().getMax(); } if (maxMemory < 30L * 1024 * 1024 * 1024) { // HotSpot 17.0 and above use compressed OOPs below 30GB of RAM // total for all memory pools (yes, including code cache). return new MemoryLayoutSpecification() { public int getArrayHeaderSize() { return 16; } public int getObjectHeaderSize() { return 12; } public int getObjectPadding() { return alignment; } public int getReferenceSize() { return 4; } public int getSuperclassFieldPadding() { return 4; } }; } } /* Worst case we over count. */ // In other cases, it's a 64-bit uncompressed OOPs object model return new MemoryLayoutSpecification() { public int getArrayHeaderSize() { return 24; } public int getObjectHeaderSize() { return 16; } public int getObjectPadding() { return alignment; } public int getReferenceSize() { return 8; } public int getSuperclassFieldPadding() { return 8; } }; } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code private static MemoryLayoutSpecification getEffectiveMemoryLayoutSpecification() { final String dataModel = System.getProperty("sun.arch.data.model"); if ("32".equals(dataModel)) { // Running with 32-bit data model return new MemoryLayoutSpecification() { public int getArrayHeaderSize() { return 12; } public int getObjectHeaderSize() { return 8; } public int getObjectPadding() { return 8; } public int getReferenceSize() { return 4; } public int getSuperclassFieldPadding() { return 4; } }; } boolean modernJvm = true; final String strSpecVersion = System.getProperty("java.specification.version"); final boolean hasDot = strSpecVersion.indexOf('.') != -1; if (hasDot) { if ("1".equals(strSpecVersion.substring(0, strSpecVersion.indexOf('.')))) { // Java 1.6, 1.7, 1.8 final String strVmVersion = System.getProperty("java.vm.version"); final int vmVersion = Integer.parseInt(strVmVersion.substring(0, strVmVersion.indexOf('.'))); modernJvm = vmVersion >= 17; } } final int alignment = getAlignment(); if (modernJvm) { long maxMemory = 0; for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) { maxMemory += mp.getUsage().getMax(); } if (maxMemory < 30L * 1024 * 1024 * 1024) { // HotSpot 17.0 and above use compressed OOPs below 30GB of RAM // total for all memory pools (yes, including code cache). return new MemoryLayoutSpecification() { public int getArrayHeaderSize() { return 16; } public int getObjectHeaderSize() { return 12; } public int getObjectPadding() { return alignment; } public int getReferenceSize() { return 4; } public int getSuperclassFieldPadding() { return 4; } }; } } /* Worst case we over count. */ // In other cases, it's a 64-bit uncompressed OOPs object model return new MemoryLayoutSpecification() { public int getArrayHeaderSize() { return 24; } public int getObjectHeaderSize() { return 16; } public int getObjectPadding() { return alignment; } public int getReferenceSize() { return 8; } public int getSuperclassFieldPadding() { return 8; } }; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void putBlock(Block block) throws Exception { rocksDB.put((BLOCKS_BUCKET_PREFIX + block.getHash()).getBytes(), SerializeUtils.serialize(block)); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void putBlock(Block block) throws Exception { byte[] key = SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + block.getHash()); rocksDB.put(key, SerializeUtils.serialize(block)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initRocksDB() { try { rocksDB = RocksDB.open(new Options().setCreateIfMissing(true), DB_FILE); } catch (RocksDBException e) { e.printStackTrace(); } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private void initRocksDB() { try { Options options = new Options(); options.setCreateIfMissing(true); rocksDB = RocksDB.open(options, DB_FILE); } catch (RocksDBException e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void putLastBlockHash(String tipBlockHash) throws Exception { rocksDB.put((BLOCKS_BUCKET_PREFIX + "l").getBytes(), tipBlockHash.getBytes()); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void putLastBlockHash(String tipBlockHash) throws Exception { rocksDB.put(SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + "l"), SerializeUtils.serialize(tipBlockHash)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Block getBlock(String blockHash) throws Exception { return (Block) SerializeUtils.deserialize(rocksDB.get((BLOCKS_BUCKET_PREFIX + blockHash).getBytes())); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Block getBlock(String blockHash) throws Exception { byte[] key = SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + blockHash); return (Block) SerializeUtils.deserialize(rocksDB.get(key)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getLastBlockHash() throws Exception { byte[] lastBlockHashBytes = rocksDB.get((BLOCKS_BUCKET_PREFIX + "l").getBytes()); if (lastBlockHashBytes != null) { return new String(lastBlockHashBytes); } return ""; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public String getLastBlockHash() throws Exception { byte[] lastBlockHashBytes = rocksDB.get(SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + "l")); if (lastBlockHashBytes != null) { return (String) SerializeUtils.deserialize(lastBlockHashBytes); } return ""; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void loadResource(Yaml yaml, InputStream yamlStream, String filename) { Node loadedYaml = yaml.compose(new UnicodeReader(yamlStream)); if (loadedYaml == null) { LOG.error("The file {} is empty", filename); return; } // Get and check top level config if (!(loadedYaml instanceof MappingNode)) { fail(loadedYaml, filename, "File must be a Map"); } MappingNode rootNode = (MappingNode) loadedYaml; NodeTuple configNodeTuple = null; for (NodeTuple tuple : rootNode.getValue()) { String name = getKeyAsString(tuple, filename); if ("config".equals(name)) { configNodeTuple = tuple; break; } } String configKeyName = getKeyAsString(configNodeTuple, filename); if (!configKeyName.equals("config")) { fail(loadedYaml, filename, "The top level entry MUST be 'config'."); } SequenceNode configNode = getValueAsSequenceNode(configNodeTuple, filename); List<Node> configList = configNode.getValue(); for (Node configEntry : configList) { if (!(configEntry instanceof MappingNode)) { fail(loadedYaml, filename, "The entry MUST be a mapping"); } NodeTuple entry = getExactlyOneNodeTuple((MappingNode) configEntry, filename); MappingNode actualEntry = getValueAsMappingNode(entry, filename); String entryType = getKeyAsString(entry, filename); switch (entryType) { case "lookup": loadYamlLookup(actualEntry, filename); break; case "matcher": loadYamlMatcher(actualEntry, filename); break; case "test": loadYamlTestcase(actualEntry, filename); break; default: throw new InvalidParserConfigurationException( "Yaml config.(" + filename + ":" + actualEntry.getStartMark().getLine() + "): " + "Found unexpected config entry: " + entryType + ", allowed are 'lookup, 'matcher' and 'test'"); } } } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code private void loadResource(Yaml yaml, InputStream yamlStream, String filename) { Node loadedYaml = yaml.compose(new UnicodeReader(yamlStream)); if (loadedYaml == null) { throw new InvalidParserConfigurationException("The file " + filename + " is empty"); } // Get and check top level config if (!(loadedYaml instanceof MappingNode)) { fail(loadedYaml, filename, "File must be a Map"); } MappingNode rootNode = (MappingNode) loadedYaml; NodeTuple configNodeTuple = null; for (NodeTuple tuple : rootNode.getValue()) { String name = getKeyAsString(tuple, filename); if ("config".equals(name)) { configNodeTuple = tuple; break; } } if (configNodeTuple == null) { fail(loadedYaml, filename, "The top level entry MUST be 'config'."); } SequenceNode configNode = getValueAsSequenceNode(configNodeTuple, filename); List<Node> configList = configNode.getValue(); for (Node configEntry : configList) { if (!(configEntry instanceof MappingNode)) { fail(loadedYaml, filename, "The entry MUST be a mapping"); } NodeTuple entry = getExactlyOneNodeTuple((MappingNode) configEntry, filename); MappingNode actualEntry = getValueAsMappingNode(entry, filename); String entryType = getKeyAsString(entry, filename); switch (entryType) { case "lookup": loadYamlLookup(actualEntry, filename); break; case "matcher": loadYamlMatcher(actualEntry, filename); break; case "test": loadYamlTestcase(actualEntry, filename); break; default: throw new InvalidParserConfigurationException( "Yaml config.(" + filename + ":" + actualEntry.getStartMark().getLine() + "): " + "Found unexpected config entry: " + entryType + ", allowed are 'lookup, 'matcher' and 'test'"); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void informSubstrings(ParserRuleContext ctx, String name, int maxSubStrings) { String text = getSourceText(ctx); inform(ctx, name, text, false); int startOffsetPrevious = 0; int count = 1; char[] chars = text.toCharArray(); String firstWords; while((firstWords = WordSplitter.getFirstWords(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstWords, true); // inform(ctx, ctx, name + "%" + count, WordSplitter.getSingleWord(text, count), true); inform(ctx, ctx, name + "%" + count, firstWords.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = WordSplitter.findNextWordStart(chars, firstWords.length()); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private void informSubstrings(ParserRuleContext ctx, String name, int maxSubStrings) { String text = getSourceText(ctx); if (text==null) { return; } inform(ctx, name, text, false); int startOffsetPrevious = 0; int count = 1; char[] chars = text.toCharArray(); String firstWords; while((firstWords = WordSplitter.getFirstWords(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstWords, true); inform(ctx, ctx, name + "%" + count, firstWords.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = WordSplitter.findNextWordStart(chars, firstWords.length()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void informSubVersions(ParserRuleContext ctx, String name, int maxSubStrings) { String text = getSourceText(ctx); inform(ctx, name, text, false); int startOffsetPrevious = 0; int count = 1; char[] chars = text.toCharArray(); String firstVersions; while((firstVersions = VersionSplitter.getFirstVersions(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstVersions, true); inform(ctx, ctx, name + "%" + count, firstVersions.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = VersionSplitter.findNextVersionStart(chars, firstVersions.length()); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private void informSubVersions(ParserRuleContext ctx, String name, int maxSubStrings) { String text = getSourceText(ctx); if (text==null) { return; } inform(ctx, name, text, false); int startOffsetPrevious = 0; int count = 1; char[] chars = text.toCharArray(); String firstVersions; while((firstVersions = VersionSplitter.getFirstVersions(text, count))!=null) { inform(ctx, ctx, name + "#" + count, firstVersions, true); inform(ctx, ctx, name + "%" + count, firstVersions.substring(startOffsetPrevious), true); count++; if (count > maxSubStrings) { return; } startOffsetPrevious = VersionSplitter.findNextVersionStart(chars, firstVersions.length()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "failed"); } else { builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { Biz biz = DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager); if (biz == null) { continue; } if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "failed"); } else { builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadinessCheckFailedHttpCode() throws IOException { HttpURLConnection huc = (HttpURLConnection) (new URL( "http://localhost:8080/health/readiness").openConnection()); huc.setRequestMethod("HEAD"); huc.connect(); int respCode = huc.getResponseCode(); System.out.println(huc.getResponseMessage()); Assert.assertEquals(503, respCode); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadinessCheckFailedHttpCode() { ResponseEntity<String> response = restTemplate.getForEntity("/health/readiness", String.class); Assert.assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "failed"); } else { builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { Biz biz = DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager); if (biz == null) { continue; } if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "failed"); } else { builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void initialize(ConfigurableApplicationContext applicationContext) { Environment environment = applicationContext.getEnvironment(); if (SOFABootEnvUtils.isSpringCloudBootstrapEnvironment(environment)) { return; } //init logging.level.com.alipay.sofa.runtime argument String runtimeLogLevelKey = Constants.LOG_LEVEL_PREFIX + SofaRuntimeLoggerFactory.SOFA_RUNTIME_LOG_SPACE; SofaBootLogSpaceIsolationInit.initSofaBootLogger(environment, runtimeLogLevelKey); SofaRuntimeLoggerFactory.getLogger(SofaRuntimeSpringContextInitializer.class).info( "SOFABoot Runtime Starting!"); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void initialize(ConfigurableApplicationContext applicationContext) { Environment environment = applicationContext.getEnvironment(); if (SOFABootEnvUtils.isSpringCloudBootstrapEnvironment(environment)) { return; } //init logging.level.com.alipay.sofa.runtime argument String runtimeLogLevelKey = Constants.LOG_LEVEL_PREFIX + SofaRuntimeLoggerFactory.SOFA_RUNTIME_LOG_SPACE; SofaBootLogSpaceIsolationInit.initSofaBootLogger(environment, runtimeLogLevelKey); SofaLogger.info("SOFABoot Runtime Starting!"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @GetMapping("/download/{key:.+}") public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @GetMapping("/download/{key:.+}") public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { return ResponseEntity.notFound().build(); } if(key.contains("../")){ return ResponseEntity.badRequest().build(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @PostMapping("refund") public Object refund(@LoginAdmin Integer adminId, @RequestBody String body) { if (adminId == null) { return ResponseUtil.unlogin(); } Integer orderId = JacksonUtil.parseInteger(body, "orderId"); Integer refundMoney = JacksonUtil.parseInteger(body, "refundMoney"); if (orderId == null) { return ResponseUtil.badArgument(); } LitemallOrder order = orderService.findById(orderId); if (order == null) { return ResponseUtil.badArgument(); } if(order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0){ return ResponseUtil.badArgumentValue(); } // 如果订单不是退款状态,则不能退款 if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) { return ResponseUtil.fail(403, "订单不能确认收货"); } // 开启事务管理 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { // 设置订单取消状态 order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM); orderService.update(order); // 商品货品数量增加 List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId); for (LitemallOrderGoods orderGoods : orderGoodsList) { Integer productId = orderGoods.getProductId(); LitemallProduct product = productService.findById(productId); Integer number = product.getNumber() + orderGoods.getNumber(); product.setNumber(number); productService.updateById(product); } } catch (Exception ex) { txManager.rollback(status); logger.error("系统内部错误", ex); return ResponseUtil.fail(403, "订单退款失败"); } txManager.commit(status); return ResponseUtil.ok(); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @PostMapping("refund") public Object refund(@LoginAdmin Integer adminId, @RequestBody String body) { if (adminId == null) { return ResponseUtil.unlogin(); } Integer orderId = JacksonUtil.parseInteger(body, "orderId"); String refundMoney = JacksonUtil.parseString(body, "refundMoney"); if (orderId == null) { return ResponseUtil.badArgument(); } LitemallOrder order = orderService.findById(orderId); if (order == null) { return ResponseUtil.badArgument(); } if (order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0) { return ResponseUtil.badArgumentValue(); } // 如果订单不是退款状态,则不能退款 if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) { return ResponseUtil.fail(403, "订单不能确认收货"); } // 开启事务管理 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { // 设置订单取消状态 order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM); orderService.update(order); // 商品货品数量增加 List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId); for (LitemallOrderGoods orderGoods : orderGoodsList) { Integer productId = orderGoods.getProductId(); LitemallProduct product = productService.findById(productId); Integer number = product.getNumber() + orderGoods.getNumber(); product.setNumber(number); productService.updateById(product); } } catch (Exception ex) { txManager.rollback(status); logger.error("系统内部错误", ex); return ResponseUtil.fail(403, "订单退款失败"); } //TODO 发送邮件和短信通知,这里采用异步发送 // 退款成功通知用户 /** * * 您申请的订单退款 [ 单号:{1} ] 已成功,请耐心等待到账。 * 注意订单号只发后6位 * */ litemallNotifyService.notifySMSTemplate(order.getMobile(), ConfigUtil.NotifyType.REFUND, new String[]{order.getOrderSn().substring(8, 14)}); txManager.commit(status); return ResponseUtil.ok(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @PostMapping("comment") public Object comment(@LoginUser Integer userId, @RequestBody String body) { if (userId == null) { return ResponseUtil.unlogin(); } Integer orderGoodsId = JacksonUtil.parseInteger(body, "orderGoodsId"); if(orderGoodsId == null){ return ResponseUtil.badArgument(); } LitemallOrderGoods orderGoods = orderGoodsService.findById(orderGoodsId); if(orderGoods == null){ return ResponseUtil.badArgumentValue(); } Integer orderId = orderGoods.getOrderId(); LitemallOrder order = orderService.findById(orderId); if(order == null){ return ResponseUtil.badArgumentValue(); } Short orderStatus = order.getOrderStatus(); if(!OrderUtil.isConfirmStatus(order) && !OrderUtil.isAutoConfirmStatus(order)) { return ResponseUtil.fail(404, "当前商品不能评价"); } if(!order.getUserId().equals(userId)){ return ResponseUtil.fail(404, "当前商品不属于用户"); } Integer commentId = orderGoods.getComment(); if(commentId == -1){ return ResponseUtil.fail(404, "当前商品评价时间已经过期"); } if(commentId != 0){ return ResponseUtil.fail(404, "订单商品已评价"); } String content = JacksonUtil.parseString(body, "content"); Integer star = JacksonUtil.parseInteger(body, "star"); if(star == null || star < 0 || star > 5){ return ResponseUtil.badArgumentValue(); } Boolean hasPicture = JacksonUtil.parseBoolean(body, "hasPicture"); List<String> picUrls = JacksonUtil.parseStringList(body, "picUrls"); if(hasPicture == null || !hasPicture){ picUrls = new ArrayList<>(0); } // 1. 创建评价 LitemallComment comment = new LitemallComment(); comment.setUserId(userId); comment.setValueId(orderGoods.getGoodsId()); comment.setType((byte)1); comment.setContent(content); comment.setHasPicture(hasPicture); comment.setPicUrls(picUrls.toArray(new String[]{})); commentService.save(comment); // 2. 更新订单商品的评价列表 orderGoods.setComment(comment.getId()); orderGoodsService.updateById(orderGoods); // 3. 更新订单中未评价的订单商品可评价数量 Short commentCount = order.getComments(); if(commentCount > 0){ commentCount--; } order.setComments(commentCount); orderService.updateWithOptimisticLocker(order); return ResponseUtil.ok(); } #location 53 #vulnerability type NULL_DEREFERENCE
#fixed code @PostMapping("comment") public Object comment(@LoginUser Integer userId, @RequestBody String body) { if (userId == null) { return ResponseUtil.unlogin(); } Integer orderGoodsId = JacksonUtil.parseInteger(body, "orderGoodsId"); if(orderGoodsId == null){ return ResponseUtil.badArgument(); } LitemallOrderGoods orderGoods = orderGoodsService.findById(orderGoodsId); if(orderGoods == null){ return ResponseUtil.badArgumentValue(); } Integer orderId = orderGoods.getOrderId(); LitemallOrder order = orderService.findById(orderId); if(order == null){ return ResponseUtil.badArgumentValue(); } Short orderStatus = order.getOrderStatus(); if(!OrderUtil.isConfirmStatus(order) && !OrderUtil.isAutoConfirmStatus(order)) { return ResponseUtil.fail(404, "当前商品不能评价"); } if(!order.getUserId().equals(userId)){ return ResponseUtil.fail(404, "当前商品不属于用户"); } Integer commentId = orderGoods.getComment(); if(commentId == -1){ return ResponseUtil.fail(404, "当前商品评价时间已经过期"); } if(commentId != 0){ return ResponseUtil.fail(404, "订单商品已评价"); } String content = JacksonUtil.parseString(body, "content"); Integer star = JacksonUtil.parseInteger(body, "star"); if(star == null || star < 0 || star > 5){ return ResponseUtil.badArgumentValue(); } Boolean hasPicture = JacksonUtil.parseBoolean(body, "hasPicture"); List<String> picUrls = JacksonUtil.parseStringList(body, "picUrls"); if(hasPicture == null || !hasPicture){ picUrls = new ArrayList<>(0); } // 1. 创建评价 LitemallComment comment = new LitemallComment(); comment.setUserId(userId); comment.setType((byte)0); comment.setValueId(orderGoods.getGoodsId()); comment.setStar(star.shortValue()); comment.setContent(content); comment.setHasPicture(hasPicture); comment.setPicUrls(picUrls.toArray(new String[]{})); commentService.save(comment); // 2. 更新订单商品的评价列表 orderGoods.setComment(comment.getId()); orderGoodsService.updateById(orderGoods); // 3. 更新订单中未评价的订单商品可评价数量 Short commentCount = order.getComments(); if(commentCount > 0){ commentCount--; } order.setComments(commentCount); orderService.updateWithOptimisticLocker(order); return ResponseUtil.ok(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @PostMapping("/update") public Object update(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone) { if (adminId == null) { return ResponseUtil.unlogin(); } LitemallGoods goods = goodsAllinone.getGoods(); LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes(); LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications(); LitemallProduct[] products = goodsAllinone.getProducts(); // 开启事务管理 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { // 商品基本信息表litemall_goods goodsService.updateById(goods); Integer gid = goods.getId(); specificationService.deleteByGid(gid); attributeService.deleteByGid(gid); productService.deleteByGid(gid); // 商品规格表litemall_goods_specification Map<String, Integer> specIds = new HashMap<>(); for (LitemallGoodsSpecification specification : specifications) { specification.setGoodsId(goods.getId()); specification.setAddTime(LocalDateTime.now()); specificationService.add(specification); specIds.put(specification.getValue(), specification.getId()); } // 商品参数表litemall_goods_attribute for (LitemallGoodsAttribute attribute : attributes) { attribute.setGoodsId(goods.getId()); attribute.setAddTime(LocalDateTime.now()); attributeService.add(attribute); } // 商品货品表litemall_product for (LitemallProduct product : products) { product.setGoodsId(goods.getId()); product.setAddTime(LocalDateTime.now()); productService.add(product); } } catch (Exception ex) { txManager.rollback(status); logger.error("系统内部错误", ex); } txManager.commit(status); qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName()); return ResponseUtil.ok(); } #location 54 #vulnerability type NULL_DEREFERENCE
#fixed code @PostMapping("/update") public Object update(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone) { if (adminId == null) { return ResponseUtil.unlogin(); } LitemallGoods goods = goodsAllinone.getGoods(); LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes(); LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications(); LitemallProduct[] products = goodsAllinone.getProducts(); // 开启事务管理 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { //将生成的分享图片地址写入数据库 qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName()); goods.setShareUrl(qCodeService.getShareImageUrl(goods.getId().toString())); // 商品基本信息表litemall_goods goodsService.updateById(goods); Integer gid = goods.getId(); specificationService.deleteByGid(gid); attributeService.deleteByGid(gid); productService.deleteByGid(gid); // 商品规格表litemall_goods_specification Map<String, Integer> specIds = new HashMap<>(); for (LitemallGoodsSpecification specification : specifications) { specification.setGoodsId(goods.getId()); specification.setAddTime(LocalDateTime.now()); specificationService.add(specification); specIds.put(specification.getValue(), specification.getId()); } // 商品参数表litemall_goods_attribute for (LitemallGoodsAttribute attribute : attributes) { attribute.setGoodsId(goods.getId()); attribute.setAddTime(LocalDateTime.now()); attributeService.add(attribute); } // 商品货品表litemall_product for (LitemallProduct product : products) { product.setGoodsId(goods.getId()); product.setAddTime(LocalDateTime.now()); productService.add(product); } } catch (Exception ex) { txManager.rollback(status); logger.error("系统内部错误", ex); } txManager.commit(status); qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName()); return ResponseUtil.ok(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initCollapseAnimations(String state){ collapseAnim = new Timeline(this); switch (state){ case "expand":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),250); break; } case "collapse":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),configManager.getFrameSettings(this.getClass().getSimpleName()).getFrameSize().width); } } collapseAnim.setEase(new Spline(1f)); collapseAnim.setDuration(300); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private void initCollapseAnimations(String state){ collapseAnim = new Timeline(this); switch (state){ case "expand":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),MAX_WIDTH); break; } case "collapse":{ collapseAnim.addPropertyToInterpolate("width",this.getWidth(),configManager.getFrameSettings(this.getClass().getSimpleName()).getFrameSize().width); } } collapseAnim.setEase(new Spline(1f)); collapseAnim.setDuration(300); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void loadConfigFile(){ JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject) parser.parse(new FileReader(CONFIG_FILE)); JSONArray buttons = (JSONArray) root.get("buttons"); cachedButtonsConfig = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) buttons) { cachedButtonsConfig.put((String) next.get("title"), (String) next.get("value")); } JSONArray framesSetting = (JSONArray) root.get("framesSettings"); cachedFramesSettings = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) framesSetting) { JSONObject location = (JSONObject) next.get("location"); JSONObject size = (JSONObject) next.get("size"); FrameSettings settings = new FrameSettings( new Point(((Long)location.get("frameX")).intValue(), ((Long)location.get("frameY")).intValue()), new Dimension(((Long)size.get("width")).intValue(),((Long)size.get("height")).intValue()) ); cachedFramesSettings.put((String) next.get("frameClassName"), settings); } whisperNotifier = WhisperNotifierStatus.valueOf((String)root.get("whisperNotifier")); decayTime = ((Long)root.get("decayTime")).intValue(); minOpacity = ((Long)root.get("minOpacity")).intValue(); maxOpacity = ((Long)root.get("maxOpacity")).intValue(); showOnStartUp = (boolean) root.get("showOnStartUp"); showPatchNotes = (boolean) root.get("showPatchNotes"); } catch (Exception e) { logger.error("Error in loadConfigFile: ",e); } } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code private void loadConfigFile(){ JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject) parser.parse(new FileReader(CONFIG_FILE)); JSONArray buttons = (JSONArray) root.get("buttons"); cachedButtonsConfig = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) buttons) { cachedButtonsConfig.put((String) next.get("title"), (String) next.get("value")); } JSONArray framesSetting = (JSONArray) root.get("framesSettings"); cachedFramesSettings = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) framesSetting) { JSONObject location = (JSONObject) next.get("location"); JSONObject size = (JSONObject) next.get("size"); FrameSettings settings = new FrameSettings( new Point(((Long)location.get("frameX")).intValue(), ((Long)location.get("frameY")).intValue()), new Dimension(((Long)size.get("width")).intValue(),((Long)size.get("height")).intValue()) ); cachedFramesSettings.put((String) next.get("frameClassName"), settings); } whisperNotifier = WhisperNotifierStatus.valueOf(loadProperty("whisperNotifier")); decayTime = Long.valueOf(loadProperty("decayTime")).intValue(); minOpacity = Long.valueOf(loadProperty("minOpacity")).intValue(); maxOpacity = Long.valueOf(loadProperty("maxOpacity")).intValue(); showOnStartUp = Boolean.valueOf(loadProperty("showOnStartUp")); showPatchNotes = Boolean.valueOf(loadProperty("showPatchNotes")); gamePath = loadProperty("gamePath"); } catch (Exception e) { logger.error("Error in loadConfigFile: ",e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private JPanel getFormattedMessagePanel(String message){ JPanel labelsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); labelsPanel.setBackground(AppThemeColor.TRANSPARENT); String itemName = StringUtils.substringBetween(message, "to buy your ", " listed for"); if(itemName == null){ itemName = StringUtils.substringBetween(message, "to buy your ", " for my"); } itemLabel = new ExLabel(itemName); itemLabel.setForeground(AppThemeColor.TEXT_IMPORTANT); labelsPanel.add(itemLabel); ExLabel secondPart = new ExLabel("listed for "); secondPart.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(secondPart); String price = StringUtils.substringBetween(message, "listed for ", " in "); if(price == null){ price = StringUtils.substringBetween(message, "for my ", " in "); } String[] split = price.split(" "); ExLabel currencyLabel = null; BufferedImage buttonIcon = null; try { switch (split[1]) { case "chaos": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Chaos_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "exalted": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Exalted_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } default: currencyLabel = new ExLabel(split[1]); currencyLabel.setForeground(AppThemeColor.TEXT_MESSAGE); break; } } catch (IOException e) { e.printStackTrace(); } ExLabel priceLabel = new ExLabel(split[0]); priceLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(priceLabel); labelsPanel.add(currencyLabel); String offer = StringUtils.substringAfterLast(message, "in Breach"); //todo String tabName = StringUtils.substringBetween(message, "(stash tab ", "; position:"); if(tabName !=null ){ offer = StringUtils.substringAfter(message, ")"); } ExLabel offerLabel = new ExLabel(offer); offerLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(offerLabel); return labelsPanel; } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code private JPanel getFormattedMessagePanel(String message){ JPanel labelsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); labelsPanel.setBackground(AppThemeColor.TRANSPARENT); String itemName = StringUtils.substringBetween(message, "to buy your ", " listed for"); if(itemName == null){ itemName = StringUtils.substringBetween(message, "to buy your ", " for my"); } itemLabel = new ExLabel(itemName); itemLabel.setForeground(AppThemeColor.TEXT_IMPORTANT); labelsPanel.add(itemLabel); ExLabel secondPart = new ExLabel("listed for "); secondPart.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(secondPart); String price = StringUtils.substringBetween(message, "listed for ", " in "); if(price == null){ price = StringUtils.substringBetween(message, "for my ", " in "); } if(price != null) { String[] split = price.split(" "); ExLabel currencyLabel = null; BufferedImage buttonIcon = null; try { switch (split[1]) { case "chaos": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Chaos_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "exalted": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Exalted_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "fusing": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Orb_of_Fusing.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } case "vaal": { buttonIcon = ImageIO.read(getClass().getClassLoader().getResource("Vaal_Orb.png")); BufferedImage icon = Scalr.resize(buttonIcon, 20); currencyLabel = new ExLabel(new ImageIcon(icon)); break; } default: currencyLabel = new ExLabel(split[1]); currencyLabel.setForeground(AppThemeColor.TEXT_MESSAGE); break; } } catch (IOException e) { e.printStackTrace(); } ExLabel priceLabel = new ExLabel(split[0]); priceLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(priceLabel); labelsPanel.add(currencyLabel); } String offer = StringUtils.substringAfterLast(message, "in Breach"); //todo String tabName = StringUtils.substringBetween(message, "(stash tab ", "; position:"); if(tabName !=null ){ offer = StringUtils.substringAfter(message, ")"); } ExLabel offerLabel = new ExLabel(offer); offerLabel.setForeground(AppThemeColor.TEXT_MESSAGE); labelsPanel.add(offerLabel); if(offer.length() > 1){ Dimension rectSize = new Dimension(); rectSize.setSize(350, 130); this.setMaximumSize(rectSize); this.setMinimumSize(rectSize); this.setPreferredSize(rectSize); } return labelsPanel; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void loadConfigFile(){ JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject) parser.parse(new FileReader(CONFIG_FILE)); JSONArray buttons = (JSONArray) root.get("buttons"); cachedButtonsConfig = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) buttons) { cachedButtonsConfig.put((String) next.get("title"), (String) next.get("value")); } JSONArray framesSetting = (JSONArray) root.get("framesSettings"); cachedFramesSettings = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) framesSetting) { JSONObject location = (JSONObject) next.get("location"); JSONObject size = (JSONObject) next.get("size"); FrameSettings settings = new FrameSettings( new Point(((Long)location.get("frameX")).intValue(), ((Long)location.get("frameY")).intValue()), new Dimension(((Long)size.get("width")).intValue(),((Long)size.get("height")).intValue()) ); cachedFramesSettings.put((String) next.get("frameClassName"), settings); } whisperNotifier = WhisperNotifierStatus.valueOf((String)root.get("whisperNotifier")); decayTime = ((Long)root.get("decayTime")).intValue(); minOpacity = ((Long)root.get("minOpacity")).intValue(); maxOpacity = ((Long)root.get("maxOpacity")).intValue(); showOnStartUp = (boolean) root.get("showOnStartUp"); showPatchNotes = (boolean) root.get("showPatchNotes"); } catch (Exception e) { logger.error("Error in loadConfigFile: ",e); } } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private void loadConfigFile(){ JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject) parser.parse(new FileReader(CONFIG_FILE)); JSONArray buttons = (JSONArray) root.get("buttons"); cachedButtonsConfig = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) buttons) { cachedButtonsConfig.put((String) next.get("title"), (String) next.get("value")); } JSONArray framesSetting = (JSONArray) root.get("framesSettings"); cachedFramesSettings = new HashMap<>(); for (JSONObject next : (Iterable<JSONObject>) framesSetting) { JSONObject location = (JSONObject) next.get("location"); JSONObject size = (JSONObject) next.get("size"); FrameSettings settings = new FrameSettings( new Point(((Long)location.get("frameX")).intValue(), ((Long)location.get("frameY")).intValue()), new Dimension(((Long)size.get("width")).intValue(),((Long)size.get("height")).intValue()) ); cachedFramesSettings.put((String) next.get("frameClassName"), settings); } whisperNotifier = WhisperNotifierStatus.valueOf(loadProperty("whisperNotifier")); decayTime = Long.valueOf(loadProperty("decayTime")).intValue(); minOpacity = Long.valueOf(loadProperty("minOpacity")).intValue(); maxOpacity = Long.valueOf(loadProperty("maxOpacity")).intValue(); showOnStartUp = Boolean.valueOf(loadProperty("showOnStartUp")); showPatchNotes = Boolean.valueOf(loadProperty("showPatchNotes")); gamePath = loadProperty("gamePath"); } catch (Exception e) { logger.error("Error in loadConfigFile: ",e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void load(){ File configFile = new File(HISTORY_FILE); if (configFile.exists()) { JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject)parser.parse(new FileReader(HISTORY_FILE)); JSONArray msgsArray = (JSONArray) root.get("messages"); messages = new String[msgsArray.size()]; for (int i = 0; i < msgsArray.size(); i++) { messages[i] = (String) msgsArray.get(i); } } catch (Exception e) { logger.error("Error during loading history file: ", e); } }else { try { FileWriter fileWriter = new FileWriter(HISTORY_FILE); JSONObject root = new JSONObject(); root.put("messages", new JSONArray()); fileWriter.write(root.toJSONString()); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { logger.error("Error during creating history file: ", e); } } } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code public void load(){ File configFile = new File(HISTORY_FILE); if (configFile.exists()) { JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject)parser.parse(new FileReader(HISTORY_FILE)); JSONArray msgsArray = (JSONArray) root.get("messages"); messages = new String[msgsArray.size()]; for (int i = 0; i < msgsArray.size(); i++) { messages[i] = (String) msgsArray.get(i); } } catch (Exception e) { logger.error("Error during loading history file: ", e); } }else { createEmptyFile(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void load() { File configFile = new File(CONFIG_FILE); if (!configFile.exists()) { try { new File(CONFIG_FILE_PATH).mkdir(); FileWriter fileWriter = new FileWriter(CONFIG_FILE); fileWriter.write(new JSONObject().toJSONString()); fileWriter.flush(); fileWriter.close(); saveButtonsConfig(getDefaultButtons()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double width = screenSize.getWidth(); double height = screenSize.getHeight(); saveComponentLocation("TaskBarFrame", new Point(500, 500)); saveComponentLocation("MessageFrame", new Point(700, 500)); saveComponentLocation("GamePathChooser", new Point(600, 500)); saveComponentLocation("TestCasesFrame", new Point(900, 500)); saveComponentLocation("SettingsFrame", new Point(600, 600)); saveComponentLocation("HistoryFrame", new Point(600, 600)); saveComponentLocation("NotificationFrame", new Point((int) width / 2, (int) height / 2)); } catch (IOException e) { logger.error(e); } } else { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(CONFIG_FILE)); JSONObject jsonObject = (JSONObject) obj; String gamePath = (String) jsonObject.get("gamePath"); JSONArray buttons = (JSONArray) jsonObject.get("buttons"); Map<String, String> buttonsConfig = new HashMap<>(); if (buttons != null) { for (JSONObject next : (Iterable<JSONObject>) buttons) { buttonsConfig.put((String) next.get("title"), (String) next.get("value")); } } else { buttonsConfig = getDefaultButtons(); } JSONObject taskBarLocation = (JSONObject) jsonObject.get("TaskBarFrame"); Point taskBarPoint = new Point( Integer.valueOf(String.valueOf(taskBarLocation.get("x"))), Integer.valueOf(String.valueOf(taskBarLocation.get("y")))); JSONObject messageLocation = (JSONObject) jsonObject.get("MessageFrame"); Point messagePoint = new Point( Integer.valueOf(String.valueOf(messageLocation.get("x"))), Integer.valueOf(String.valueOf(messageLocation.get("y")))); JSONObject gamePathLocation = (JSONObject) jsonObject.get("GamePathChooser"); Point gamePathPoint = new Point( Integer.valueOf(String.valueOf(gamePathLocation.get("x"))), Integer.valueOf(String.valueOf(gamePathLocation.get("y")))); JSONObject settingsLocation = (JSONObject) jsonObject.get("SettingsFrame"); Point settingsPoint = new Point( Integer.valueOf(String.valueOf(settingsLocation.get("x"))), Integer.valueOf(String.valueOf(settingsLocation.get("y")))); JSONObject historyLocation = (JSONObject) jsonObject.get("HistoryFrame"); Point historyPoint = new Point( Integer.valueOf(String.valueOf(historyLocation.get("x"))), Integer.valueOf(String.valueOf(historyLocation.get("y")))); JSONObject notificationLocation = (JSONObject) jsonObject.get("NotificationFrame"); Point notificationPoint = new Point( Integer.valueOf(String.valueOf(notificationLocation.get("x"))), Integer.valueOf(String.valueOf(notificationLocation.get("y")))); //removing JSONObject testLocation = (JSONObject) jsonObject.get("TestCasesFrame"); Point testPoint = new Point( Integer.valueOf(String.valueOf(testLocation.get("x"))), Integer.valueOf(String.valueOf(testLocation.get("y")))); properties.put("gamePath", gamePath); properties.put("buttons", buttonsConfig); properties.put("TaskBarFrame", taskBarPoint); properties.put("MessageFrame", messagePoint); properties.put("GamePathChooser", gamePathPoint); properties.put("SettingsFrame", settingsPoint); properties.put("HistoryFrame", historyPoint); properties.put("NotificationFrame", notificationPoint); //removing properties.put("TestCasesFrame", testPoint); } catch (Exception e) { logger.error("Error in ConfigManager.load", e); } } } #location 43 #vulnerability type NULL_DEREFERENCE
#fixed code private void load() { File configFile = new File(CONFIG_FILE); if (!configFile.exists()) { try { new File(CONFIG_FILE_PATH).mkdir(); FileWriter fileWriter = new FileWriter(CONFIG_FILE); fileWriter.write(new JSONObject().toJSONString()); fileWriter.flush(); fileWriter.close(); saveButtonsConfig(getDefaultButtons()); cachedFramesSettings = getDefaultFramesSettings(); getDefaultFramesSettings().forEach(this::saveFrameSettings); } catch (IOException e) { logger.error(e); } } else { loadConfigFile(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] tryDecompress(byte[] raw) throws Exception { if (!isGzipStream(raw)) { return raw; } GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(raw)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IoUtils.copy(gis, out); return out.toByteArray(); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] tryDecompress(byte[] raw) throws Exception { if (!isGzipStream(raw)) { return raw; } GZIPInputStream gis = null; ByteArrayOutputStream out = null; try { gis = new GZIPInputStream(new ByteArrayInputStream(raw)); out = new ByteArrayOutputStream(); IoUtils.copy(gis, out); return out.toByteArray(); } finally { if (out != null) { out.close(); } if (gis != null) { gis.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void signalPublish(String key, String value) throws Exception { long start = System.currentTimeMillis(); final Datum datum = new Datum(); datum.key = key; datum.value = value; if (RaftCore.getDatum(key) == null) { datum.timestamp.set(1L); } else { datum.timestamp.set(RaftCore.getDatum(key).timestamp.incrementAndGet()); } JSONObject json = new JSONObject(); json.put("datum", datum); json.put("source", peers.local()); onPublish(datum, peers.local()); final String content = JSON.toJSONString(json); for (final String server : peers.allServersIncludeMyself()) { if (isLeader(server)) { continue; } final String url = buildURL(server, API_ON_PUB); HttpClient.asyncHttpPostLarge(url, Arrays.asList("key=" + key), content, new AsyncCompletionHandler<Integer>() { @Override public Integer onCompleted(Response response) throws Exception { if (response.getStatusCode() != HttpURLConnection.HTTP_OK) { Loggers.RAFT.warn("RAFT", "failed to publish data to peer, datumId=" + datum.key + ", peer=" + server + ", http code=" + response.getStatusCode()); return 1; } return 0; } @Override public STATE onContentWriteCompleted() { return STATE.CONTINUE; } }); } long end = System.currentTimeMillis(); Loggers.RAFT.info("signalPublish cost " + (end - start) + " ms" + " : " + key); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void signalPublish(String key, String value) throws Exception { long start = System.currentTimeMillis(); final Datum datum = new Datum(); datum.key = key; datum.value = value; if (RaftCore.getDatum(key) == null) { datum.timestamp.set(1L); } else { datum.timestamp.set(RaftCore.getDatum(key).timestamp.incrementAndGet()); } JSONObject json = new JSONObject(); json.put("datum", datum); json.put("source", peers.local()); json.put("increaseTerm", false); onPublish(datum, peers.local(), false); final String content = JSON.toJSONString(json); for (final String server : peers.allServersIncludeMyself()) { if (isLeader(server)) { continue; } final String url = buildURL(server, API_ON_PUB); HttpClient.asyncHttpPostLarge(url, Arrays.asList("key=" + key), content, new AsyncCompletionHandler<Integer>() { @Override public Integer onCompleted(Response response) throws Exception { if (response.getStatusCode() != HttpURLConnection.HTTP_OK) { Loggers.RAFT.warn("RAFT", "failed to publish data to peer, datumId=" + datum.key + ", peer=" + server + ", http code=" + response.getStatusCode()); return 1; } return 0; } @Override public STATE onContentWriteCompleted() { return STATE.CONTINUE; } }); } long end = System.currentTimeMillis(); Loggers.RAFT.info("signalPublish cost " + (end - start) + " ms" + " : " + key); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8")); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); } #location 47 #vulnerability type RESOURCE_LEAK
#fixed code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void refreshSrvIfNeed() { try { if (!CollectionUtils.isEmpty(serverList)) { LogUtils.LOG.debug("server list provided by user: " + serverList); return; } if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { return; } List<String> list = getServerListFromEndpoint(); if (list.isEmpty()) { throw new Exception("Can not acquire vipserver list"); } if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); } serversFromEndpoint = list; lastSrvRefTime = System.currentTimeMillis(); } catch (Throwable e) { LogUtils.LOG.warn("failed to update server list", e); } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private void refreshSrvIfNeed() { try { if (!CollectionUtils.isEmpty(serverList)) { LogUtils.LOG.debug("server list provided by user: " + serverList); return; } if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) { return; } List<String> list = getServerListFromEndpoint(); if (CollectionUtils.isEmpty(list)) { throw new Exception("Can not acquire vipserver list"); } if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) { LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list); } serversFromEndpoint = list; lastSrvRefTime = System.currentTimeMillis(); } catch (Throwable e) { LogUtils.LOG.warn("failed to update server list", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] tryDecompress(InputStream raw) throws Exception { try { GZIPInputStream gis = new GZIPInputStream(raw); ByteArrayOutputStream out = new ByteArrayOutputStream(); IoUtils.copy(gis, out); return out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] tryDecompress(InputStream raw) throws Exception { try { GZIPInputStream gis = new GZIPInputStream(raw); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(gis, out); return out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void contextPrepared(ConfigurableApplicationContext context) { System.out.printf("Log files: %s/logs/%n", NACOS_HOME); System.out.printf("Conf files: %s/conf/%n", NACOS_HOME); System.out.printf("Data files: %s/data/%n", NACOS_HOME); if (!STANDALONE_MODE) { try { List<String> clusterConf = readClusterConf(); System.out.printf("The server IP list of Nacos is %s%n", clusterConf); } catch (IOException e) { logger.error("read cluster conf fail", e); } } System.out.println(); } #location 5 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code @Override public void contextPrepared(ConfigurableApplicationContext context) { }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8")); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); } #location 47 #vulnerability type RESOURCE_LEAK
#fixed code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString()); FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8"); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void contextPrepared(ConfigurableApplicationContext context) { System.out.printf("Log files: %s/logs/%n", NACOS_HOME); System.out.printf("Conf files: %s/conf/%n", NACOS_HOME); System.out.printf("Data files: %s/data/%n", NACOS_HOME); if (!STANDALONE_MODE) { try { List<String> clusterConf = readClusterConf(); System.out.printf("The server IP list of Nacos is %s%n", clusterConf); } catch (IOException e) { logger.error("read cluster conf fail", e); } } System.out.println(); } #location 4 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code @Override public void contextPrepared(ConfigurableApplicationContext context) { }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Instance selectOneHealthyInstance(String serviceName, List<String> clusters, boolean subscribe) throws NacosException { if (subscribe) { return Balancer.RandomByWeight.selectHost( hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","))); } else { return Balancer.RandomByWeight.selectHost( hostReactor.getServiceInfoDirectlyFromServer(serviceName, StringUtils.join(clusters, ","))); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Instance selectOneHealthyInstance(String serviceName, List<String> clusters, boolean subscribe) throws NacosException { return selectOneHealthyInstance(serviceName, Constants.DEFAULT_GROUP, clusters, subscribe); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/onAddIP4Dom") public String onAddIP4Dom(HttpServletRequest request) throws Exception { if (Switch.getDisableAddIP()) { throw new AccessControlException("Adding IP for dom is forbidden now."); } String clientIP = WebUtils.required(request, "clientIP"); long term = Long.parseLong(WebUtils.required(request, "term")); if (!RaftCore.isLeader(clientIP)) { Loggers.RAFT.warn("peer(" + JSON.toJSONString(clientIP) + ") tried to publish " + "data but wasn't leader, leader: " + JSON.toJSONString(RaftCore.getLeader())); throw new IllegalStateException("peer(" + clientIP + ") tried to publish " + "data but wasn't leader"); } if (term < RaftCore.getPeerSet().local().term.get()) { Loggers.RAFT.warn("out of date publish, pub-term: " + JSON.toJSONString(clientIP) + ", cur-term: " + JSON.toJSONString(RaftCore.getPeerSet().local())); throw new IllegalStateException("out of date publish, pub-term:" + term + ", cur-term: " + RaftCore.getPeerSet().local().term.get()); } RaftCore.getPeerSet().local().resetLeaderDue(); final String dom = WebUtils.required(request, "dom"); if (domainsManager.getDomain(dom) == null) { throw new IllegalStateException("dom doesn't exist: " + dom); } boolean updateOnly = Boolean.parseBoolean(WebUtils.optional(request, "updateOnly", Boolean.FALSE.toString())); String ipListString = WebUtils.required(request, "ipList"); List<IpAddress> newIPs = new ArrayList<>(); List<String> ipList; if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { newIPs = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() { }); } else { ipList = Arrays.asList(ipListString.split(",")); for (String ip : ipList) { IpAddress ipAddr = IpAddress.fromJSON(ip); newIPs.add(ipAddr); } } long timestamp = Long.parseLong(WebUtils.required(request, "timestamp")); if (CollectionUtils.isEmpty(newIPs)) { throw new IllegalArgumentException("Empty ip list"); } if (updateOnly) { //make sure every IP is in the dom, otherwise refuse update List<IpAddress> oldIPs = domainsManager.getDomain(dom).allIPs(); Collection diff = CollectionUtils.subtract(newIPs, oldIPs); if (diff.size() != 0) { throw new IllegalArgumentException("these IPs are not present: " + Arrays.toString(diff.toArray()) + ", if you want to add them, remove updateOnly flag"); } } domainsManager.easyAddIP4Dom(dom, newIPs, timestamp, term); return "ok"; } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @RequestMapping("/onAddIP4Dom") public String onAddIP4Dom(HttpServletRequest request) throws Exception { if (Switch.getDisableAddIP()) { throw new AccessControlException("Adding IP for dom is forbidden now."); } String clientIP = WebUtils.required(request, "clientIP"); long term = Long.parseLong(WebUtils.required(request, "term")); if (!RaftCore.isLeader(clientIP)) { Loggers.RAFT.warn("peer(" + JSON.toJSONString(clientIP) + ") tried to publish " + "data but wasn't leader, leader: " + JSON.toJSONString(RaftCore.getLeader())); throw new IllegalStateException("peer(" + clientIP + ") tried to publish " + "data but wasn't leader"); } if (term < RaftCore.getPeerSet().local().term.get()) { Loggers.RAFT.warn("out of date publish, pub-term: " + JSON.toJSONString(clientIP) + ", cur-term: " + JSON.toJSONString(RaftCore.getPeerSet().local())); throw new IllegalStateException("out of date publish, pub-term:" + term + ", cur-term: " + RaftCore.getPeerSet().local().term.get()); } RaftCore.getPeerSet().local().resetLeaderDue(); final String dom = WebUtils.required(request, "dom"); if (domainsManager.getDomain(dom) == null) { throw new IllegalStateException("dom doesn't exist: " + dom); } boolean updateOnly = Boolean.parseBoolean(WebUtils.optional(request, "updateOnly", Boolean.FALSE.toString())); String ipListString = WebUtils.required(request, "ipList"); List<IpAddress> newIPs = new ArrayList<>(); List<String> ipList; if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { newIPs = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() { }); } else { ipList = Arrays.asList(ipListString.split(",")); for (String ip : ipList) { IpAddress ipAddr = IpAddress.fromJSON(ip); newIPs.add(ipAddr); } } if (CollectionUtils.isEmpty(newIPs)) { throw new IllegalArgumentException("Empty ip list"); } if (updateOnly) { //make sure every IP is in the dom, otherwise refuse update List<IpAddress> oldIPs = domainsManager.getDomain(dom).allIPs(); Collection diff = CollectionUtils.subtract(newIPs, oldIPs); if (diff.size() != 0) { throw new IllegalArgumentException("these IPs are not present: " + Arrays.toString(diff.toArray()) + ", if you want to add them, remove updateOnly flag"); } } domainsManager.easyAddIP4Dom(dom, newIPs, term); return "ok"; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap = null; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); } #location 34 #vulnerability type NULL_DEREFERENCE
#fixed code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap = null; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void registerInstance(String namespaceId, String serviceName, String clusterName, Instance instance) throws Exception { Service service = getService(namespaceId, serviceName); boolean serviceUpdated = false; if (service == null) { service = new Service(); service.setName(serviceName); service.setNamespaceId(namespaceId); // now validate the dom. if failed, exception will be thrown service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(); cluster.setName(instance.getClusterName()); cluster.setDom(service); cluster.init(); if (service.getClusterMap().containsKey(cluster.getName())) { service.getClusterMap().get(cluster.getName()).update(cluster); } else { service.getClusterMap().put(cluster.getName(), cluster); } service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (serviceUpdated) { Lock lock = addLockIfAbsent(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); Condition condition = addCondtion(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); addOrReplaceService(service); try { lock.lock(); condition.await(5000, TimeUnit.MILLISECONDS); } finally { lock.unlock(); } } if (service.allIPs().contains(instance)) { throw new NacosException(NacosException.INVALID_PARAM, "instance already exist: " + instance); } addInstance(namespaceId, serviceName, clusterName, instance.isEphemeral(), instance); } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void registerInstance(String namespaceId, String serviceName, String clusterName, Instance instance) throws Exception { Service service = getService(namespaceId, serviceName); boolean serviceUpdated = false; if (service == null) { service = new Service(); service.setName(serviceName); service.setNamespaceId(namespaceId); // now validate the dom. if failed, exception will be thrown service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(); cluster.setName(instance.getClusterName()); cluster.setDom(service); cluster.init(); if (service.getClusterMap().containsKey(cluster.getName())) { service.getClusterMap().get(cluster.getName()).update(cluster); } else { service.getClusterMap().put(cluster.getName(), cluster); } service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (serviceUpdated) { Lock lock = addLockIfAbsent(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); Condition condition = addCondtion(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); final Service finalService = service; GlobalExecutor.submit(new Runnable() { @Override public void run() { try { addOrReplaceService(finalService); } catch (Exception e) { Loggers.SRV_LOG.error("register or update service failed, service: {}", finalService, e); } } }); try { lock.lock(); condition.await(5000, TimeUnit.MILLISECONDS); } finally { lock.unlock(); } } if (service.allIPs().contains(instance)) { throw new NacosException(NacosException.INVALID_PARAM, "instance already exist: " + instance); } addInstance(namespaceId, serviceName, clusterName, instance.isEphemeral(), instance); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8")); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); } #location 47 #vulnerability type RESOURCE_LEAK
#fixed code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = readClusterConf(); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = readClusterConf(); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = readClusterConf(); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); Set<Integer> currentInstanceIndexes = Sets.newHashSet(); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); if (instance.getInstanceIndex() != null) { currentInstanceIndexes.add(instance.getInstanceIndex()); } } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { // Generate instance index int instanceIndex = 0; while (currentInstanceIndexes.contains(instanceIndex)) { instanceIndex++; } currentInstanceIndexes.add(instanceIndex); instance.setInstanceIndex(instanceIndex); instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException { Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral)); List<Instance> currentIPs = service.allIPs(ephemeral); Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size()); Set<String> currentInstanceIds = Sets.newHashSet(); for (Instance instance : currentIPs) { currentInstances.put(instance.toIPAddr(), instance); currentInstanceIds.add(instance.getInstanceId()); } Map<String, Instance> instanceMap; if (datum != null) { instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances); } else { instanceMap = new HashMap<>(ips.length); } for (Instance instance : ips) { if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(instance.getClusterName(), service); cluster.init(); service.getClusterMap().put(instance.getClusterName(), cluster); Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.", instance.getClusterName(), instance.toJSON()); } if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) { instanceMap.remove(instance.getDatumKey()); } else { instance.setInstanceId(instance.generateInstanceId(currentInstanceIds)); instanceMap.put(instance.getDatumKey(), instance); } } if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) { throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: " + JSON.toJSONString(instanceMap.values())); } return new ArrayList<>(instanceMap.values()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> readClusterConf() throws IOException { List<String> instanceList = new ArrayList<String>(); List<String> lines = IoUtils.readLines( new InputStreamReader(new FileInputStream(new File(CLUSTER_CONF_FILE_PATH)), UTF_8)); String comment = "#"; for (String line : lines) { String instance = line.trim(); if (instance.startsWith(comment)) { // # it is ip continue; } if (instance.contains(comment)) { // 192.168.71.52:8848 # Instance A instance = instance.substring(0, instance.indexOf(comment)); instance = instance.trim(); } instanceList.add(instance); } return instanceList; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public static List<String> readClusterConf() throws IOException { List<String> instanceList = new ArrayList<String>(); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(new File(CLUSTER_CONF_FILE_PATH)), UTF_8); List<String> lines = IoUtils.readLines(reader); String comment = "#"; for (String line : lines) { String instance = line.trim(); if (instance.startsWith(comment)) { // # it is ip continue; } if (instance.contains(comment)) { // 192.168.71.52:8848 # Instance A instance = instance.substring(0, instance.indexOf(comment)); instance = instance.trim(); } instanceList.add(instance); } return instanceList; } finally { if (reader != null) { reader.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @NeedAuth @RequestMapping("/remvIP4Dom") public String remvIP4Dom(HttpServletRequest request) throws Exception { String dom = WebUtils.required(request, "dom"); String ipListString = WebUtils.required(request, "ipList"); Loggers.DEBUG_LOG.debug("[REMOVE-IP] full arguments: serviceName:" + dom + ", iplist:" + ipListString); List<IpAddress> newIPs = new ArrayList<>(); List<String> ipList = new ArrayList<>(); if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { newIPs = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() { }); } else { ipList = Arrays.asList(ipListString.split(",")); } List<IpAddress> ipObjList = new ArrayList<>(ipList.size()); if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { ipObjList = newIPs; } else { for (String ip : ipList) { ipObjList.add(IpAddress.fromJSON(ip)); } } domainsManager.easyRemvIP4Dom(dom, ipObjList); Loggers.EVT_LOG.info("{" + dom + "} {POS} {IP-REMV}" + " dead: " + ipList + " operator: " + WebUtils.optional(request, "clientIP", "unknown")); return "ok"; } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @NeedAuth @RequestMapping("/remvIP4Dom") public String remvIP4Dom(HttpServletRequest request) throws Exception { String dom = WebUtils.required(request, "dom"); String ipListString = WebUtils.required(request, "ipList"); Map<String, String> proxyParams = new HashMap<>(16); for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { proxyParams.put(entry.getKey(), entry.getValue()[0]); } if (Loggers.DEBUG_LOG.isDebugEnabled()) { Loggers.DEBUG_LOG.debug("[REMOVE-IP] full arguments: params:" + proxyParams); } List<String> ipList = new ArrayList<>(); List<IpAddress> ipObjList = new ArrayList<>(ipList.size()); if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) { ipList = Arrays.asList(ipListString); ipObjList = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() { }); } else { ipList = Arrays.asList(ipListString.split(",")); for (String ip : ipList) { ipObjList.add(IpAddress.fromJSON(ip)); } } if (!RaftCore.isLeader()) { Loggers.RAFT.info("I'm not leader, will proxy to leader."); if (RaftCore.getLeader() == null) { throw new IllegalArgumentException("no leader now."); } RaftPeer leader = RaftCore.getLeader(); String server = leader.ip; if (!server.contains(UtilsAndCommons.CLUSTER_CONF_IP_SPLITER)) { server = server + UtilsAndCommons.CLUSTER_CONF_IP_SPLITER + RunningConfig.getServerPort(); } String url = "http://" + server + RunningConfig.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/api/remvIP4Dom"; HttpClient.HttpResult result1 = HttpClient.httpPost(url, null, proxyParams); if (result1.code != HttpURLConnection.HTTP_OK) { Loggers.SRV_LOG.warn("failed to remove ip for dom, caused " + result1.content); throw new IllegalArgumentException("failed to remove ip for dom, caused " + result1.content); } return "ok"; } VirtualClusterDomain domain = (VirtualClusterDomain) domainsManager.getDomain(dom); if (domain == null) { throw new IllegalStateException("dom doesn't exist: " + dom); } if (CollectionUtils.isEmpty(ipObjList)) { throw new IllegalArgumentException("Empty ip list"); } String key = UtilsAndCommons.getIPListStoreKey(domainsManager.getDomain(dom)); long timestamp = 1; if (RaftCore.getDatum(key) != null) { timestamp = RaftCore.getDatum(key).timestamp.get(); } if (RaftCore.isLeader()) { try { RaftCore.OPERATE_LOCK.lock(); proxyParams.put("clientIP", NetUtils.localServer()); proxyParams.put("notify", "true"); proxyParams.put("term", String.valueOf(RaftCore.getPeerSet().local().term)); proxyParams.put("timestamp", String.valueOf(timestamp)); onRemvIP4Dom(MockHttpRequest.buildRequest2(proxyParams)); if (domain.getEnableHealthCheck() && !domain.getEnableClientBeat()) { syncOnRemvIP4Dom(dom, ipList, proxyParams, WebUtils.optional(request, "clientIP", "unknown")); } else { asyncOnRemvIP4Dom(dom, ipList, proxyParams, WebUtils.optional(request, "clientIP", "unknown")); } } finally { RaftCore.OPERATE_LOCK.unlock(); } Loggers.EVT_LOG.info("{" + dom + "} {POS} {IP-REMV}" + " new: " + ipListString + " operatorIP: " + WebUtils.optional(request, "clientIP", "unknown")); } return "ok"; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void checkLocalConfig(CacheData cacheData) { final String dataId = cacheData.dataId; final String group = cacheData.group; final String tenant = cacheData.tenant; File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant); // 没有 -> 有 if (!cacheData.isUseLocalConfigInfo() && path.exists()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5.getInstance().getMD5String(content); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); return; } // 有 -> 没有。不通知业务监听器,从server拿到配置后通知。 if (cacheData.isUseLocalConfigInfo() && !path.exists()) { cacheData.setUseLocalConfigInfo(false); LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(), dataId, group, tenant); return; } // 有变更 if (cacheData.isUseLocalConfigInfo() && path.exists() && cacheData.getLocalConfigInfoVersion() != path.lastModified()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5.getInstance().getMD5String(content); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code private void checkLocalConfig(CacheData cacheData) { final String dataId = cacheData.dataId; final String group = cacheData.group; final String tenant = cacheData.tenant; File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant); // 没有 -> 有 if (!cacheData.isUseLocalConfigInfo() && path.exists()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); return; } // 有 -> 没有。不通知业务监听器,从server拿到配置后通知。 if (cacheData.isUseLocalConfigInfo() && !path.exists()) { cacheData.setUseLocalConfigInfo(false); LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(), dataId, group, tenant); return; } // 有变更 if (cacheData.isUseLocalConfigInfo() && path.exists() && cacheData.getLocalConfigInfoVersion() != path.lastModified()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void registerInstance(String namespaceId, String serviceName, String clusterName, Instance instance) throws Exception { Service service = getService(namespaceId, serviceName); boolean serviceUpdated = false; if (service == null) { service = new Service(); service.setName(serviceName); service.setNamespaceId(namespaceId); // now validate the service. if failed, exception will be thrown service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(); cluster.setName(instance.getClusterName()); cluster.setDom(service); cluster.init(); if (service.getClusterMap().containsKey(cluster.getName())) { service.getClusterMap().get(cluster.getName()).update(cluster); } else { service.getClusterMap().put(cluster.getName(), cluster); } service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (serviceUpdated) { Lock lock = addLockIfAbsent(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); Condition condition = addCondtion(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName)); final Service finalService = service; GlobalExecutor.submit(new Runnable() { @Override public void run() { try { addOrReplaceService(finalService); } catch (Exception e) { Loggers.SRV_LOG.error("register or update service failed, service: {}", finalService, e); } } }); try { lock.lock(); condition.await(5000, TimeUnit.MILLISECONDS); } finally { lock.unlock(); } } if (service.allIPs().contains(instance)) { throw new NacosException(NacosException.INVALID_PARAM, "instance already exist: " + instance); } addInstance(namespaceId, serviceName, clusterName, instance.isEphemeral(), instance); } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void registerInstance(String namespaceId, String serviceName, String clusterName, Instance instance) throws Exception { Service service = getService(namespaceId, serviceName); boolean serviceUpdated = false; if (service == null) { service = new Service(); service.setName(serviceName); service.setNamespaceId(namespaceId); // now validate the service. if failed, exception will be thrown service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } if (!service.getClusterMap().containsKey(instance.getClusterName())) { Cluster cluster = new Cluster(); cluster.setName(instance.getClusterName()); cluster.setDom(service); cluster.init(); if (service.getClusterMap().containsKey(cluster.getName())) { service.getClusterMap().get(cluster.getName()).update(cluster); } else { service.getClusterMap().put(cluster.getName(), cluster); } service.setLastModifiedMillis(System.currentTimeMillis()); service.recalculateChecksum(); service.valid(); serviceUpdated = true; } // only local memory is updated: if (serviceUpdated) { putService(service); } if (service.allIPs().contains(instance)) { throw new NacosException(NacosException.INVALID_PARAM, "instance already exist: " + instance); } addInstance(namespaceId, serviceName, clusterName, instance.isEphemeral(), instance); }
Below is the vulnerable code, please generate the patch based on the following information.