input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Test void shouldAutoEnableCaching() { AnnotationConfigApplicationContext context = setup(""); assertThat(context.getBeansOfType(CacheManager.class)).isNotEmpty(); assertThat(context.getBeansOfType(CacheManager.class).get("cacheManager")) .isNotInstanceOf(NoOpCacheManager.class); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test void shouldAutoEnableCaching() { ApplicationContextRunner contextRunner = baseApplicationRunner(); contextRunner.run(context -> { assertThat(context.getBeansOfType(CacheManager.class)).hasSize(1); assertThat(((CacheManager) context.getBean("loadBalancerCacheManager")) .getCacheNames()).hasSize(1); assertThat(context.getBean("loadBalancerCacheManager")) .isInstanceOf(CaffeineCacheManager.class); assertThat(((CacheManager) context.getBean("loadBalancerCacheManager")) .getCacheNames()).contains("CachingServiceInstanceListSupplierCache"); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void newConnectionManagerWithTTL() throws Exception { HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory() .newConnectionManager(false, 2, 6, 56L, TimeUnit.DAYS, null); then(((PoolingHttpClientConnectionManager) connectionManager) .getDefaultMaxPerRoute()).isEqualTo(6); then(((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal()) .isEqualTo(2); Object pool = getField(((PoolingHttpClientConnectionManager) connectionManager), "pool"); then((Long) getField(pool, "timeToLive")).isEqualTo(new Long(56)); TimeUnit timeUnit = getField(pool, "tunit"); then(timeUnit).isEqualTo(TimeUnit.DAYS); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void newConnectionManagerWithTTL() { HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory() .newConnectionManager(false, 2, 6, 56L, TimeUnit.DAYS, null); then(((PoolingHttpClientConnectionManager) connectionManager) .getDefaultMaxPerRoute()).isEqualTo(6); then(((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal()) .isEqualTo(2); Object pool = getField((connectionManager), "pool"); then((Long) getField(pool, "timeToLive")).isEqualTo(new Long(56)); TimeUnit timeUnit = getField(pool, "timeUnit"); then(timeUnit).isEqualTo(TimeUnit.DAYS); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @ManagedOperation public boolean rebind(String name) { if (!this.beans.getBeanNames().contains(name)) { return false; } if (this.applicationContext != null) { try { Object bean = this.applicationContext.getBean(name); if (AopUtils.isAopProxy(bean)) { bean = getTargetObject(bean); } // TODO: determine a more general approach to fix this. // see https://github.com/spring-cloud/spring-cloud-commons/issues/318 if (bean.getClass().getName().equals("com.zaxxer.hikari.HikariDataSource")) { return false; //ignore } this.applicationContext.getAutowireCapableBeanFactory().destroyBean(bean); this.applicationContext.getAutowireCapableBeanFactory() .initializeBean(bean, name); return true; } catch (RuntimeException e) { this.errors.put(name, e); throw e; } } return false; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @ManagedOperation public boolean rebind(String name) { if (!this.beans.getBeanNames().contains(name)) { return false; } if (this.applicationContext != null) { try { Object bean = this.applicationContext.getBean(name); if (AopUtils.isAopProxy(bean)) { bean = getTargetObject(bean); } this.applicationContext.getAutowireCapableBeanFactory().destroyBean(bean); this.applicationContext.getAutowireCapableBeanFactory() .initializeBean(bean, name); return true; } catch (RuntimeException e) { this.errors.put(name, e); throw e; } catch (Exception e) { this.errors.put(name, e); throw new IllegalStateException("Cannot rebind to " + name, e); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void newConnectionManager() throws Exception { HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory() .newConnectionManager(false, 2, 6); then(((PoolingHttpClientConnectionManager) connectionManager) .getDefaultMaxPerRoute()).isEqualTo(6); then(((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal()) .isEqualTo(2); Object pool = getField(((PoolingHttpClientConnectionManager) connectionManager), "pool"); then((Long) getField(pool, "timeToLive")).isEqualTo(new Long(-1)); TimeUnit timeUnit = getField(pool, "tunit"); then(timeUnit).isEqualTo(TimeUnit.MILLISECONDS); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void newConnectionManager() { HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory() .newConnectionManager(false, 2, 6); then(((PoolingHttpClientConnectionManager) connectionManager) .getDefaultMaxPerRoute()).isEqualTo(6); then(((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal()) .isEqualTo(2); Object pool = getField((connectionManager), "pool"); then((Long) getField(pool, "timeToLive")).isEqualTo(new Long(-1)); TimeUnit timeUnit = getField(pool, "timeUnit"); then(timeUnit).isEqualTo(TimeUnit.MILLISECONDS); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HostInfo convertAddress(final InetAddress address) { HostInfo hostInfo = new HostInfo(); Future<String> result = getExecutor().submit(new Callable<String>() { @Override public String call() throws Exception { return address.getHostName(); } }); String hostname; try { hostname = result.get(this.properties.getTimeoutSeconds(), TimeUnit.SECONDS); } catch (Exception e) { log.info("Cannot determine local hostname"); hostname = "localhost"; } hostInfo.setHostname(hostname); hostInfo.setIpAddress(address.getHostAddress()); return hostInfo; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public HostInfo convertAddress(final InetAddress address) { HostInfo hostInfo = new HostInfo(); Future<String> result = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { return address.getHostName(); } }); String hostname; try { hostname = result.get(this.properties.getTimeoutSeconds(), TimeUnit.SECONDS); } catch (Exception e) { log.info("Cannot determine local hostname"); hostname = "localhost"; } hostInfo.setHostname(hostname); hostInfo.setIpAddress(address.getHostAddress()); return hostInfo; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void receive(DatagramPacket p) throws IOException { synchronized (inReceiveSyncRoot) { inReceive++; } try { super.receive(p); } finally { synchronized (inReceiveSyncRoot) { inReceive--; inReceiveSyncRoot.notifyAll(); } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void receive(DatagramPacket p) throws IOException { final Lock receiveLock = receiveCloseLock.readLock(); receiveLock.lock(); try { super.receive(p); } finally { receiveLock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); // cancel termination timer in case agent is freed // before termination timer is triggered synchronized (terminationFutureSyncRoot) { if (terminationFuture != null) { terminationFuture.cancel(true); terminationFuture = null; } } //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void validateRequestAttributes(StunMessageEvent evt) throws IllegalArgumentException, StunException, IOException { Message request = evt.getMessage(); //assert valid username UsernameAttribute unameAttr = (UsernameAttribute)request .getAttribute(Attribute.USERNAME); String username; if (unameAttr != null) { username = new String(unameAttr.getUsername()); if (!validateUsername( unameAttr)) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNAUTHORIZED, "unknown user " + username); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Non-recognized username: " + new String(unameAttr.getUsername())); } } //assert Message Integrity MessageIntegrityAttribute msgIntAttr = (MessageIntegrityAttribute) request.getAttribute(Attribute.MESSAGE_INTEGRITY); if (msgIntAttr != null) { //we should complain if we have msg integrity and no username. if (unameAttr == null) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.BAD_REQUEST, "missing username"); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Missing USERNAME in the presence of MESSAGE-INTEGRITY: "); } if (!validateMessageIntegrity(msgIntAttr, new String(unameAttr.getUsername()), evt.getRawMessage())) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNAUTHORIZED, "Wrong MESSAGE-INTEGRITY value"); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Wrong MESSAGE-INTEGRITY value."); } } else if(Boolean.getBoolean(StackProperties.REQUIRE_MESSAGE_INTEGRITY)) { // no message integrity Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNAUTHORIZED, "Missing MESSAGE-INTEGRITY."); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Missing MESSAGE-INTEGRITY."); } //look for unknown attributes. List<Attribute> allAttributes = request.getAttributes(); StringBuffer sBuff = new StringBuffer(); for(Attribute attr : allAttributes) { if(attr instanceof OptionalAttribute && attr.getAttributeType() < Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE) sBuff.append(attr.getAttributeType()); } if (sBuff.length() > 0) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNKNOWN_ATTRIBUTE, "unknown attribute ", sBuff.toString().toCharArray()); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Missing MESSAGE-INTEGRITY."); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code private void validateRequestAttributes(StunMessageEvent evt) throws IllegalArgumentException, StunException, IOException { Message request = evt.getMessage(); //assert valid username UsernameAttribute unameAttr = (UsernameAttribute)request .getAttribute(Attribute.USERNAME); String username = null; if (unameAttr != null) { username = LongTermCredential.toString(unameAttr.getUsername()); if (!validateUsername(username)) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNAUTHORIZED, "unknown user " + username); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Non-recognized username: " + username); } } //assert Message Integrity MessageIntegrityAttribute msgIntAttr = (MessageIntegrityAttribute) request.getAttribute(Attribute.MESSAGE_INTEGRITY); if (msgIntAttr != null) { //we should complain if we have msg integrity and no username. if (unameAttr == null) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.BAD_REQUEST, "missing username"); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Missing USERNAME in the presence of MESSAGE-INTEGRITY: "); } if (!validateMessageIntegrity( msgIntAttr, username, true, evt.getRawMessage())) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNAUTHORIZED, "Wrong MESSAGE-INTEGRITY value"); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Wrong MESSAGE-INTEGRITY value."); } } else if(Boolean.getBoolean(StackProperties.REQUIRE_MESSAGE_INTEGRITY)) { // no message integrity Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNAUTHORIZED, "Missing MESSAGE-INTEGRITY."); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Missing MESSAGE-INTEGRITY."); } //look for unknown attributes. List<Attribute> allAttributes = request.getAttributes(); StringBuffer sBuff = new StringBuffer(); for(Attribute attr : allAttributes) { if(attr instanceof OptionalAttribute && attr.getAttributeType() < Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE) sBuff.append(attr.getAttributeType()); } if (sBuff.length() > 0) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNKNOWN_ATTRIBUTE, "unknown attribute ", sBuff.toString().toCharArray()); sendResponse(request.getTransactionID(), error, evt.getLocalAddress(), evt.getRemoteAddress()); throw new IllegalArgumentException( "Missing MESSAGE-INTEGRITY."); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String[] getBlockedInterfaces() { if (!interfaceFiltersinitialized) { try { initializeInterfaceFilters(); } catch (Exception e) { logger.log(Level.WARNING, "There were errors during host " + "candidate interface filters initialization.", e); } } return blockedInterfaces; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static String[] getBlockedInterfaces() { if (!interfaceFiltersInitialized) { try { initializeInterfaceFilters(); } catch (Exception e) { logger.log(Level.WARNING, "There were errors during host " + "candidate interface filters initialization.", e); } } return blockedInterfaces; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean hasRequestListeners(TransportAddress localAddr) { synchronized(requestListeners) { if(!requestListeners.isEmpty()) { // there is a generic listener return true; } } synchronized(requestListenersChildren) { if (requestListenersChildren != null) { EventDispatcher child = requestListenersChildren.get(localAddr); if (child != null && child.requestListeners != null) { return !child.requestListeners.isEmpty(); } } } return false; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean hasRequestListeners(TransportAddress localAddr) { synchronized(requestListeners) { if(!requestListeners.isEmpty()) { // there is a generic listener return true; } } synchronized(requestListenersChildren) { if (!requestListenersChildren.isEmpty()) { EventDispatcher child = requestListenersChildren.get(localAddr); if (child != null && child.requestListeners != null) { return !child.requestListeners.isEmpty(); } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void free() { synchronized (localCandidates) { /* * Since the sockets of the non-HostCandidate LocalCandidates may * depend on the socket of the HostCandidate for which they have * been harvested, order the freeing. */ CandidateType[] candidateTypes = new CandidateType[] { CandidateType.RELAYED_CANDIDATE, CandidateType.PEER_REFLEXIVE_CANDIDATE, CandidateType.SERVER_REFLEXIVE_CANDIDATE }; for (CandidateType candidateType : candidateTypes) { Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); if (candidateType.equals(localCandidate.getType())) { free(localCandidate); localCandidateIter.remove(); } } } // Free whatever's left. Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); free(localCandidate); localCandidateIter.remove(); } } getParentStream().removePairStateChangeListener(this); keepAlivePairs.clear(); getComponentSocket().close(); socket.close(); } #location 50 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void free() { synchronized (localCandidates) { /* * Since the sockets of the non-HostCandidate LocalCandidates may * depend on the socket of the HostCandidate for which they have * been harvested, order the freeing. */ CandidateType[] candidateTypes = new CandidateType[] { CandidateType.RELAYED_CANDIDATE, CandidateType.PEER_REFLEXIVE_CANDIDATE, CandidateType.SERVER_REFLEXIVE_CANDIDATE }; for (CandidateType candidateType : candidateTypes) { Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); if (candidateType.equals(localCandidate.getType())) { free(localCandidate); localCandidateIter.remove(); } } } // Free whatever's left. Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); free(localCandidate); localCandidateIter.remove(); } } getParentStream().removePairStateChangeListener(this); keepAlivePairs.clear(); if (componentSocket != null) { componentSocket.close(); } if (socket != null) { socket.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String[] getAllowedInterfaces(){ if (!interfaceFiltersinitialized) { try { initializeInterfaceFilters(); } catch (Exception e) { logger.log(Level.WARNING, "There were errors during host " + "candidate interface filters initialization.", e); } } return allowedInterfaces; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static String[] getAllowedInterfaces(){ if (!interfaceFiltersInitialized) { try { initializeInterfaceFilters(); } catch (Exception e) { logger.log(Level.WARNING, "There were errors during host " + "candidate interface filters initialization.", e); } } return allowedInterfaces; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void incomingCheckReceived(TransportAddress remoteAddress, TransportAddress localAddress, long priority, String remoteUFrag, String localUFrag, boolean useCandidate) { if (isOver()) { //means we already completed ICE and are happily running media //the only reason we are called is most probably because the remote //party is still sending Binding Requests our way and making sure we //are still alive. return; } String ufrag = null; LocalCandidate localCandidate = null; localCandidate = findLocalCandidate(localAddress); if (localCandidate == null) { logger.info("No localAddress for this incoming checks: " + localAddress); return; } Component parentComponent = localCandidate.getParentComponent(); RemoteCandidate remoteCandidate = null; remoteCandidate = new RemoteCandidate( remoteAddress, parentComponent, CandidateType.PEER_REFLEXIVE_CANDIDATE, foundationsRegistry.obtainFoundationForPeerReflexiveCandidate(), priority, // We can not know the related candidate of a remote peer // reflexive candidate. We must set it to "null". null, ufrag); CandidatePair triggeredPair = createCandidatePair(localCandidate, remoteCandidate); logger.fine("set use-candidate " + useCandidate + " for pair " + triggeredPair.toShortString()); if (useCandidate) { triggeredPair.setUseCandidateReceived(); } synchronized(startLock) { if (isStarted()) { //we are started, which means we have the remote candidates //so it's now safe to go and see whether this is a new PR cand. if (triggeredPair.getParentComponent().getSelectedPair() == null) { logger.info("Received check from " + triggeredPair.toShortString() + " triggered a check. " + "Local ufrag " + getLocalUfrag()); } triggerCheck(triggeredPair); } else { logger.fine("Receive STUN checks before our ICE has started"); //we are not started yet so we'd better wait until we get the //remote candidates in case we are holding to a new PR one. this.preDiscoveredPairsQueue.add(triggeredPair); } } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void incomingCheckReceived(TransportAddress remoteAddress, TransportAddress localAddress, long priority, String remoteUFrag, String localUFrag, boolean useCandidate) { String ufrag = null; LocalCandidate localCandidate = findLocalCandidate(localAddress); if (localCandidate == null) { logger.info("No localAddress for this incoming checks: " + localAddress); return; } Component parentComponent = localCandidate.getParentComponent(); RemoteCandidate remoteCandidate = new RemoteCandidate( remoteAddress, parentComponent, CandidateType.PEER_REFLEXIVE_CANDIDATE, foundationsRegistry.obtainFoundationForPeerReflexiveCandidate(), priority, // We can not know the related candidate of a remote peer // reflexive candidate. We must set it to "null". null, ufrag); CandidatePair triggeredPair = createCandidatePair(localCandidate, remoteCandidate); logger.fine("set use-candidate " + useCandidate + " for pair " + triggeredPair.toShortString()); if (useCandidate) { triggeredPair.setUseCandidateReceived(); } synchronized(startLock) { if (state == IceProcessingState.WAITING) { logger.fine("Receive STUN checks before our ICE has started"); //we are not started yet so we'd better wait until we get the //remote candidates in case we are holding to a new PR one. this.preDiscoveredPairsQueue.add(triggeredPair); } else if (state == IceProcessingState.FAILED) { // Failure is permanent, currently. } else //Running, Connected or Terminated. { if (logger.isLoggable(Level.FINE)) { logger.debug("Received check from " + triggeredPair.toShortString() + " triggered a check. " + "Local ufrag " + getLocalUfrag()); } // We have been started, and have not failed (yet). If this is // a new pair, handle it (even if we have already completed). triggerCheck(triggeredPair); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); // cancel termination timer in case agent is freed // before termination timer is triggered synchronized (terminationFutureSyncRoot) { if (terminationFuture != null) { terminationFuture.cancel(true); terminationFuture = null; } } //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). stunKeepAliveRunner.cancel(); // cancel termination timer in case agent is freed // before termination timer is triggered synchronized (terminationFutureSyncRoot) { if (terminationFuture != null) { terminationFuture.cancel(true); terminationFuture = null; } } //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); // cancel termination timer in case agent is freed // before termination timer is triggered synchronized (terminationFutureSyncRoot) { if (terminationFuture != null) { terminationFuture.cancel(true); terminationFuture = null; } } //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if (getState().isEstablished()) { return; } List<IceMediaStream> streams = getStreams(); for (IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if (checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if (checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if (!allListsEnded) { return; } if (!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( if (logger.isLoggable(Level.INFO)) { if (connCheckClient.isAlive() || connCheckServer.isAlive()) { logger.info("Suspicious ICE connectivity failure. Checks" + " failed but the remote end was able to reach us."); } logger.info("ICE state is FAILED"); } terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if (getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } // The race condition in which another thread enters COMPLETED right // under our nose here has been observed (and not in a single instance) // So check that we did indeed just trigger the change. if (!setState(IceProcessingState.COMPLETED)) { return; } // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) if (stunKeepAliveThread == null && !StackProperties.getBoolean( StackProperties.NO_KEEP_ALIVES, false)) { // schedule STUN checks for selected candidates scheduleStunKeepAlive(); } scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); } #location 73 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if (getState().isEstablished()) { return; } List<IceMediaStream> streams = getStreams(); for (IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if (checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if (checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if (!allListsEnded) { return; } if (!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( if (logger.isLoggable(Level.INFO)) { if (connCheckClient.isAlive() || connCheckServer.isAlive()) { logger.info("Suspicious ICE connectivity failure. Checks" + " failed but the remote end was able to reach us."); } logger.info("ICE state is FAILED"); } terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if (getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } // The race condition in which another thread enters COMPLETED right // under our nose here has been observed (and not in a single instance) // So check that we did indeed just trigger the change. if (!setState(IceProcessingState.COMPLETED)) { return; } // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) scheduleStunKeepAlive(); scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if(getState() == IceProcessingState.COMPLETED) return; List<IceMediaStream> streams = getStreams(); for(IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if(checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if(checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if(!allListsEnded) return; if(!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( logger.info("ICE state is FAILED"); terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if(getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } logger.info("ICE state is COMPLETED"); setState(IceProcessingState.COMPLETED); // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) if(stunKeepAliveThread == null && !StackProperties.getBoolean( StackProperties.NO_KEEP_ALIVES, false)) { // schedule STUN checks for selected candidates scheduleStunKeepAlive(); } scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); } #location 36 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if(getState() == IceProcessingState.COMPLETED) return; List<IceMediaStream> streams = getStreams(); for(IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if(checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if(checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if(!allListsEnded) return; if(!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if(getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } // The race condition in which another thread enters COMPLETED right // under our nose here has been observed (and not in a single instance) // So check that we did indeed just trigger the change. if (!setState(IceProcessingState.COMPLETED)) return; // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) if (stunKeepAliveThread == null && !StackProperties.getBoolean( StackProperties.NO_KEEP_ALIVES, false)) { // schedule STUN checks for selected candidates scheduleStunKeepAlive(); } scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void cancel() { cancel(false); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void sendRequest() throws IllegalArgumentException, IOException { logger.fine( "sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); this.retransmitter.schedule(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); // cancel termination timer in case agent is freed // before termination timer is triggered synchronized (terminationFutureSyncRoot) { if (terminationFuture != null) { terminationFuture.cancel(true); terminationFuture = null; } } //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if (getState().isEstablished()) { return; } List<IceMediaStream> streams = getStreams(); for (IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if (checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if (checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if (!allListsEnded) { return; } if (!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( if (logger.isLoggable(Level.INFO)) { if (connCheckClient.isAlive() || connCheckServer.isAlive()) { logger.info("Suspicious ICE connectivity failure. Checks" + " failed but the remote end was able to reach us."); } logger.info("ICE state is FAILED"); } terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if (getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } // The race condition in which another thread enters COMPLETED right // under our nose here has been observed (and not in a single instance) // So check that we did indeed just trigger the change. if (!setState(IceProcessingState.COMPLETED)) { return; } // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) if (stunKeepAliveThread == null && !StackProperties.getBoolean( StackProperties.NO_KEEP_ALIVES, false)) { // schedule STUN checks for selected candidates scheduleStunKeepAlive(); } scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); } #location 79 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if (getState().isEstablished()) { return; } List<IceMediaStream> streams = getStreams(); for (IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if (checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if (checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if (!allListsEnded) { return; } if (!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( if (logger.isLoggable(Level.INFO)) { if (connCheckClient.isAlive() || connCheckServer.isAlive()) { logger.info("Suspicious ICE connectivity failure. Checks" + " failed but the remote end was able to reach us."); } logger.info("ICE state is FAILED"); } terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if (getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } // The race condition in which another thread enters COMPLETED right // under our nose here has been observed (and not in a single instance) // So check that we did indeed just trigger the change. if (!setState(IceProcessingState.COMPLETED)) { return; } // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) scheduleStunKeepAlive(); scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void free() { synchronized (localCandidates) { /* * Since the sockets of the non-HostCandidate LocalCandidates may * depend on the socket of the HostCandidate for which they have * been harvested, order the freeing. */ CandidateType[] candidateTypes = new CandidateType[] { CandidateType.RELAYED_CANDIDATE, CandidateType.PEER_REFLEXIVE_CANDIDATE, CandidateType.SERVER_REFLEXIVE_CANDIDATE }; for (CandidateType candidateType : candidateTypes) { Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); if (candidateType.equals(localCandidate.getType())) { free(localCandidate); localCandidateIter.remove(); } } } // Free whatever's left. Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); free(localCandidate); localCandidateIter.remove(); } } getSocket().close(); } #location 48 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void free() { synchronized (localCandidates) { /* * Since the sockets of the non-HostCandidate LocalCandidates may * depend on the socket of the HostCandidate for which they have * been harvested, order the freeing. */ CandidateType[] candidateTypes = new CandidateType[] { CandidateType.RELAYED_CANDIDATE, CandidateType.PEER_REFLEXIVE_CANDIDATE, CandidateType.SERVER_REFLEXIVE_CANDIDATE }; for (CandidateType candidateType : candidateTypes) { Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); if (candidateType.equals(localCandidate.getType())) { free(localCandidate); localCandidateIter.remove(); } } } // Free whatever's left. Iterator<LocalCandidate> localCandidateIter = localCandidates.iterator(); while (localCandidateIter.hasNext()) { LocalCandidate localCandidate = localCandidateIter.next(); free(localCandidate); localCandidateIter.remove(); } } getComponentSocket().close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean equals(Object obj) throws NullPointerException { if(obj == this) return true; if( ! (obj instanceof Candidate)) return false; Candidate<?> targetCandidate = (Candidate<?>) obj; //compare candidate addresses if( ! targetCandidate.getTransportAddress() .equals(getTransportAddress())) return false; //compare bases if( getBase() == null ) { if (targetCandidate.getBase() != null) return false; } //compare other properties if(((getBase() == this && targetCandidate.getBase() == targetCandidate) || getBase().equals(targetCandidate.getBase())) && getPriority() == targetCandidate.getPriority() && getType() == targetCandidate.getType() && getFoundation().equals(targetCandidate.getFoundation())) { return true; } return false; } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean equals(Object obj) throws NullPointerException { if (obj == this) return true; if (! (obj instanceof Candidate)) return false; Candidate<?> candidate = (Candidate<?>) obj; //compare candidate addresses if (! candidate.getTransportAddress().equals(getTransportAddress())) return false; //compare bases Candidate<?> base = getBase(); Candidate<?> candidateBase = candidate.getBase(); boolean baseEqualsCandidateBase; if (base == null) { if (candidateBase != null) return false; else baseEqualsCandidateBase = true; } else { baseEqualsCandidateBase = base.equals(candidateBase); } //compare other properties return (baseEqualsCandidateBase || (base == this && candidateBase == candidate)) && getPriority() == candidate.getPriority() && getType() == candidate.getType() && getFoundation().equals(candidate.getFoundation()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void cancel(boolean waitForResponse) { // XXX The cancelled field is initialized to false and then the one and // only write access to it is here to set it to true. The rest of the // code just checks whether it has become true. Consequently, there // shouldn't be a problem if the set is outside a synchronized block. // However, it being outside a synchronized block will decrease the risk // of deadlocks. cancelled = true; if(!waitForResponse) { // Try to interrupt #waitFor(long) if possible. But don't risk a // deadlock. It is not a problem if it is not possible to interrupt // #waitFor(long) here because it will complete in finite time and // this StunClientTransaction will eventually notice that it has // been cancelled. if (lock.tryLock()) { try { lockCondition.signal(); } finally { lock.unlock(); } } } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void sendRequest() throws IllegalArgumentException, IOException { logger.fine( "sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); this.retransmitter.schedule(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); } #location 34 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); // cancel termination timer in case agent is freed // before termination timer is triggered synchronized (terminationFutureSyncRoot) { if (terminationFuture != null) { terminationFuture.cancel(true); terminationFuture = null; } } //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isOver() { return state == IceProcessingState.COMPLETED || state == IceProcessingState.TERMINATED || state == IceProcessingState.FAILED; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean isOver() { IceProcessingState state = getState(); return (state != null) && state.isOver(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendRequest() throws IllegalArgumentException, IOException { logger.fine( "sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); retransmissionThreadPool.execute(this); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void sendRequest() throws IllegalArgumentException, IOException { logger.fine( "sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); this.retransmitter.schedule(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { retransmissionsThread.setName("ice4j.ClientTransaction"); nextWaitInterval = originalWaitInterval; for (retransmissionCounter = 0; retransmissionCounter < maxRetransmissions; retransmissionCounter ++) { waitFor(nextWaitInterval); //did someone tell us to get lost? if(cancelled) return; if(nextWaitInterval < maxWaitInterval) nextWaitInterval *= 2; try { sendRequest0(); } catch (Exception ex) { //I wonder whether we should notify anyone that a retransmission //has failed logger.log(Level.WARNING, "A client tran retransmission failed", ex); } } //before stating that a transaction has timeout-ed we should first wait //for a reception of the response if(nextWaitInterval < maxWaitInterval) nextWaitInterval *= 2; waitFor(nextWaitInterval); responseCollector.processTimeout( new StunTimeoutEvent( this.request, getLocalAddress(), transactionID)); stackCallback.removeClientTransaction(this); } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { retransmissionsThread.setName("ice4j.ClientTransaction"); nextWaitInterval = originalWaitInterval; synchronized(this) { for (retransmissionCounter = 0; retransmissionCounter < maxRetransmissions; retransmissionCounter ++) { waitFor(nextWaitInterval); //did someone tell us to get lost? if(cancelled) return; if(nextWaitInterval < maxWaitInterval) nextWaitInterval *= 2; try { sendRequest0(); } catch (Exception ex) { //I wonder whether we should notify anyone that a //retransmission has failed logger.log(Level.INFO, "A client tran retransmission failed", ex); } } //before stating that a transaction has timeout-ed we should first //wait for a reception of the response if(nextWaitInterval < maxWaitInterval) nextWaitInterval *= 2; waitFor(nextWaitInterval); if(cancelled) return; stackCallback.removeClientTransaction(this); responseCollector.processTimeout( new StunTimeoutEvent( this.request, getLocalAddress(), transactionID)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void assertSigned(File outFolder, List<File> uApks) throws Exception { assertNotNull(outFolder); File[] outFiles = outFolder.listFiles(); assertNotNull(outFiles); assertEquals("should be same count of apks in out folder", uApks.size(), outFiles.length); for (File outFile : outFiles) { AndroidApkSignerVerify.Result verifyResult = new AndroidApkSignerVerify().verify(outFile, null, null, false); assertTrue(verifyResult.verified); assertEquals(0, verifyResult.warning); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private static void assertSigned(File outFolder, List<File> uApks) throws Exception { assertNotNull(outFolder); File[] outFiles = outFolder.listFiles(pathname -> FileUtil.getFileExtension(pathname).toLowerCase().equals("apk")); System.out.println("Found " + outFiles.length + " apks in out dir"); assertNotNull(outFiles); assertEquals("should be same count of apks in out folder", uApks.size(), outFiles.length); for (File outFile : outFiles) { AndroidApkSignerVerify.Result verifyResult = new AndroidApkSignerVerify().verify(outFile, null, null, false); assertTrue(verifyResult.verified); assertEquals(0, verifyResult.warning); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testResign() throws Exception { copyToTestPath(originalFolder, Collections.singletonList(singedApks.get(0))); File signedApk = originalFolder.listFiles()[0]; String cmd = "-" + CLIParser.ARG_APK_FILE + " " + signedApk.getAbsolutePath() + " -" + CLIParser.ARG_APK_OUT + " " + outFolder.getAbsolutePath() + " --skipZipAlign --allowResign --debug --ks " + testReleaseKs.getAbsolutePath() + " --ksPass " + ksPass + " --ksKeyPass " + keyPass + " --ksAlias " + ksAlias; System.out.println(cmd); SignTool.Result result = SignTool.mainExecute(CLIParserTest.asArgArray(cmd)); assertNotNull(result); assertEquals(0, result.unsuccessful); assertEquals(1, result.success); assertEquals(1, outFolder.listFiles().length); AndroidApkSignerVerify.Result verifyResult = new AndroidApkSignerVerify().verify(outFolder.listFiles()[0], null, null, false); assertTrue(verifyResult.verified); assertEquals(0, verifyResult.warnings.size()); assertEquals(0, verifyResult.errors.size()); assertEquals(releaseCertSha256, verifyResult.certInfoList.get(0).certSha256); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testResign() throws Exception { List<File> signedApks = copyToTestPath(originalFolder, Collections.singletonList(singedApks.get(0))); File signedApk = signedApks.get(0); String cmd = "-" + CLIParser.ARG_APK_FILE + " " + signedApk.getAbsolutePath() + " -" + CLIParser.ARG_APK_OUT + " " + outFolder.getAbsolutePath() + " --skipZipAlign --allowResign --debug --ks " + testReleaseKs.getAbsolutePath() + " --ksPass " + ksPass + " --ksKeyPass " + keyPass + " --ksAlias " + ksAlias; System.out.println(cmd); SignTool.Result result = SignTool.mainExecute(CLIParserTest.asArgArray(cmd)); assertNotNull(result); assertEquals(0, result.unsuccessful); assertEquals(1, result.success); assertEquals(1, outFolder.listFiles().length); AndroidApkSignerVerify.Result verifyResult = new AndroidApkSignerVerify().verify(outFolder.listFiles()[0], null, null, false); assertTrue(verifyResult.verified); assertEquals(0, verifyResult.warnings.size()); assertEquals(0, verifyResult.errors.size()); assertEquals(releaseCertSha256, verifyResult.certInfoList.get(0).certSha256); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Expression parseTildeExpression() { tokens.consume(TILDE); int major = intOf(tokens.consume(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new GreaterOrEqual(versionOf(major, 0, 0)); } tokens.consume(DOT); int minor = intOf(tokens.consume(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major + 1, 0, 0)) ); } tokens.consume(DOT); int patch = intOf(tokens.consume(NUMERIC).lexeme); return new And( new GreaterOrEqual(versionOf(major, minor, patch)), new Less(versionOf(major, minor + 1, 0)) ); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private Expression parseTildeExpression() { consumeNextToken(TILDE); int major = intOf(consumeNextToken(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new GreaterOrEqual(versionOf(major, 0, 0)); } consumeNextToken(DOT); int minor = intOf(consumeNextToken(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major + 1, 0, 0)) ); } consumeNextToken(DOT); int patch = intOf(consumeNextToken(NUMERIC).lexeme); return new And( new GreaterOrEqual(versionOf(major, minor, patch)), new Less(versionOf(major, minor + 1, 0)) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Expression parseVersionExpression() { int major = intOf(tokens.consume(NUMERIC).lexeme); tokens.consume(DOT); if (tokens.positiveLookahead(STAR)) { tokens.consume(); return new And( new GreaterOrEqual(versionOf(major, 0, 0)), new Less(versionOf(major + 1, 0, 0)) ); } int minor = intOf(tokens.consume(NUMERIC).lexeme); tokens.consume(DOT); tokens.consume(STAR); return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major, minor + 1, 0)) ); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private Expression parseVersionExpression() { int major = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); if (tokens.positiveLookahead(STAR)) { tokens.consume(); return new And( new GreaterOrEqual(versionOf(major, 0, 0)), new Less(versionOf(major + 1, 0, 0)) ); } int minor = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); consumeNextToken(STAR); return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major, minor + 1, 0)) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void checkForLeadingZeroes() { Character la1 = chars.lookahead(1); Character la2 = chars.lookahead(2); if (la1 == '0' && DIGIT.isMatchedBy(la2)) { throw new ParseException( "Numeric identifier MUST NOT contain leading zeroes" ); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private void checkForLeadingZeroes() { Character la1 = chars.lookahead(1); Character la2 = chars.lookahead(2); if (la1 != null && la1 == '0' && DIGIT.isMatchedBy(la2)) { throw new ParseException( "Numeric identifier MUST NOT contain leading zeroes" ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Expression parseTildeExpression() { tokens.consume(TILDE); int major = intOf(tokens.consume(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new GreaterOrEqual(versionOf(major, 0, 0)); } tokens.consume(DOT); int minor = intOf(tokens.consume(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major + 1, 0, 0)) ); } tokens.consume(DOT); int patch = intOf(tokens.consume(NUMERIC).lexeme); return new And( new GreaterOrEqual(versionOf(major, minor, patch)), new Less(versionOf(major, minor + 1, 0)) ); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code private Expression parseTildeExpression() { consumeNextToken(TILDE); int major = intOf(consumeNextToken(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new GreaterOrEqual(versionOf(major, 0, 0)); } consumeNextToken(DOT); int minor = intOf(consumeNextToken(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major + 1, 0, 0)) ); } consumeNextToken(DOT); int patch = intOf(consumeNextToken(NUMERIC).lexeme); return new And( new GreaterOrEqual(versionOf(major, minor, patch)), new Less(versionOf(major, minor + 1, 0)) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Version parseVersion() { int major = intOf(tokens.consume(NUMERIC).lexeme); int minor = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); minor = intOf(tokens.consume(NUMERIC).lexeme); } int patch = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); patch = intOf(tokens.consume(NUMERIC).lexeme); } return versionOf(major, minor, patch); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private Version parseVersion() { int major = intOf(consumeNextToken(NUMERIC).lexeme); int minor = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); minor = intOf(consumeNextToken(NUMERIC).lexeme); } int patch = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); patch = intOf(consumeNextToken(NUMERIC).lexeme); } return versionOf(major, minor, patch); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Version parseVersion() { int major = intOf(tokens.consume(NUMERIC).lexeme); int minor = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); minor = intOf(tokens.consume(NUMERIC).lexeme); } int patch = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); patch = intOf(tokens.consume(NUMERIC).lexeme); } return versionOf(major, minor, patch); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private Version parseVersion() { int major = intOf(consumeNextToken(NUMERIC).lexeme); int minor = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); minor = intOf(consumeNextToken(NUMERIC).lexeme); } int patch = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); patch = intOf(consumeNextToken(NUMERIC).lexeme); } return versionOf(major, minor, patch); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Expression parseVersionExpression() { int major = intOf(tokens.consume(NUMERIC).lexeme); tokens.consume(DOT); if (tokens.positiveLookahead(STAR)) { tokens.consume(); return new And( new GreaterOrEqual(versionOf(major, 0, 0)), new Less(versionOf(major + 1, 0, 0)) ); } int minor = intOf(tokens.consume(NUMERIC).lexeme); tokens.consume(DOT); tokens.consume(STAR); return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major, minor + 1, 0)) ); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private Expression parseVersionExpression() { int major = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); if (tokens.positiveLookahead(STAR)) { tokens.consume(); return new And( new GreaterOrEqual(versionOf(major, 0, 0)), new Less(versionOf(major + 1, 0, 0)) ); } int minor = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); consumeNextToken(STAR); return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major, minor + 1, 0)) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Version parseVersion() { int major = intOf(tokens.consume(NUMERIC).lexeme); int minor = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); minor = intOf(tokens.consume(NUMERIC).lexeme); } int patch = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); patch = intOf(tokens.consume(NUMERIC).lexeme); } return versionOf(major, minor, patch); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private Version parseVersion() { int major = intOf(consumeNextToken(NUMERIC).lexeme); int minor = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); minor = intOf(consumeNextToken(NUMERIC).lexeme); } int patch = 0; if (tokens.positiveLookahead(DOT)) { tokens.consume(); patch = intOf(consumeNextToken(NUMERIC).lexeme); } return versionOf(major, minor, patch); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Expression parseTildeExpression() { tokens.consume(TILDE); int major = intOf(tokens.consume(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new GreaterOrEqual(versionOf(major, 0, 0)); } tokens.consume(DOT); int minor = intOf(tokens.consume(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major + 1, 0, 0)) ); } tokens.consume(DOT); int patch = intOf(tokens.consume(NUMERIC).lexeme); return new And( new GreaterOrEqual(versionOf(major, minor, patch)), new Less(versionOf(major, minor + 1, 0)) ); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private Expression parseTildeExpression() { consumeNextToken(TILDE); int major = intOf(consumeNextToken(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new GreaterOrEqual(versionOf(major, 0, 0)); } consumeNextToken(DOT); int minor = intOf(consumeNextToken(NUMERIC).lexeme); if (!tokens.positiveLookahead(DOT)) { return new And( new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major + 1, 0, 0)) ); } consumeNextToken(DOT); int patch = intOf(consumeNextToken(NUMERIC).lexeme); return new And( new GreaterOrEqual(versionOf(major, minor, patch)), new Less(versionOf(major, minor + 1, 0)) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = { "/{uid}" }) public ModelAndView index(@PathVariable String uid, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView("report/chart"); try { ReportingPo po = reportingService.getByUid(uid); Map<String, Object> buildinParams = generationService.getBuildInParameters(request.getParameterMap(), po.getDataRange()); List<HtmlFormElement> formElements = generationService.getFormElements(po, buildinParams, 0); EasyUIQueryFormView formView = new EasyUIQueryFormView(); modelAndView.addObject("uid", uid); modelAndView.addObject("id", po.getId()); modelAndView.addObject("name", po.getName()); modelAndView.addObject("comment", po.getComment().trim()); modelAndView.addObject("formHtmlText", formView.getFormHtmlText(formElements)); } catch (QueryParamsException | TemplatePraseException ex) { modelAndView.addObject("message", ex.getMessage()); this.logException("查询参数生成失败", ex); } catch (Exception ex) { modelAndView.addObject("message", "查询参数生成失败!请联系管理员."); this.logException("查询参数生成失败", ex); } return modelAndView; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = { "/{uid}" }) public ModelAndView index(@PathVariable String uid, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView("report/chart"); try { ReportingUtils.previewByTemplate(uid, modelAndView, new EasyUIQueryFormView(), request); } catch (QueryParamsException | TemplatePraseException ex) { modelAndView.addObject("formHtmlText", ex.getMessage()); this.logException("查询参数生成失败", ex); } catch (Exception ex) { modelAndView.addObject("formHtmlText", "查询参数生成失败!请联系管理员."); this.logException("查询参数生成失败", ex); } return modelAndView; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } CipherParameters cipherParameters = null; if (isEncrypt) { cipherParameters = getCipherParameters(iv); try { encCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } encCipher.init(isEncrypt, cipherParameters); } else { _decryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); cipherParameters = getCipherParameters(iv); try { decCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } decCipher.init(isEncrypt, cipherParameters); } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } CipherParameters cipherParameters = null; if (isEncrypt) { cipherParameters = getCipherParameters(iv); try { encCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } encCipher.init(isEncrypt, cipherParameters); } else { _decryptIV = Arrays.copyOfRange(iv,0,_ivLength); cipherParameters = getCipherParameters(iv); try { decCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } decCipher.init(isEncrypt, cipherParameters); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } if (isEncrypt) { try { _encryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _encryptIV, 0, _ivLength); encCipher = getCipher(isEncrypt); ParametersWithIV parameterIV = new ParametersWithIV( new KeyParameter(_key.getEncoded()), _encryptIV); encCipher.init(isEncrypt, parameterIV); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } } else { try { _decryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); decCipher = getCipher(isEncrypt); ParametersWithIV parameterIV = new ParametersWithIV( new KeyParameter(_key.getEncoded()), _decryptIV); decCipher.init(isEncrypt, parameterIV); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } CipherParameters cipherParameters = null; if (isEncrypt) { cipherParameters = getCipherParameters(iv); try { encCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } encCipher.init(isEncrypt, cipherParameters); } else { _decryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); cipherParameters = getCipherParameters(iv); try { decCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } decCipher.init(isEncrypt, cipherParameters); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } if (isEncrypt) { try { _encryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _encryptIV, 0, _ivLength); encCipher = getCipher(isEncrypt); ParametersWithIV parameterIV = new ParametersWithIV( new KeyParameter(_key.getEncoded()), _encryptIV); encCipher.init(isEncrypt, parameterIV); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } } else { try { _decryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); decCipher = getCipher(isEncrypt); ParametersWithIV parameterIV = new ParametersWithIV( new KeyParameter(_key.getEncoded()), _decryptIV); decCipher.init(isEncrypt, parameterIV); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } } } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } CipherParameters cipherParameters = null; if (isEncrypt) { cipherParameters = getCipherParameters(iv); try { encCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } encCipher.init(isEncrypt, cipherParameters); } else { _decryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); cipherParameters = getCipherParameters(iv); try { decCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } decCipher.init(isEncrypt, cipherParameters); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String exec(String cmd) throws IOException { Process process = Runtime.getRuntime().exec(cmd); InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); try { String err = IOUtils.toString(errorStream, "UTF-8"); String out = IOUtils.toString(inputStream, "UTF-8"); return err + "\n" + out; } finally { inputStream.close(); errorStream.close(); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public static String exec(String cmd) throws IOException { CommandLine cmdLine = CommandLine.parse(cmd); DefaultExecutor executor = new DefaultExecutor(); // 防止抛出异常 executor.setExitValues(null); // 命令执行的超时时间 ExecuteWatchdog watchdog = new ExecuteWatchdog(600000); executor.setWatchdog(watchdog); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); return outputStream.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8")))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test @Ignore public void testCodec130() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Base64OutputStream base64os = new Base64OutputStream(bos); base64os.write(STRING_FIXTURE.getBytes()); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); Base64InputStream ins = new Base64InputStream(bis); // we skip the first character read from the reader ins.skip(1); StringBuffer sb = new StringBuffer(); int len = 0; byte[] bytes = new byte[10]; while ((len = ins.read(bytes)) != -1) { String s = new String(bytes, 0, len, "iso-8859-1"); sb.append(s); } String str = sb.toString(); assertEquals(STRING_FIXTURE.substring(1), str); } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Test @Ignore public void testCodec130() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Base64OutputStream base64os = new Base64OutputStream(bos); base64os.write(StringUtils.getBytesUtf8(STRING_FIXTURE)); base64os.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); Base64InputStream ins = new Base64InputStream(bis); // we skip the first character read from the reader ins.skip(1); byte[] decodedBytes = Base64TestData.streamToBytes(ins, new byte[64]); String str = StringUtils.newStringUtf8(decodedBytes); assertEquals(STRING_FIXTURE.substring(1), str); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(6, b64stream.skip(10)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(6, b64stream.skip(10)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); b64stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testBase64() { String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public void testBase64() { String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); Base64 b64 = new Base64(76, null); // null lineSeparator same as saying no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); // bogus characters to decode (to skip actually) byte[] decode = b64.decode("SGVsbG{}8gV29ybGQ="); String decodeString = StringUtils.newStringUtf8(decode); assertTrue("decode hello world", decodeString.equals("Hello World")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testDecodePadMarkerIndex3() { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes()))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes()))); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void testDecodePadMarkerIndex3() throws UnsupportedEncodingException { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes("UTF-8")))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes("UTF-8")))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testWriteOutOfBounds() throws Exception { byte[] buf = new byte[1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); Base64OutputStream out = new Base64OutputStream(bout); try { out.write(buf, -1, 0); fail("Expected Base64OutputStream.write(buf, -1, 0) to throw a IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ioobe) { // Expected } try { out.write(buf, buf.length + 1, 0); fail("Expected Base64OutputStream.write(buf, buf.length + 1, 0) to throw a IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ioobe) { // Expected } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public void testWriteOutOfBounds() throws Exception { byte[] buf = new byte[1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); Base64OutputStream out = new Base64OutputStream(bout); try { out.write(buf, -1, 1); fail("Expected Base64OutputStream.write(buf, -1, 1) to throw a IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ioobe) { // Expected } try { out.write(buf, 1, -1); fail("Expected Base64OutputStream.write(buf, 1, -1) to throw a IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ioobe) { // Expected } try { out.write(buf, buf.length + 1, 0); fail("Expected Base64OutputStream.write(buf, buf.length + 1, 0) to throw a IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ioobe) { // Expected } try { out.write(buf, buf.length - 1, 2); fail("Expected Base64OutputStream.write(buf, buf.length - 1, 2) to throw a IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ioobe) { // Expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test @Ignore public void testCodec130() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Base64OutputStream base64os = new Base64OutputStream(bos); base64os.write(STRING_FIXTURE.getBytes()); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); Base64InputStream ins = new Base64InputStream(bis); // we skip the first character read from the reader ins.skip(1); StringBuffer sb = new StringBuffer(); int len = 0; byte[] bytes = new byte[10]; while ((len = ins.read(bytes)) != -1) { String s = new String(bytes, 0, len, "iso-8859-1"); sb.append(s); } String str = sb.toString(); assertEquals(STRING_FIXTURE.substring(1), str); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test @Ignore public void testCodec130() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Base64OutputStream base64os = new Base64OutputStream(bos); base64os.write(StringUtils.getBytesUtf8(STRING_FIXTURE)); base64os.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); Base64InputStream ins = new Base64InputStream(bis); // we skip the first character read from the reader ins.skip(1); byte[] decodedBytes = Base64TestData.streamToBytes(ins, new byte[64]); String str = StringUtils.newStringUtf8(decodedBytes); assertEquals(STRING_FIXTURE.substring(1), str); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadOutOfBounds() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); byte[] buf = new byte[1024]; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(buf, -1, 0); fail("Expected Base32InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, 0, -1); fail("Expected Base32InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length + 1, 0); fail("Base32InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length - 1, 2); fail("Base32InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadOutOfBounds() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); byte[] buf = new byte[1024]; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(buf, -1, 0); fail("Expected Base32InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, 0, -1); fail("Expected Base32InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length + 1, 0); fail("Base32InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length - 1, 2); fail("Base32InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testKnownDecodings() { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64 .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(Charsets.UTF_8)))); assertEquals("http://jakarta.apache.org/commmons", new String(Base64 .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(Charsets.UTF_8)))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(Charsets.UTF_8)))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" .getBytes(Charsets.UTF_8)))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(Charsets.UTF_8)))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testKnownDecodings() { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(CHARSET_UTF8)))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64 .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(CHARSET_UTF8)))); assertEquals("http://jakarta.apache.org/commmons", new String(Base64 .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(CHARSET_UTF8)))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(CHARSET_UTF8)))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" .getBytes(CHARSET_UTF8)))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(CHARSET_UTF8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadNull() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(null, 0, 0); fail("Base32InputStream.read(null, 0, 0) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadNull() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(null, 0, 0); fail("Base32InputStream.read(null, 0, 0) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipNone() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); byte[] actualBytes = new byte[6]; assertEquals(0, b64stream.skip(0)); b64stream.read(actualBytes, 0, actualBytes.length); assertArrayEquals(actualBytes, new byte[] { 0, 0, 0, (byte) 255, (byte) 255, (byte) 255 }); // End of stream reached assertEquals(-1, b64stream.read()); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipNone() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); byte[] actualBytes = new byte[6]; assertEquals(0, b64stream.skip(0)); b64stream.read(actualBytes, 0, actualBytes.length); assertArrayEquals(actualBytes, new byte[] { 0, 0, 0, (byte) 255, (byte) 255, (byte) 255 }); // End of stream reached assertEquals(-1, b64stream.read()); b64stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCodec101() throws Exception { byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3); ByteArrayInputStream bais = new ByteArrayInputStream(codec101); Base64InputStream in = new Base64InputStream(bais); byte[] result = new byte[8192]; int c = in.read(result); assertTrue("Codec101: First read successful [c=" + c + "]", c > 0); c = in.read(result); assertTrue("Codec101: Second read should report end-of-stream [c=" + c + "]", c < 0); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCodec101() throws Exception { byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3); ByteArrayInputStream bais = new ByteArrayInputStream(codec101); Base64InputStream in = new Base64InputStream(bais); byte[] result = new byte[8192]; int c = in.read(result); assertTrue("Codec101: First read successful [c=" + c + "]", c > 0); c = in.read(result); assertTrue("Codec101: Second read should report end-of-stream [c=" + c + "]", c < 0); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes()))); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes("UTF-8")))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(6, b64stream.skip(6)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(6, b64stream.skip(6)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); b64stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEncodeAtzNotEmpty() throws EncoderException { BeiderMorseEncoder bmpm = new BeiderMorseEncoder(); bmpm.setNameType(NameType.GENERIC); bmpm.setRuleType(RuleType.APPROX); String[] names = { "ácz", "átz", "Ignácz", "Ignátz", "Ignác" }; for (String name : names) { Assert.assertFalse(bmpm.encode(name).equals("")); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEncodeAtzNotEmpty() throws EncoderException { BeiderMorseEncoder bmpm = new BeiderMorseEncoder(); bmpm.setNameType(NameType.GENERIC); bmpm.setRuleType(RuleType.APPROX); String[] names = { "ácz", "átz", "Ignácz", "Ignátz", "Ignác" }; for (String name : names) { assertNotEmpty(bmpm, name); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes("UTF-8")))); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(Charsets.UTF_8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipNone() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); byte[] actualBytes = new byte[6]; assertEquals(0, b32stream.skip(0)); b32stream.read(actualBytes, 0, actualBytes.length); assertArrayEquals(actualBytes, new byte[] { 102, 111, 111, 0, 0, 0 }); // End of stream reached assertEquals(-1, b32stream.read()); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipNone() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); byte[] actualBytes = new byte[6]; assertEquals(0, b32stream.skip(0)); b32stream.read(actualBytes, 0, actualBytes.length); assertArrayEquals(actualBytes, new byte[] { 102, 111, 111, 0, 0, 0 }); // End of stream reached assertEquals(-1, b32stream.read()); b32stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(8, b32stream.skip(10)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(3, b32stream.skip(10)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testInputStreamReader() throws Exception { byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3); ByteArrayInputStream bais = new ByteArrayInputStream(codec101); Base64InputStream in = new Base64InputStream(bais); InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); assertNotNull("Codec101: InputStreamReader works!", line); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testInputStreamReader() throws Exception { byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3); ByteArrayInputStream bais = new ByteArrayInputStream(codec101); Base64InputStream in = new Base64InputStream(bais); InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); assertNotNull("Codec101: InputStreamReader works!", line); br.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectEncode() throws Exception { Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes("UTF-8")))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectEncode() throws Exception { Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(Charsets.UTF_8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testKnownDecodings() throws UnsupportedEncodingException { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8")))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64 .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes("UTF-8")))); assertEquals("http://jakarta.apache.org/commmons", new String(Base64 .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes("UTF-8")))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes("UTF-8")))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" .getBytes("UTF-8")))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes("UTF-8")))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testKnownDecodings() throws UnsupportedEncodingException { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64 .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(Charsets.UTF_8)))); assertEquals("http://jakarta.apache.org/commmons", new String(Base64 .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(Charsets.UTF_8)))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(Charsets.UTF_8)))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" .getBytes(Charsets.UTF_8)))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(Charsets.UTF_8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectEncode() throws Exception { final Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(Charsets.UTF_8)))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectEncode() throws Exception { final Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(CHARSET_UTF8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(Charsets.UTF_8)))); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(CHARSET_UTF8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); assertEquals(8, b64stream.skip(8)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(6, b64stream.skip(6)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testDecodePadOnlyChunked() { assertTrue(Base64.decodeBase64("====\n".getBytes()).length == 0); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes()))); // Test truncated padding assertTrue(Base64.decodeBase64("===\n".getBytes()).length == 0); assertTrue(Base64.decodeBase64("==\n".getBytes()).length == 0); assertTrue(Base64.decodeBase64("=\n".getBytes()).length == 0); assertTrue(Base64.decodeBase64("\n".getBytes()).length == 0); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void testDecodePadOnlyChunked() throws UnsupportedEncodingException { assertTrue(Base64.decodeBase64("====\n".getBytes("UTF-8")).length == 0); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes("UTF-8")))); // Test truncated padding assertTrue(Base64.decodeBase64("===\n".getBytes("UTF-8")).length == 0); assertTrue(Base64.decodeBase64("==\n".getBytes("UTF-8")).length == 0); assertTrue(Base64.decodeBase64("=\n".getBytes("UTF-8")).length == 0); assertTrue(Base64.decodeBase64("\n".getBytes("UTF-8")).length == 0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWriteToNullCoverage() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Base64OutputStream out = new Base64OutputStream(bout); try { out.write(null, 0, 0); fail("Expcted Base64OutputStream.write(null) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWriteToNullCoverage() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Base64OutputStream out = new Base64OutputStream(bout); try { out.write(null, 0, 0); fail("Expcted Base64OutputStream.write(null) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } finally { out.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRead0() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); byte[] buf = new byte[1024]; int bytesRead = 0; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); bytesRead = in.read(buf, 0, 0); assertEquals("Base64InputStream.read(buf, 0, 0) returns 0", 0, bytesRead); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testRead0() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); byte[] buf = new byte[1024]; int bytesRead = 0; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); bytesRead = in.read(buf, 0, 0); assertEquals("Base64InputStream.read(buf, 0, 0) returns 0", 0, bytesRead); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadOnlyChunked() throws UnsupportedEncodingException { assertEquals(0, Base64.decodeBase64("====\n".getBytes("UTF-8")).length); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes("UTF-8")))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===\n".getBytes("UTF-8")).length); assertEquals(0, Base64.decodeBase64("==\n".getBytes("UTF-8")).length); assertEquals(0, Base64.decodeBase64("=\n".getBytes("UTF-8")).length); assertEquals(0, Base64.decodeBase64("\n".getBytes("UTF-8")).length); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadOnlyChunked() throws UnsupportedEncodingException { assertEquals(0, Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)).length); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("==\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("=\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("\n".getBytes(Charsets.UTF_8)).length); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadOnly() { assertEquals(0, Base64.decodeBase64("====".getBytes(Charsets.UTF_8)).length); assertEquals("", new String(Base64.decodeBase64("====".getBytes(Charsets.UTF_8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("==".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("=".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("".getBytes(Charsets.UTF_8)).length); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadOnly() { assertEquals(0, Base64.decodeBase64("====".getBytes(CHARSET_UTF8)).length); assertEquals("", new String(Base64.decodeBase64("====".getBytes(CHARSET_UTF8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("==".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("=".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("".getBytes(CHARSET_UTF8)).length); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(8, b32stream.skip(8)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(3, b32stream.skip(3)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMarkSupported() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); // Always returns false for now. assertFalse("Base32InputStream.markSupported() is false", in.markSupported()); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMarkSupported() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); // Always returns false for now. assertFalse("Base32InputStream.markSupported() is false", in.markSupported()); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAvailable() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); assertEquals(1, b64stream.available()); assertEquals(6, b64stream.skip(10)); // End of stream reached assertEquals(0, b64stream.available()); assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); assertEquals(0, b64stream.available()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAvailable() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); assertEquals(1, b64stream.available()); assertEquals(6, b64stream.skip(10)); // End of stream reached assertEquals(0, b64stream.available()); assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); assertEquals(0, b64stream.available()); b64stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadOnlyChunked() { assertEquals(0, Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)).length); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("==\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("=\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("\n".getBytes(Charsets.UTF_8)).length); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadOnlyChunked() { assertEquals(0, Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8)).length); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("==\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("=\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("\n".getBytes(CHARSET_UTF8)).length); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBase64() { String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); Base64 b64 = new Base64(BaseNCodec.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); // bogus characters to decode (to skip actually) {e-acute*6} byte[] decode = b64.decode("SGVsbG{\u00e9\u00e9\u00e9\u00e9\u00e9\u00e9}8gV29ybGQ="); String decodeString = StringUtils.newStringUtf8(decode); assertTrue("decode hello world", decodeString.equals("Hello World")); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testBase64() { String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); Base64 b64 = new Base64(BaseNCodec.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); // bogus characters to decode (to skip actually) {e-acute*6} byte[] decode = b64.decode("SGVsbG{\u00e9\u00e9\u00e9\u00e9\u00e9\u00e9}8gV29ybGQ="); String decodeString = StringUtils.newStringUtf8(decode); assertEquals("decode hello world", "Hello World", decodeString); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testKnownDecodings() { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes()))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64 .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes()))); assertEquals("http://jakarta.apache.org/commmons", new String(Base64 .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes()))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes()))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" .getBytes()))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes()))); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void testKnownDecodings() throws UnsupportedEncodingException { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8")))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64 .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes("UTF-8")))); assertEquals("http://jakarta.apache.org/commmons", new String(Base64 .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes("UTF-8")))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes("UTF-8")))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" .getBytes("UTF-8")))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes("UTF-8")))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRead0() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); byte[] buf = new byte[1024]; int bytesRead = 0; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); bytesRead = in.read(buf, 0, 0); assertEquals("Base32InputStream.read(buf, 0, 0) returns 0", 0, bytesRead); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testRead0() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); byte[] buf = new byte[1024]; int bytesRead = 0; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); bytesRead = in.read(buf, 0, 0); assertEquals("Base32InputStream.read(buf, 0, 0) returns 0", 0, bytesRead); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadMarkerIndex3() { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes(Charsets.UTF_8)))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes(Charsets.UTF_8)))); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadMarkerIndex3() { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes(CHARSET_UTF8)))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes(CHARSET_UTF8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWriteToNullCoverage() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Base32OutputStream out = new Base32OutputStream(bout); try { out.write(null, 0, 0); fail("Expcted Base32OutputStream.write(null) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWriteToNullCoverage() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Base32OutputStream out = new Base32OutputStream(bout); try { out.write(null, 0, 0); fail("Expcted Base32OutputStream.write(null) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } out.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(3, b32stream.skip(3)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipToEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(3, b32stream.skip(3)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); b32stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testDecodePadOnly() { assertTrue(Base64.decodeBase64("====".getBytes()).length == 0); assertEquals("", new String(Base64.decodeBase64("====".getBytes()))); // Test truncated padding assertTrue(Base64.decodeBase64("===".getBytes()).length == 0); assertTrue(Base64.decodeBase64("==".getBytes()).length == 0); assertTrue(Base64.decodeBase64("=".getBytes()).length == 0); assertTrue(Base64.decodeBase64("".getBytes()).length == 0); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void testDecodePadOnly() throws UnsupportedEncodingException { assertTrue(Base64.decodeBase64("====".getBytes("UTF-8")).length == 0); assertEquals("", new String(Base64.decodeBase64("====".getBytes("UTF-8")))); // Test truncated padding assertTrue(Base64.decodeBase64("===".getBytes("UTF-8")).length == 0); assertTrue(Base64.decodeBase64("==".getBytes("UTF-8")).length == 0); assertTrue(Base64.decodeBase64("=".getBytes("UTF-8")).length == 0); assertTrue(Base64.decodeBase64("".getBytes("UTF-8")).length == 0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadOnly() throws UnsupportedEncodingException { assertEquals(0, Base64.decodeBase64("====".getBytes("UTF-8")).length); assertEquals("", new String(Base64.decodeBase64("====".getBytes("UTF-8")))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===".getBytes("UTF-8")).length); assertEquals(0, Base64.decodeBase64("==".getBytes("UTF-8")).length); assertEquals(0, Base64.decodeBase64("=".getBytes("UTF-8")).length); assertEquals(0, Base64.decodeBase64("".getBytes("UTF-8")).length); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadOnly() throws UnsupportedEncodingException { assertEquals(0, Base64.decodeBase64("====".getBytes(Charsets.UTF_8)).length); assertEquals("", new String(Base64.decodeBase64("====".getBytes(Charsets.UTF_8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("==".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("=".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("".getBytes(Charsets.UTF_8)).length); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); assertEquals(8, b64stream.skip(10)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(6, b64stream.skip(10)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes()))); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8")))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadNull() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(null, 0, 0); fail("Base64InputStream.read(null, 0, 0) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadNull() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(null, 0, 0); fail("Base64InputStream.read(null, 0, 0) to throw a NullPointerException"); } catch (NullPointerException e) { // Expected } in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testKnownEncodings() { assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64 .encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes(Charsets.UTF_8)))); assertEquals( "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", new String( Base64 .encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" .getBytes(Charsets.UTF_8)))); assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64 .encodeBase64("It was the best of times, it was the worst of times.".getBytes(Charsets.UTF_8)))); assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64 .encodeBase64("http://jakarta.apache.org/commmons".getBytes(Charsets.UTF_8)))); assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64 .encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes(Charsets.UTF_8)))); assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }" .getBytes(Charsets.UTF_8)))); assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes(Charsets.UTF_8)))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testKnownEncodings() { assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64 .encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes(CHARSET_UTF8)))); assertEquals( "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", new String( Base64 .encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" .getBytes(CHARSET_UTF8)))); assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64 .encodeBase64("It was the best of times, it was the worst of times.".getBytes(CHARSET_UTF8)))); assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64 .encodeBase64("http://jakarta.apache.org/commmons".getBytes(CHARSET_UTF8)))); assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64 .encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes(CHARSET_UTF8)))); assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }" .getBytes(CHARSET_UTF8)))); assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes(CHARSET_UTF8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadOutOfBounds() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); byte[] buf = new byte[1024]; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(buf, -1, 0); fail("Expected Base64InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, 0, -1); fail("Expected Base64InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length + 1, 0); fail("Base64InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length - 1, 2); fail("Base64InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadOutOfBounds() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); byte[] buf = new byte[1024]; ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); try { in.read(buf, -1, 0); fail("Expected Base64InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, 0, -1); fail("Expected Base64InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length + 1, 0); fail("Base64InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } try { in.read(buf, buf.length - 1, 2); fail("Base64InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected } in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(CHARSET_UTF8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipBig() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); assertEquals(6, b64stream.skip(Integer.MAX_VALUE)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipBig() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); assertEquals(6, b64stream.skip(Integer.MAX_VALUE)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); b64stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipBig() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(3, b32stream.skip(1024)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipBig() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(3, b32stream.skip(1024)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); b32stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMarkSupported() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); // Always returns false for now. assertFalse("Base64InputStream.markSupported() is false", in.markSupported()); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMarkSupported() throws Exception { byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); ByteArrayInputStream bin = new ByteArrayInputStream(decoded); Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); // Always returns false for now. assertFalse("Base64InputStream.markSupported() is false", in.markSupported()); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodePadMarkerIndex3() throws UnsupportedEncodingException { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes("UTF-8")))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes("UTF-8")))); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodePadMarkerIndex3() throws UnsupportedEncodingException { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes(Charsets.UTF_8)))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes(Charsets.UTF_8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testKnownEncodings() throws UnsupportedEncodingException { assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64 .encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes("UTF-8")))); assertEquals( "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", new String( Base64 .encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" .getBytes("UTF-8")))); assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64 .encodeBase64("It was the best of times, it was the worst of times.".getBytes("UTF-8")))); assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64 .encodeBase64("http://jakarta.apache.org/commmons".getBytes("UTF-8")))); assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64 .encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes("UTF-8")))); assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }" .getBytes("UTF-8")))); assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes("UTF-8")))); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testKnownEncodings() throws UnsupportedEncodingException { assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64 .encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes(Charsets.UTF_8)))); assertEquals( "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", new String( Base64 .encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" .getBytes(Charsets.UTF_8)))); assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64 .encodeBase64("It was the best of times, it was the worst of times.".getBytes(Charsets.UTF_8)))); assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64 .encodeBase64("http://jakarta.apache.org/commmons".getBytes(Charsets.UTF_8)))); assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64 .encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes(Charsets.UTF_8)))); assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }" .getBytes(Charsets.UTF_8)))); assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes(Charsets.UTF_8)))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testBase64() { String content = "Hello World"; String encodedContent; encodedContent = new String(Base64.encodeBase64(content.getBytes())); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public void testBase64() { String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAvailable() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(1, b32stream.available()); assertEquals(3, b32stream.skip(10)); // End of stream reached assertEquals(0, b32stream.available()); assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); assertEquals(0, b32stream.available()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAvailable() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(1, b32stream.available()); assertEquals(3, b32stream.skip(10)); // End of stream reached assertEquals(0, b32stream.available()); assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); assertEquals(0, b32stream.available()); b32stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(3, b32stream.skip(10)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); // due to CODEC-130, skip now skips correctly decoded characters rather than encoded assertEquals(3, b32stream.skip(10)); // End of stream reached assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); b32stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void bind() { if (bound) throw new IllegalStateException("Already bound to " + assignedThread); bound = true; assignedThread = Thread.currentThread(); AffinitySupport.setAffinity(1L << id); if (LOGGER.isLoggable(Level.INFO)) LOGGER.info("Assigning cpu " + id + " to " + assignedThread); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void bind() { bind(false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static VanillaCpuLayout fromProperties(String fileName) throws IOException { return fromProperties(new FileInputStream(fileName)); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public static VanillaCpuLayout fromProperties(String fileName) throws IOException { return fromProperties(openFile(fileName)); }
Below is the vulnerable code, please generate the patch based on the following information.