output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void receive(DatagramPacket p) throws IOException { final Lock receiveLock = receiveCloseLock.readLock(); receiveLock.lock(); try { super.receive(p); } finally { receiveLock.unlock(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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"); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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."); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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"); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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"); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void sendRequest() throws IllegalArgumentException, IOException { logger.fine( "sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); this.retransmitter.schedule(); }
#vulnerable code void cancel() { cancel(false); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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"); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void sendRequest() throws IllegalArgumentException, IOException { logger.fine( "sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); this.retransmitter.schedule(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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"); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isOver() { IceProcessingState state = getState(); return (state != null) && state.isOver(); }
#vulnerable code public boolean isOver() { return state == IceProcessingState.COMPLETED || state == IceProcessingState.TERMINATED || state == IceProcessingState.FAILED; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void sendRequest() throws IllegalArgumentException, IOException { logger.fine( "sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); this.retransmitter.schedule(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)) ); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)) ); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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" ); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)) ); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)) ); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)) ); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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")); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(Charsets.UTF_8)))); }
#vulnerable code @Test public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes("UTF-8")))); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testObjectEncode() throws Exception { Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(Charsets.UTF_8)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testObjectEncode() throws Exception { final Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(CHARSET_UTF8)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(CHARSET_UTF8)))); }
#vulnerable code @Test public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(Charsets.UTF_8)))); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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")))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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")))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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)))); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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=")); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void bind() { bind(false); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static VanillaCpuLayout fromProperties(String fileName) throws IOException { return fromProperties(openFile(fileName)); }
#vulnerable code public static VanillaCpuLayout fromProperties(String fileName) throws IOException { return fromProperties(new FileInputStream(fileName)); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void bind() { bind(false); }
#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 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void bind() { bind(false); }
#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 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void bind(boolean wholeCore) { if (bound && assignedThread != null && assignedThread.isAlive()) throw new IllegalStateException("cpu " + id + " already bound to " + assignedThread); if (wholeCore) { int core = coreForId(id); for (AffinityLock al : CORES.get(core)) { if (bound && al.assignedThread != null && al.assignedThread.isAlive()) { LOGGER.severe("cpu " + al.id + " already bound to " + al.assignedThread); } else { al.bound = true; al.assignedThread = Thread.currentThread(); } } if (LOGGER.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder().append("Assigning core ").append(core); String sep = ": cpus "; for (AffinityLock al : CORES.get(core)) { sb.append(sep).append(al.id); sep = ", "; } sb.append(" to ").append(assignedThread); LOGGER.info(sb.toString()); } } else { bound = true; assignedThread = Thread.currentThread(); if (LOGGER.isLoggable(Level.INFO)) LOGGER.info("Assigning cpu " + id + " to " + assignedThread); } AffinitySupport.setAffinity(1L << id); }
#vulnerable code public void bind(boolean wholeCore) { if (bound && assignedThread != null && assignedThread.isAlive()) throw new IllegalStateException("cpu " + id + " already bound to " + assignedThread); if (wholeCore) { int core = coreForId(id); for (AffinityLock al : CORES[core]) { if (bound && al.assignedThread != null && al.assignedThread.isAlive()) { LOGGER.severe("cpu " + al.id + " already bound to " + al.assignedThread); } else { al.bound = true; al.assignedThread = Thread.currentThread(); } } if (LOGGER.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder().append("Assigning core ").append(core); String sep = ": cpus "; for (AffinityLock al : CORES[core]) { sb.append(sep).append(al.id); sep = ", "; } sb.append(" to ").append(assignedThread); LOGGER.info(sb.toString()); } } else { bound = true; assignedThread = Thread.currentThread(); if (LOGGER.isLoggable(Level.INFO)) LOGGER.info("Assigning cpu " + id + " to " + assignedThread); } AffinitySupport.setAffinity(1L << id); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { synchronized (Runtime.getRuntime()) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } }
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testAnalyzer() { ExpressionCompiler compiler = new ExpressionCompiler("order.id == 10"); compiler.compile(); for (String input : compiler.getParserContextState().getInputs().keySet()) { System.out.println("input>" + input); } assertEquals(1, compiler.getParserContextState().getInputs().size()); assertTrue(compiler.getParserContextState().getInputs().containsKey("order")); }
#vulnerable code public void testAnalyzer() { ExpressionCompiler compiler = new ExpressionCompiler("order.id == 10"); compiler.compile(); for (String input : compiler.getInputs()) { System.out.println("input>" + input); } assertEquals(1, compiler.getInputs().size()); assertTrue(compiler.getInputs().contains("order")); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Object getCollectionProperty(Object ctx, String prop) throws Exception { if (prop.length() != 0) { ctx = getBeanProperty(ctx, prop); } int start = ++cursor; whiteSpaceSkip(); if (cursor == length || scanTo(']')) throw new PropertyAccessException("unterminated '['"); prop = new String(property, start, cursor++ - start); if (ctx instanceof Map) { return ((Map) ctx).get(eval(prop, ctx, variableFactory)); } else if (ctx instanceof List) { return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory)); } else if (ctx instanceof Collection) { int count = (Integer) eval(prop, ctx, variableFactory); if (count > ((Collection) ctx).size()) throw new PropertyAccessException("index [" + count + "] out of bounds on collections"); Iterator iter = ((Collection) ctx).iterator(); for (int i = 0; i < count; i++) iter.next(); return iter.next(); } else if (ctx.getClass().isArray()) { return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory)); } else if (ctx instanceof CharSequence) { return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory)); } else { throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName())); } }
#vulnerable code private Object getCollectionProperty(Object ctx, String prop) throws Exception { if (prop.length() != 0) { ctx = getBeanProperty(ctx, prop); } int start = ++cursor; whiteSpaceSkip(); if (cursor == length) throw new PropertyAccessException("unterminated '['"); Object item; if (scanTo(']')) throw new PropertyAccessException("unterminated '['"); // String ex = new String(property, start, cursor++ - start); item = eval(new String(property, start, cursor++ - start), ctx, variableFactory); if (ctx instanceof Map) { return ((Map) ctx).get(item); } else if (ctx instanceof List) { return ((List) ctx).get((Integer) item); } else if (ctx instanceof Collection) { int count = (Integer) item; if (count > ((Collection) ctx).size()) throw new PropertyAccessException("index [" + count + "] out of bounds on collections"); Iterator iter = ((Collection) ctx).iterator(); for (int i = 0; i < count; i++) iter.next(); return iter.next(); } else if (ctx.getClass().isArray()) { return Array.get(ctx, (Integer) item); } else if (ctx instanceof CharSequence) { return ((CharSequence) ctx).charAt((Integer) item); } else { throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName())); } } #location 37 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (CACHE_DISABLE || !cacheAggressively) { char[] seg = new char[expression.length - 3]; // arraycopy(expression, 2, seg, 0, seg.length); for (int i = 0; i < seg.length; i++) seg[i] = expression[i + 2]; return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { if (tokens == null) { tokens = new HashMap(); } ForeachContext foreachContext; String[] names; String[] aliases; if (!(localStack.peek() instanceof ForeachContext)) { // create a clone of the context foreachContext = ((ForeachContext) currNode.getRegister()).clone(); names = foreachContext.getNames(); aliases = foreachContext.getAliases(); try { Iterator[] iters = new Iterator[names.length]; for (int i = 0; i < names.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(names[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); // this throws null pointer exception in thread race } // set the newly created iterators into the context foreachContext.setIterators(iters); // push the context onto the local stack. localStack.push(foreachContext); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)), e); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)), e); } } else { foreachContext = (ForeachContext) localStack.peek(); // names = foreachContext.getNames(); aliases = foreachContext.getAliases(); } Iterator[] iters = foreachContext.getItererators(); if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(aliases[i], iters[i].next()); } int c; tokens.put("i0", c = foreachContext.getCount()); if (c != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked foreachContext.incrementCount(); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(aliases[i]); } // foreachContext.setIterators(null); // foreachContext.setCount(0); localStack.pop(); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } }
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (CACHE_DISABLE || !cacheAggressively) { char[] seg = new char[expression.length - 3]; // arraycopy(expression, 2, seg, 0, seg.length); for (int i = 0; i < seg.length; i++) seg[i] = expression[i + 2]; return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { if (tokens == null) { tokens = new HashMap(); } ForeachContext foreachContext; if (!(localStack.peek() instanceof ForeachContext)) { foreachContext = ((ForeachContext) currNode.getRegister()).clone(); // if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); localStack.push(foreachContext); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } foreachContext = (ForeachContext) localStack.peek(); Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); localStack.pop(); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 119 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked // return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens); if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s)); return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { ExpressionParser oParser = new ExpressionParser(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = ( ForeachContext ) currNode.getRegister(); if ( foreachContext.getItererators() == null ) { try { String[] lists = getForEachSegment(currNode).split( "," ); Iterator[] iters = new Iterator[lists.length]; for( int i = 0; i < lists.length; i++ ) { Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse(); if ( listObject instanceof Object[]) { listObject = Arrays.asList( (Object[]) listObject ); } iters[i] = ((Collection)listObject).iterator() ; } foreachContext.setIterators( iters ); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split( "," ); // must trim vars for ( int i = 0; i < alias.length; i++ ) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for ( int i = 0; i < iters.length; i++ ) { tokens.put(alias[i], iters[i].next()); } if ( foreachContext.getCount() != 0 ) { sbuf.append( foreachContext.getSeperator() ); } foreachContext.setCount( foreachContext.getCount( ) + 1 ); } else { for ( int i = 0; i < iters.length; i++ ) { tokens.remove(alias[i]); } foreachContext.setIterators( null ); foreachContext.setCount( 0 ); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length == 2) { return register; } else { return sbuf.toString(); } } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } }
#vulnerable code public Object execute(Object ctx, Map tokens) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked // return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens); if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s)); return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { ExpressionParser oParser = new ExpressionParser(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { String seperator = ""; if (currNode.getRegister() == null || currNode.getRegister() instanceof String) { try { String props = ( String) currNode.getRegister(); if ( props != null && props.length() > 0 ) { seperator = props; } String[] lists = getForEachSegment(currNode).split( "," ); Iterator[] iters = new Iterator[lists.length]; for( int i = 0; i < lists.length; i++ ) { Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse(); if ( listObject instanceof Object[]) { listObject = Arrays.asList( (Object[]) listObject ); } iters[i] = ((Collection)listObject).iterator() ; } currNode.setRegister( iters ); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = (Iterator[]) currNode.getRegister(); String[] alias = currNode.getAlias().split( "," ); // must trim vars for ( int i = 0; i < alias.length; i++ ) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for ( int i = 0; i < iters.length; i++ ) { tokens.put(alias[i], iters[i].next()); } sbuf.append( seperator ); } else { for ( int i = 0; i < iters.length; i++ ) { tokens.remove(alias[i]); } exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length == 2) { return register; } else { return sbuf.toString(); } } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 103 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void setExpression(String expression) { if (expression != null && !"".equals(expression)) { synchronized (EX_PRECACHE) { if ((this.expr = EX_PRECACHE.get(expression)) == null) { length = (this.expr = expression.toCharArray()).length; // trim any whitespace. while (length != 0 && isWhitespace(this.expr[length - 1])) length--; char[] e = new char[length]; for (int i = 0; i != e.length; i++) e[i] = expr[i]; EX_PRECACHE.put(expression, e); } else { length = this.expr.length; } } } }
#vulnerable code protected void setExpression(String expression) { if (expression != null && !"".equals(expression)) { if ((this.expr = EX_PRECACHE.get(expression)) == null) { synchronized (EX_PRECACHE) { length = (this.expr = expression.toCharArray()).length; // trim any whitespace. while (length != 0 && isWhitespace(this.expr[length - 1])) length--; char[] e = new char[length]; for (int i = 0; i != e.length; i++) e[i] = expr[i]; EX_PRECACHE.put(expression, e); } } else { length = this.expr.length; } } } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked // return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens); if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s)); return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { ExpressionParser oParser = new ExpressionParser(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = ( ForeachContext ) currNode.getRegister(); if ( foreachContext.getItererators() == null ) { try { String[] lists = getForEachSegment(currNode).split( "," ); Iterator[] iters = new Iterator[lists.length]; for( int i = 0; i < lists.length; i++ ) { Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse(); if ( listObject instanceof Object[]) { listObject = Arrays.asList( (Object[]) listObject ); } iters[i] = ((Collection)listObject).iterator() ; } foreachContext.setIterators( iters ); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split( "," ); // must trim vars for ( int i = 0; i < alias.length; i++ ) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for ( int i = 0; i < iters.length; i++ ) { tokens.put(alias[i], iters[i].next()); } if ( foreachContext.getCount() != 0 ) { sbuf.append( foreachContext.getSeperator() ); } foreachContext.setCount( foreachContext.getCount( ) + 1 ); } else { for ( int i = 0; i < iters.length; i++ ) { tokens.remove(alias[i]); } foreachContext.setIterators( null ); foreachContext.setCount( 0 ); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length == 2) { return register; } else { return sbuf.toString(); } } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } }
#vulnerable code public Object execute(Object ctx, Map tokens) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked // return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens); if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s)); return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { ExpressionParser oParser = new ExpressionParser(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { String seperator = ""; if (currNode.getRegister() == null || currNode.getRegister() instanceof String) { try { String props = ( String) currNode.getRegister(); if ( props != null && props.length() > 0 ) { seperator = props; } String[] lists = getForEachSegment(currNode).split( "," ); Iterator[] iters = new Iterator[lists.length]; for( int i = 0; i < lists.length; i++ ) { Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse(); if ( listObject instanceof Object[]) { listObject = Arrays.asList( (Object[]) listObject ); } iters[i] = ((Collection)listObject).iterator() ; } currNode.setRegister( iters ); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = (Iterator[]) currNode.getRegister(); String[] alias = currNode.getAlias().split( "," ); // must trim vars for ( int i = 0; i < alias.length; i++ ) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for ( int i = 0; i < iters.length; i++ ) { tokens.put(alias[i], iters[i].next()); } sbuf.append( seperator ); } else { for ( int i = 0; i < iters.length; i++ ) { tokens.remove(alias[i]); } exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length == 2) { return register; } else { return sbuf.toString(); } } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 93 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testVarInputs() { ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;"); CompiledExpression c = compiler.compile(); ParserContext pCtx = compiler.getParserContextState(); assertEquals(4, pCtx.getInputs().size()); assertTrue(pCtx.getInputs().containsKey("test")); assertTrue(pCtx.getInputs().containsKey("foo")); assertTrue(pCtx.getInputs().containsKey("bo")); assertTrue(pCtx.getInputs().containsKey("trouble")); assertEquals(2, pCtx.getVariables().size()); assertTrue(pCtx.getVariables().containsKey("bleh")); assertTrue(pCtx.getVariables().containsKey("twa")); assertEquals(String.class, DebugTools.determineType("bleh", c)); }
#vulnerable code public void testVarInputs() { ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;"); CompiledExpression c = compiler.compile(); assertEquals(4, compiler.getInputs().size()); assertTrue(compiler.getInputs().contains("test")); assertTrue(compiler.getInputs().contains("foo")); assertTrue(compiler.getInputs().contains("bo")); assertTrue(compiler.getInputs().contains("trouble")); assertEquals(2, compiler.getLocals().size()); assertTrue(compiler.getLocals().contains("bleh")); assertTrue(compiler.getLocals().contains("twa")); assertEquals(String.class, DebugTools.determineType("bleh", c)); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { synchronized (Runtime.getRuntime()) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } }
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 122 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String readInFile(String fileName) { File file = new File(String.valueOf(peek()) + "/" + fileName); try { // FileChannel fc = new FileInputStream(file).getChannel(); FileInputStream instream = new FileInputStream(file); BufferedInputStream bufstream = new BufferedInputStream(instream); push(file.getParent()); byte[] buf = new byte[10]; int read; int i; StringAppender appender = new StringAppender(); while ((read = bufstream.read(buf)) != -1) { for (i = 0; i < read; i++) { appender.append((char) buf[i]); } } bufstream.close(); instream.close(); // ByteBuffer buf = allocateDirect(10); // // StringAppender appender = new StringAppender(); // int read; // // while (true) { // buf.rewind(); // if ((read = fc.read(buf)) != -1) { // buf.rewind(); // for (; read != 0; read--) { // appender.append((char) buf.get()); // } // } // else { // break; // } // } pop(); return appender.toString(); } catch (FileNotFoundException e) { throw new TemplateError("cannot include template '" + fileName + "': file not found."); } catch (IOException e) { throw new TemplateError("unknown I/O exception while including '" + fileName + "' (stacktrace nested)", e); } }
#vulnerable code public static String readInFile(String fileName) { File file = new File(String.valueOf(peek()) + "/" + fileName); try { FileChannel fc = new FileInputStream(file).getChannel(); push(file.getParent()); ByteBuffer buf = allocateDirect(10); StringAppender appender = new StringAppender(); int read; while (true) { buf.rewind(); if ((read = fc.read(buf)) != -1) { buf.rewind(); for (; read != 0; read--) { appender.append((char) buf.get()); } } else { break; } } pop(); return appender.toString(); } catch (FileNotFoundException e) { throw new TemplateError("cannot include template '" + fileName + "': file not found."); } catch (IOException e) { throw new TemplateError("unknown I/O exception while including '" + fileName + "' (stacktrace nested)", e); } } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { synchronized (Runtime.getRuntime()) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } }
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 110 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings({"unchecked"}) private Object getMethod(Object ctx, String name) throws Exception { int st = cursor; String tk = cursor != length && expr[cursor] == '(' && ((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ? new String(expr, st + 1, cursor - st - 1) : ""; cursor++; Object[] args; Accessor[] es; if (tk.length() == 0) { args = ParseTools.EMPTY_OBJ_ARR; es = null; } else { String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1); es = new ExecutableStatement[subtokens.length]; args = new Object[subtokens.length]; for (int i = 0; i < subtokens.length; i++) { args[i] = (es[i] = (ExecutableStatement) subCompileExpression(subtokens[i].toCharArray())) .getValue(this.ctx, thisRef, variableFactory); } } if (first && variableFactory != null && variableFactory.isResolveable(name)) { Object ptr = variableFactory.getVariableResolver(name).getValue(); if (ptr instanceof Method) { ctx = ((Method) ptr).getDeclaringClass(); name = ((Method) ptr).getName(); } else if (ptr instanceof MethodStub) { ctx = ((MethodStub) ptr).getClassReference(); name = ((MethodStub) ptr).getMethodName(); } else if (ptr instanceof Function) { addAccessorNode(new FunctionAccessor((Function) ptr, es)); Object[] parm = null; if (es != null) { parm = new Object[es.length]; for (int i = 0; i < es.length; i++) { parm[i] = es[i].getValue(ctx, thisRef, variableFactory); } } return ((Function) ptr).call(ctx, thisRef, variableFactory, parm); } else { throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: " + name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")"); } first = false; } if (ctx == null) throw new PropertyAccessException("unable to access property (null parent): " + name); /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class<?> cls = ctx instanceof Class ? (Class<?>) ctx : ctx.getClass(); Method m; Class[] parameterTypes = null; /** * If we have not cached the method then we need to go ahead and try to resolve it. */ /** * Try to find an instance method from the class target. */ if ((m = getBestCandidate(args, name, cls, cls.getMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = getBestCandidate(args, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } } if (m == null) { StringAppender errorBuild = new StringAppender(); for (int i = 0; i < args.length; i++) { errorBuild.append(args[i] != null ? args[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } if ("size".equals(name) && args.length == 0 && cls.isArray()) { addAccessorNode(new ArrayLength()); return getLength(ctx); } throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { if (es != null) { ExecutableStatement cExpr; for (int i = 0; i < es.length; i++) { cExpr = (ExecutableStatement) es[i]; if (cExpr.getKnownIngressType() == null) { cExpr.setKnownIngressType(parameterTypes[i]); cExpr.computeTypeConversionRule(); } if (!cExpr.isConvertableIngressEgress()) { args[i] = convert(args[i], parameterTypes[i]); } } } else { /** * Coerce any types if required. */ for (int i = 0; i < args.length; i++) args[i] = convert(args[i], parameterTypes[i]); } addAccessorNode(new MethodAccessor(getWidenedTarget(m), (ExecutableStatement[]) es)); /** * Invoke the target method and return the response. */ return m.invoke(ctx, args); } }
#vulnerable code @SuppressWarnings({"unchecked"}) private Object getMethod(Object ctx, String name) throws Exception { int st = cursor; String tk = cursor != length && expr[cursor] == '(' && ((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ? new String(expr, st + 1, cursor - st - 1) : ""; cursor++; Object[] args; Accessor[] es; if (tk.length() == 0) { args = ParseTools.EMPTY_OBJ_ARR; es = null; } else { String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1); es = new ExecutableStatement[subtokens.length]; args = new Object[subtokens.length]; for (int i = 0; i < subtokens.length; i++) { args[i] = (es[i] = (ExecutableStatement) subCompileExpression(subtokens[i].toCharArray())) .getValue(this.ctx, thisRef, variableFactory); } } if (first && variableFactory != null && variableFactory.isResolveable(name)) { Object ptr = variableFactory.getVariableResolver(name).getValue(); if (ptr instanceof Method) { ctx = ((Method) ptr).getDeclaringClass(); name = ((Method) ptr).getName(); } else if (ptr instanceof MethodStub) { ctx = ((MethodStub) ptr).getClassReference(); name = ((MethodStub) ptr).getMethodName(); } else if (ptr instanceof Function) { addAccessorNode(new FunctionAccessor((Function) ptr, es)); Object[] parm = null; if (es != null) { parm = new Object[es.length]; for (int i = 0; i < es.length; i++) { parm[i] = es[i].getValue(ctx, thisRef, variableFactory); } } return ((Function) ptr).call(ctx, thisRef, variableFactory, parm); } else { throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: " + name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")"); } first = false; } /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class<?> cls = ctx == null || ctx instanceof Class ? (Class<?>) ctx : ctx.getClass(); Method m; Class[] parameterTypes = null; /** * If we have not cached the method then we need to go ahead and try to resolve it. */ /** * Try to find an instance method from the class target. */ if ((m = getBestCandidate(args, name, cls, cls.getMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = getBestCandidate(args, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } } if (m == null) { StringAppender errorBuild = new StringAppender(); for (int i = 0; i < args.length; i++) { errorBuild.append(args[i] != null ? args[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } if ("size".equals(name) && args.length == 0 && cls.isArray()) { addAccessorNode(new ArrayLength()); return getLength(ctx); } throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { if (es != null) { ExecutableStatement cExpr; for (int i = 0; i < es.length; i++) { cExpr = (ExecutableStatement) es[i]; if (cExpr.getKnownIngressType() == null) { cExpr.setKnownIngressType(parameterTypes[i]); cExpr.computeTypeConversionRule(); } if (!cExpr.isConvertableIngressEgress()) { args[i] = convert(args[i], parameterTypes[i]); } } } else { /** * Coerce any types if required. */ for (int i = 0; i < args.length; i++) args[i] = convert(args[i], parameterTypes[i]); } addAccessorNode(new MethodAccessor(getWidenedTarget(m), (ExecutableStatement[]) es)); /** * Invoke the target method and return the response. */ return m.invoke(ctx, args); } } #location 72 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (CACHE_DISABLE || !cacheAggressively) { char[] seg = new char[expression.length - 3]; // arraycopy(expression, 2, seg, 0, seg.length); for (int i = 0; i < seg.length; i++) seg[i] = expression[i + 2]; return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { if (tokens == null) { tokens = new HashMap(); } ForeachContext foreachContext; String[] names; String[] aliases; if (!(localStack.peek() instanceof ForeachContext)) { // create a clone of the context foreachContext = ((ForeachContext) currNode.getRegister()).clone(); names = foreachContext.getNames(); aliases = foreachContext.getAliases(); try { Iterator[] iters = new Iterator[names.length]; for (int i = 0; i < names.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(names[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); // this throws null pointer exception in thread race } // set the newly created iterators into the context foreachContext.setIterators(iters); // push the context onto the local stack. localStack.push(foreachContext); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)), e); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)), e); } } else { foreachContext = (ForeachContext) localStack.peek(); // names = foreachContext.getNames(); aliases = foreachContext.getAliases(); } Iterator[] iters = foreachContext.getItererators(); if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(aliases[i], iters[i].next()); } int c; tokens.put("i0", c = foreachContext.getCount()); if (c != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked foreachContext.incrementCount(); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(aliases[i]); } // foreachContext.setIterators(null); // foreachContext.setCount(0); localStack.pop(); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } }
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (CACHE_DISABLE || !cacheAggressively) { char[] seg = new char[expression.length - 3]; // arraycopy(expression, 2, seg, 0, seg.length); for (int i = 0; i < seg.length; i++) seg[i] = expression[i + 2]; return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { if (tokens == null) { tokens = new HashMap(); } ForeachContext foreachContext; if (!(localStack.peek() instanceof ForeachContext)) { foreachContext = ((ForeachContext) currNode.getRegister()).clone(); // if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); localStack.push(foreachContext); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } foreachContext = (ForeachContext) localStack.peek(); Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); localStack.pop(); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 118 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { synchronized (Runtime.getRuntime()) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } }
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, compileExpression(s)); return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { //noinspection unchecked MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { //noinspection unchecked Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { //noinspection unchecked tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } //noinspection unchecked tokens.put("i0", foreachContext.getCount()); foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length != 2) { return sbuf.toString(); } else { return register; } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); IncludeRefParam[] params = includeRef.getParams(); Map<String, Object> vars = new HashMap<String, Object>(params.length * 2); for (IncludeRefParam param : params) { vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens)); } if (registry == null) { throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'"); } String template = registry.getTemplate(includeRef.getName()); if (template == null) { throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'"); } sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 139 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.