input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization String cluster = Cluster.getIdentifier(jobtracker); return cluster != null ? cluster: null; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } String cluster = null; if (jobtracker != null) { // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization cluster = Cluster.getIdentifier(jobtracker); } return cluster; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int getQSize() { int res = 0; for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; res+=queue.size(); } for (int i = 0; i < queues.length; i++) { Queue queue = cbQueues[i]; res+=queue.size(); } return res; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int getQSize() { int res = 0; final Actor actors[] = this.actors; for (int i = 0; i < actors.length; i++) { Actor a = actors[i]; res+=a.__mailbox.size(); res+=a.__cbQueue.size(); } return res; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { removeActor((Actor) poll.getTarget()); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActor(actor); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void rebalance(DispatcherThread dispatcherThread) { int load = dispatcherThread.getLoad(); DispatcherThread minLoadThread = createNewThreadIfPossible(); if ( minLoadThread != null ) { // split dispatcherThread.splitTo(minLoadThread); minLoadThread.start(); return; } minLoadThread = findMinLoadThread(load / 4); if ( minLoadThread == null ) { // does not pay off. stay on current // System.out.println("no rebalance possible"); return; } // move cheapest actor up to half load synchronized (dispatcherThread.queueList) { long minNanos = Long.MAX_VALUE; Actor minActor = null; for (int i = 0; i < dispatcherThread.queueList.size(); i++) { Actor actor = dispatcherThread.queueList.get(i); if (actor.__nanos < minNanos) { minNanos = actor.__nanos; minActor = actor; } } if (minActor != null) { // System.out.println("move "+minActor+" from "+dispatcherThread+" to "+minLoadThread); dispatcherThread.removeActor(minActor); minLoadThread.addActor(minActor); dispatcherThread.applyQueueList(); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void rebalance(DispatcherThread dispatcherThread) { synchronized (balanceLock) { long load = dispatcherThread.getLoadNanos(); DispatcherThread minLoadThread = createNewThreadIfPossible(); if (minLoadThread != null) { // split dispatcherThread.splitTo(minLoadThread); minLoadThread.start(); return; } minLoadThread = findMinLoadThread(2 * load / 3, null); if (minLoadThread == null || minLoadThread == dispatcherThread) { // does not pay off. stay on current // System.out.println("no rebalance possible"); return; } // move cheapest actor synchronized (dispatcherThread.queueList) { ArrayList<Actor> qList = new ArrayList<>(dispatcherThread.queueList); long otherLoad = minLoadThread.getLoadNanos(); for (int i = 0; i < qList.size(); i++) { Actor actor = qList.get(i); if (otherLoad + actor.__nanos < load - actor.__nanos) { otherLoad += actor.__nanos; load -= actor.__nanos; System.out.println("move for idle " + actor.__nanos + " myload " + load + " otherlOad " + otherLoad); dispatcherThread.removeActor(actor); minLoadThread.addActor(actor); dispatcherThread.applyQueueList(); } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; } } scheduler.threadStopped(this); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int getQSize() { int res = 0; for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; res+=queue.size(); } for (int i = 0; i < queues.length; i++) { Queue queue = cbQueues[i]; res+=queue.size(); } return res; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int getQSize() { int res = 0; final Actor actors[] = this.actors; for (int i = 0; i < actors.length; i++) { Actor a = actors[i]; res+=a.__mailbox.size(); res+=a.__cbQueue.size(); } return res; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { removeActor((Actor) poll.getTarget()); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActor(actor); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int getLoad() { int res = 0; for (int i = 0; i < queues.length; i++) { MpscConcurrentQueue queue = (MpscConcurrentQueue) queues[i]; int load = queue.size() * 100 / queue.getCapacity(); if ( load > res ) res = load; } return res; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int getLoad() { int res = 0; final Actor actors[] = this.actors; for (int i = 0; i < actors.length; i++) { MpscConcurrentQueue queue = (MpscConcurrentQueue) actors[i].__mailbox; int load = queue.size() * 100 / queue.getCapacity(); if ( load > res ) res = load; } return res; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isEmpty() { for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; if ( ! queue.isEmpty() ) return false; } for (int i = 0; i < cbQueues.length; i++) { Queue queue = cbQueues[i]; if ( ! queue.isEmpty() ) return false; } return true; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean isEmpty() { for (int i = 0; i < actors.length; i++) { Actor act = actors[i]; if ( ! act.__mailbox.isEmpty() || ! act.__cbQueue.isEmpty() ) return false; } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { int emptyCount = 0; int scheduleNewActorCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; scheduleNewActorCount++; if ( scheduleNewActorCount > 500 ) { scheduleNewActorCount = 0; schedulePendingAdds(); } } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) ) { scheduleNewActorCount = 0; schedulePendingAdds(); if ( System.currentTimeMillis()-created > 3000 ) { if ( actors.length == 0 && toAdd.peek() == null ) { shutDown(); } else { scheduler.tryStopThread(this); } } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( actors.length > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); scheduler.tryStopThread(this); i = 0; } } System.out.println("thread died"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isEmpty() { for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; if ( ! queue.isEmpty() ) return false; } for (int i = 0; i < cbQueues.length; i++) { Queue queue = cbQueues[i]; if ( ! queue.isEmpty() ) return false; } return true; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean isEmpty() { for (int i = 0; i < actors.length; i++) { Actor act = actors[i]; if ( ! act.__mailbox.isEmpty() || ! act.__cbQueue.isEmpty() ) return false; } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActor(actor); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean pollQs() { CallEntry poll = pollQueues(actors); // first callback actors if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActorImmediate(actor); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { int emptyCount = 0; int scheduleNewActorCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; scheduleNewActorCount++; if ( scheduleNewActorCount > 500 ) { scheduleNewActorCount = 0; schedulePendingAdds(); } } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) ) { scheduleNewActorCount = 0; schedulePendingAdds(); if ( System.currentTimeMillis()-created > 3000 ) { if ( actors.length == 0 && toAdd.peek() == null ) { shutDown(); } else { scheduler.tryStopThread(this); } } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( actors.length > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); scheduler.tryStopThread(this); i = 0; } } System.out.println("thread died"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActor(actor); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean pollQs() { CallEntry poll = pollQueues(actors); // first callback actors if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActorImmediate(actor); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; } } scheduler.threadStopped(this); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Collection<?> getSortableContainerPropertyIds() { if (backingList instanceof SortableLazyList) { // Assume SortableLazyList can sort by any Comparable property } else if (backingList instanceof LazyList) { // When using LazyList, don't support sorting by default // as the sorting should most probably be done at backend call level return Collections.emptySet(); } final ArrayList<String> props = new ArrayList<String>(); for (Object a : getContainerPropertyIds()) { DynaProperty db = getDynaClass().getDynaProperty(a.toString()); if (db != null && db.getType() != null && (db.getType(). isPrimitive() || Comparable.class.isAssignableFrom( db.getType()))) { props.add(db.getName()); } } return props; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Collection<?> getSortableContainerPropertyIds() { if (backingList instanceof SortableLazyList) { // Assume SortableLazyList can sort by any Comparable property } else if (backingList instanceof LazyList) { // When using LazyList, don't support sorting by default // as the sorting should most probably be done at backend call level return Collections.emptySet(); } final ArrayList<String> props = new ArrayList<String>(); for (Object a : getContainerPropertyIds()) { String propName = a.toString(); Class<?> propType = getType(propName); if (propType != null && (propType.isPrimitive() || Comparable.class.isAssignableFrom(propType))) { props.add(propName); } } return props; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Property getContainerProperty(Object itemId, Object propertyId) { return getItem(itemId).getItemProperty(propertyId); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Property getContainerProperty(Object itemId, Object propertyId) { Item i = getItem(itemId); return (i != null) ? i.getItemProperty(propertyId) : null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void visitIincInsn(int var, int increment) { super.visitIincInsn(var, increment); // Track variable state and name at variable stores. (At variable increases.) LocalVariableScope lvs = getLocalVariableScope(var); instrumentToTrackVariableName(lvs); instrumentToTrackVariableState(lvs); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void visitIincInsn(int var, int increment) { super.visitIincInsn(var, increment); // Track variable state at variable increases (e.g. i++). LocalVariableScope lvs = getLocalVariableScope(var); instrumentToTrackVariableState(lvs, lineNumber); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/api/processor", method = RequestMethod.POST, headers = "Accept=application/json") ConversationDTO requestProcessor(@RequestParam(value = "runnerLogId", required = false) String runnerLogId, @RequestBody RfRequestDTO rfRequestDTO) { Conversation existingConversation = null; Conversation currentConversation; // TODO : Get RfRequest Id if present as part of this request and update the existing conversation entity. // Note : New conversation entity which is getting created below is still required for logging purpose. if (rfRequestDTO == null) { return null; } else if (rfRequestDTO.getId() != null && !rfRequestDTO.getId().isEmpty()) { RfRequest rfRequest = rfRequestRepository.findOne(rfRequestDTO.getId()); String conversationId = rfRequest != null ? rfRequest.getConversationId() : null; existingConversation = conversationId != null ? conversationRepository.findOne(conversationId) : null; // finding updated existing conversation existingConversation = existingConversation != null ? nodeRepository.findOne(existingConversation.getNodeId()).getConversation() : null; rfRequestDTO.setAssertionDTO(EntityToDTO.toDTO(existingConversation.getRfRequest().getAssertion())); } long startTime = System.currentTimeMillis(); RfResponseDTO result = genericHandler.processHttpRequest(rfRequestDTO); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; if (result != null) { String nodeId = null; if (existingConversation != null && existingConversation.getNodeId() != null) { nodeId = existingConversation.getNodeId(); } assertHandler.runAssert(result, nodeId); } currentConversation = ConversationConverter.convertToEntity(rfRequestDTO, result); // This is used to get project-runner/folder-runner logs currentConversation.setRunnerLogId(runnerLogId); if (existingConversation != null) { currentConversation.getRfRequest().setAssertion(existingConversation.getRfRequest().getAssertion()); } rfRequestRepository.save(currentConversation.getRfRequest()); rfResponseRepository.save(currentConversation.getRfResponse()); currentConversation.setDuration(duration); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof User) { currentConversation.setLastModifiedBy((User) principal); } Date currentDate = new Date(); currentConversation.setCreatedDate(currentDate); currentConversation.setLastModifiedDate(currentDate); currentConversation.setLastRunDate(currentDate); currentConversation.setName(currentConversation.getRfRequest().getApiUrl()); try { currentConversation = conversationRepository.save(currentConversation); currentConversation.getRfRequest().setConversationId(currentConversation.getId()); rfRequestRepository.save(currentConversation.getRfRequest()); ActivityLog activityLog = null; // Note : existingConversation will be null if the request was not saved previously. if (existingConversation != null && existingConversation.getNodeId() != null) { BaseNode node = nodeRepository.findOne(existingConversation.getNodeId()); currentConversation.setNodeId(node.getId()); currentConversation.setName(node.getName()); activityLog = activityLogRepository.findActivityLogByDataId(node.getId()); } if (principal instanceof User) { currentConversation.setLastModifiedBy((User) principal); } conversationRepository.save(currentConversation); if (activityLog == null) { activityLog = new ActivityLog(); activityLog.setDataId(existingConversation.getNodeId()); activityLog.setType("CONVERSATION"); } activityLog.setName(currentConversation.getName()); activityLog.setWorkspaceId(currentConversation.getWorkspaceId()); activityLog.setLastModifiedDate(currentDate); List<BaseEntity> logData = activityLog.getData(); logData.add(0, currentConversation); activityLogRepository.save(activityLog); } catch (InvalidDataAccessResourceUsageException e) { throw new ApiException("Please use sql as datasource, some of features are not supported by hsql", e); } ConversationDTO conversationDTO = new ConversationDTO(); conversationDTO.setWorkspaceId(rfRequestDTO.getWorkspaceId()); conversationDTO.setDuration(duration); conversationDTO.setRfResponseDTO(result); if (result != null) { result.setItemDTO(conversationDTO); } return conversationDTO; } #location 83 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/api/processor", method = RequestMethod.POST, headers = "Accept=application/json") ConversationDTO requestProcessor(@RequestParam(value = "runnerLogId", required = false) String runnerLogId, @RequestBody RfRequestDTO rfRequestDTO) { Conversation existingConversation = null; Conversation currentConversation; // TODO : Get RfRequest Id if present as part of this request and update the existing conversation entity. // Note : New conversation entity which is getting created below is still required for logging purpose. if (rfRequestDTO == null) { return null; } else if (rfRequestDTO.getId() != null && !rfRequestDTO.getId().isEmpty()) { RfRequest rfRequest = rfRequestRepository.findOne(rfRequestDTO.getId()); String conversationId = rfRequest != null ? rfRequest.getConversationId() : null; existingConversation = conversationId != null ? conversationRepository.findOne(conversationId) : null; // finding updated existing conversation existingConversation = existingConversation != null ? nodeRepository.findOne(existingConversation.getNodeId()).getConversation() : null; if(existingConversation != null) { rfRequestDTO.setAssertionDTO(EntityToDTO.toDTO(existingConversation.getRfRequest().getAssertion())); } } long startTime = System.currentTimeMillis(); RfResponseDTO result = genericHandler.processHttpRequest(rfRequestDTO); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; if (result != null) { String nodeId = null; if (existingConversation != null && existingConversation.getNodeId() != null) { nodeId = existingConversation.getNodeId(); } assertHandler.runAssert(result, nodeId); } currentConversation = ConversationConverter.convertToEntity(rfRequestDTO, result); // This is used to get project-runner/folder-runner logs currentConversation.setRunnerLogId(runnerLogId); if (existingConversation != null) { currentConversation.getRfRequest().setAssertion(existingConversation.getRfRequest().getAssertion()); } rfRequestRepository.save(currentConversation.getRfRequest()); rfResponseRepository.save(currentConversation.getRfResponse()); currentConversation.setDuration(duration); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof User) { currentConversation.setLastModifiedBy((User) principal); } Date currentDate = new Date(); currentConversation.setCreatedDate(currentDate); currentConversation.setLastModifiedDate(currentDate); currentConversation.setLastRunDate(currentDate); currentConversation.setName(currentConversation.getRfRequest().getApiUrl()); try { currentConversation = conversationRepository.save(currentConversation); currentConversation.getRfRequest().setConversationId(currentConversation.getId()); rfRequestRepository.save(currentConversation.getRfRequest()); ActivityLog activityLog = null; // Note : existingConversation will be null if the request was not saved previously. if (existingConversation != null && existingConversation.getNodeId() != null) { BaseNode node = nodeRepository.findOne(existingConversation.getNodeId()); currentConversation.setNodeId(node.getId()); currentConversation.setName(node.getName()); activityLog = activityLogRepository.findActivityLogByDataId(node.getId()); } if (principal instanceof User) { currentConversation.setLastModifiedBy((User) principal); } conversationRepository.save(currentConversation); if (activityLog == null) { activityLog = new ActivityLog(); if(existingConversation != null) { activityLog.setDataId(existingConversation.getNodeId()); } activityLog.setType("CONVERSATION"); } activityLog.setName(currentConversation.getName()); activityLog.setWorkspaceId(currentConversation.getWorkspaceId()); activityLog.setLastModifiedDate(currentDate); List<BaseEntity> logData = activityLog.getData(); logData.add(0, currentConversation); activityLogRepository.save(activityLog); } catch (InvalidDataAccessResourceUsageException e) { throw new ApiException("Please use sql as datasource, some of features are not supported by hsql", e); } ConversationDTO conversationDTO = new ConversationDTO(); conversationDTO.setWorkspaceId(rfRequestDTO.getWorkspaceId()); conversationDTO.setDuration(duration); conversationDTO.setRfResponseDTO(result); if (result != null) { result.setItemDTO(conversationDTO); } return conversationDTO; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.PUT, headers = "Accept=application/json", consumes = "application/json") public @ResponseBody String updateEntityData(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName, @PathVariable("uuid") String uuid, @RequestBody Object genericEntityDataDTO) { DBObject resultObject = new BasicDBObject(); if (genericEntityDataDTO instanceof Map) { Map map = (Map) genericEntityDataDTO; if (map.get("id") != null && map.get("id") instanceof String) { String entityDataId = (String) map.get("id"); logger.debug("Updating Entity Data with Id " + entityDataId); } JSONObject uiJson = createJsonFromMap(map); // ID is stored separately (in a different column). uiJson.remove("_id"); DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName); BasicDBObject queryObject = new BasicDBObject(); queryObject.append("_id", new ObjectId(uuid)); resultObject = dbCollection.findOne(queryObject); Set<String> keySet = uiJson.keySet(); for (String key : keySet) { Object obj = uiJson.get(key); if (obj instanceof Map) { Map doc = (Map) obj; if (doc.containsKey("_relation")) { Map relation = (Map) doc.get("_relation"); resultObject.put(key, new DBRef(mongoTemplate.getDb(), projectId + "_" + (String) relation.get("entity"), new ObjectId((String) relation.get("_id")))); } else { resultObject.put(key, uiJson.get(key)); } } else { resultObject.put(key, uiJson.get(key)); } } dbCollection.save(resultObject); } resolveDBRef(resultObject); String json = resultObject.toString(); // Indentation JSONObject jsonObject = new JSONObject(json); return jsonObject.toString(4); } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.PUT, headers = "Accept=application/json", consumes = "application/json") public @ResponseBody String updateEntityData(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName, @PathVariable("uuid") String uuid, @RequestBody Object genericEntityDataDTO) { DBObject resultObject = new BasicDBObject(); if (genericEntityDataDTO instanceof Map) { Map map = (Map) genericEntityDataDTO; if (map.get("id") != null && map.get("id") instanceof String) { String entityDataId = (String) map.get("id"); logger.debug("Updating Entity Data with Id " + entityDataId); } JSONObject uiJson = new JSONObject(map); // ID is stored separately (in a different column). DBObject obj = (DBObject) JSON.parse(uiJson.toString()); obj.removeField("_id"); DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName); BasicDBObject queryObject = new BasicDBObject(); queryObject.append("_id", new ObjectId(uuid)); resultObject = dbCollection.findOne(queryObject); Set<String> keySet = obj.keySet(); for (String key : keySet) { resultObject.put(key, obj.get(key)); } relationToDBRef(resultObject, projectId); dbCollection.save(resultObject); } dbRefToRelation(resultObject); String json = resultObject.toString(); // Indentation JSONObject jsonObject = new JSONObject(json); return jsonObject.toString(4); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void rfToSwaggerConverter(String projectId) { Swagger swagger = new SwaggerParser().read("http://petstore.swagger.io/v2/swagger.json"); Project project = projectController.findById(null, projectId); String projectNodeRefId = project.getProjectRef().getId(); TreeNode projectNode = nodeController.getProjectTree(projectNodeRefId); swagger = new Swagger(); //TODO : set host and basepath for swagger //swagger.setHost(host); //swagger.setBasePath(basePath); Info info = new Info(); info.setTitle(projectNode.getName()); info.setDescription(projectNode.getDescription()); swagger.setInfo(info); Map<String, Path> paths = new HashMap<>(); Path path = null; String pathKey = null; String method = null; Operation op = null; String operationId = null; String summary = null; List<TreeNode> children = projectNode.getChildren(); for (int i = 0; i < children.size(); i++) { TreeNode childNode = children.get(i); path = new Path(); op = new Operation(); operationId = childNode.getName(); summary = childNode.getDescription(); op.setOperationId(operationId); op.setSummary(summary); method = childNode.getMethod().toLowerCase(); path.set(method, op); //TODO : pathKey is the relative url (for example /workspaces) from the api url pathKey = null; paths.put(pathKey, path); } swagger.setPaths(paths); JsonNode jsonNode = Json.mapper().convertValue(swagger, JsonNode.class); System.out.println(jsonNode.toString()); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code private void rfToSwaggerConverter(String projectId) { Swagger swagger = new SwaggerParser().read("http://petstore.swagger.io/v2/swagger.json"); Project project = projectController.findById(null, projectId); String projectNodeRefId = project.getProjectRef().getId(); TreeNode projectNode = nodeController.getProjectTree(projectNodeRefId, null); swagger = new Swagger(); //TODO : set host and basepath for swagger //swagger.setHost(host); //swagger.setBasePath(basePath); Info info = new Info(); info.setTitle(projectNode.getName()); info.setDescription(projectNode.getDescription()); swagger.setInfo(info); Map<String, Path> paths = new HashMap<>(); Path path = null; String pathKey = null; String method = null; Operation op = null; String operationId = null; String summary = null; List<TreeNode> children = projectNode.getChildren(); for (int i = 0; i < children.size(); i++) { TreeNode childNode = children.get(i); path = new Path(); op = new Operation(); operationId = childNode.getName(); summary = childNode.getDescription(); op.setOperationId(operationId); op.setSummary(summary); method = childNode.getMethod().toLowerCase(); path.set(method, op); //TODO : pathKey is the relative url (for example /workspaces) from the api url pathKey = null; paths.put(pathKey, path); } swagger.setPaths(paths); JsonNode jsonNode = Json.mapper().convertValue(swagger, JsonNode.class); System.out.println(jsonNode.toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ModbusPdu decodeException(FunctionCode functionCode, ByteBuf buffer) throws DecoderException { int code = buffer.readByte(); ExceptionCode exceptionCode = ExceptionCode .fromCode(code) .orElseThrow(() -> new DecoderException("invalid exception code: " + code)); return new ExceptionResponse(functionCode, exceptionCode); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private ModbusPdu decodeException(FunctionCode functionCode, ByteBuf buffer) throws DecoderException { int code = buffer.readUnsignedByte(); ExceptionCode exceptionCode = ExceptionCode .fromCode(code) .orElseThrow(() -> new DecoderException("invalid exception code: " + code)); return new ExceptionResponse(functionCode, exceptionCode); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long appendUtf8(long pos, char[] chars, int offset, int length) { if (pos + length > realCapacity()) throw new BufferOverflowException(); long address = this.address + translate(0); Memory memory = this.memory; int i; ascii: { for (i = 0; i < length - 3; i += 4) { char c0 = chars[offset + i]; char c1 = chars[offset + i + 1]; char c2 = chars[offset + i + 2]; char c3 = chars[offset + i + 3]; if ((c0 | c1 | c2 | c3) > 0x007F) break ascii; memory.writeInt(address + pos, (c0) | (c1 << 8) | (c2 << 16) | (c3 << 24)); pos += 4; } for (; i < length; i++) { char c = chars[offset + i]; if (c > 0x007F) break ascii; memory.writeByte(address + pos++, (byte) c); } return pos; } return appendUTF0(pos, chars, offset, length, i); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code public long appendUtf8(long pos, char[] chars, int offset, int length) { if (pos + length > realCapacity()) throw new BufferOverflowException(); long address = this.address + translate(0); Memory memory = this.memory; if (memory == null) throw new NullPointerException(); Unsafe unsafe = UnsafeMemory.UNSAFE; int i; ascii: { for (i = 0; i < length - 3; i += 4) { char c0 = chars[offset + i]; char c1 = chars[offset + i + 1]; char c2 = chars[offset + i + 2]; char c3 = chars[offset + i + 3]; if ((c0 | c1 | c2 | c3) > 0x007F) break ascii; unsafe.putInt(address + pos, (c0) | (c1 << 8) | (c2 << 16) | (c3 << 24)); pos += 4; } for (; i < length; i++) { char c = chars[offset + i]; if (c > 0x007F) break ascii; unsafe.putByte(address + pos++, (byte) c); } return pos; } return appendUtf8a(pos, chars, offset, length, i); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testName() { NativeBytesStore<Void> nativeStore = NativeBytesStore.nativeStoreWithFixedCapacity(30); Bytes<Void> bytes = nativeStore.bytesForWrite(); long expected = 12345L; int offset = 5; bytes.writeLong(offset, expected); bytes.writePosition(offset + 8); assertEquals(expected, bytes.readLong(offset)); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testName() { Bytes<Void> bytes = Bytes.allocateDirect(30); long expected = 12345L; int offset = 5; bytes.writeLong(offset, expected); bytes.writePosition(offset + 8); assertEquals(expected, bytes.readLong(offset)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testName() { NativeBytesStore<Void> nativeStore = NativeBytesStore.nativeStoreWithFixedCapacity(30); Bytes<Void> bytes = nativeStore.bytesForWrite(); long expected = 12345L; int offset = 5; bytes.writeLong(offset, expected); bytes.writePosition(offset + 8); assertEquals(expected, bytes.readLong(offset)); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testName() { Bytes<Void> bytes = Bytes.allocateDirect(30); long expected = 12345L; int offset = 5; bytes.writeLong(offset, expected); bytes.writePosition(offset + 8); assertEquals(expected, bytes.readLong(offset)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static BytesStore<Bytes<Void>, Void> copyOf(Bytes bytes) { long remaining = bytes.readRemaining(); NativeBytes<Void> bytes2 = NativeBytes.nativeBytes(remaining); bytes2.write(bytes, 0, remaining); return bytes2; } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static BytesStore<Bytes<Void>, Void> copyOf(Bytes bytes) { long remaining = bytes.readRemaining(); NativeBytes<Void> bytes2 = Bytes.allocateElasticDirect(remaining); bytes2.write(bytes, 0, remaining); return bytes2; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Bytes acquireBytesForWrite(long position) throws IOException, IllegalStateException, IllegalArgumentException { MappedBytesStore mbs = acquireByteStore(position); MappedBytes bytes = mbs.bytesForWrite(); bytes.writePosition(position); mbs.release(); return bytes; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public Bytes acquireBytesForWrite(long position) throws IOException, IllegalStateException, IllegalArgumentException { MappedBytesStore mbs = acquireByteStore(position); Bytes bytes = mbs.bytesForWrite(); bytes.writePosition(position); mbs.release(); return bytes; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testName() { NativeBytesStore<Void> nativeStore = NativeBytesStore.nativeStoreWithFixedCapacity(30); Bytes<Void> bytes = nativeStore.bytesForWrite(); long expected = 12345L; int offset = 5; bytes.writeLong(offset, expected); bytes.writePosition(offset + 8); assertEquals(expected, bytes.readLong(offset)); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testName() { Bytes<Void> bytes = Bytes.allocateDirect(30); long expected = 12345L; int offset = 5; bytes.writeLong(offset, expected); bytes.writePosition(offset + 8); assertEquals(expected, bytes.readLong(offset)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Bytes acquireBytesForWrite(long position) throws IOException, IllegalStateException, IllegalArgumentException { MappedBytesStore mbs = acquireByteStore(position); Bytes bytes = mbs.bytesForWrite(); bytes.writePosition(position); mbs.release(); return bytes; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public Bytes acquireBytesForWrite(long position) throws IOException, IllegalStateException, IllegalArgumentException { MappedBytesStore mbs = acquireByteStore(position); MappedBytes bytes = mbs.bytesForWrite(); bytes.writePosition(position); mbs.release(); return bytes; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long appendUtf8(long pos, char[] chars, int offset, int length) { if (pos + length > realCapacity()) throw new BufferOverflowException(); long address = this.address + translate(0); Memory memory = this.memory; int i; ascii: { for (i = 0; i < length - 3; i += 4) { char c0 = chars[offset + i]; char c1 = chars[offset + i + 1]; char c2 = chars[offset + i + 2]; char c3 = chars[offset + i + 3]; if ((c0 | c1 | c2 | c3) > 0x007F) break ascii; memory.writeInt(address + pos, (c0) | (c1 << 8) | (c2 << 16) | (c3 << 24)); pos += 4; } for (; i < length; i++) { char c = chars[offset + i]; if (c > 0x007F) break ascii; memory.writeByte(address + pos++, (byte) c); } return pos; } return appendUTF0(pos, chars, offset, length, i); } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code public long appendUtf8(long pos, char[] chars, int offset, int length) { if (pos + length > realCapacity()) throw new BufferOverflowException(); long address = this.address + translate(0); Memory memory = this.memory; if (memory == null) throw new NullPointerException(); Unsafe unsafe = UnsafeMemory.UNSAFE; int i; ascii: { for (i = 0; i < length - 3; i += 4) { char c0 = chars[offset + i]; char c1 = chars[offset + i + 1]; char c2 = chars[offset + i + 2]; char c3 = chars[offset + i + 3]; if ((c0 | c1 | c2 | c3) > 0x007F) break ascii; unsafe.putInt(address + pos, (c0) | (c1 << 8) | (c2 << 16) | (c3 << 24)); pos += 4; } for (; i < length; i++) { char c = chars[offset + i]; if (c > 0x007F) break ascii; unsafe.putByte(address + pos++, (byte) c); } return pos; } return appendUtf8a(pos, chars, offset, length, i); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean compareAndSwapValue(long expected, long value) { if (value == LONG_NOT_COMPLETE && binaryLongReferences != null) binaryLongReferences.add(new WeakReference<>(this)); return bytes.compareAndSwapLong(offset, expected, value); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean compareAndSwapValue(long expected, long value) { BytesStore bytes = this.bytes; return bytes != null && bytes.compareAndSwapLong(offset, expected, value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void toHexString() { Bytes bytes = NativeBytes.nativeBytes(1020); bytes.append("Hello World"); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello Wo rld \n", bytes.toHexString()); bytes.readLimit(bytes.realCapacity()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000003f0 00 00 00 00 00 00 00 00 00 00 00 00 ········ ···· \n", bytes.toHexString()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + ".... truncated", bytes.toHexString(256)); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void toHexString() { Bytes bytes = Bytes.allocateElasticDirect(1020); bytes.append("Hello World"); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello Wo rld \n", bytes.toHexString()); bytes.readLimit(bytes.realCapacity()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000003f0 00 00 00 00 00 00 00 00 00 00 00 00 ········ ···· \n", bytes.toHexString()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + ".... truncated", bytes.toHexString(256)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int peekVolatileInt() { readCheckOffset(readPosition, 4, true); MappedBytesStore bytesStore = (MappedBytesStore) (BytesStore) this.bytesStore; long address = bytesStore.address + bytesStore.translate(readPosition); Memory memory = bytesStore.memory; for (int i = 0; i < 128; i++) { int value = memory.readVolatileInt(address); if (value != 0) return value; } return 0; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public int peekVolatileInt() { if (!bytesStore.inside(readPosition)) { acquireNextByteStore(readPosition); } MappedBytesStore bytesStore = (MappedBytesStore) (BytesStore) this.bytesStore; long address = bytesStore.address + bytesStore.translate(readPosition); Memory memory = bytesStore.memory; // are we inside a cache line? if ((address & 63) <= 60) { if (memory == null) throw new NullPointerException(); for (int i = 0; i < 64; i++) { int value = UnsafeMemory.UNSAFE.getIntVolatile(null, address); if (value != 0 && value != 0x80000000) return value; } } else { for (int i = 0; i < 32; i++) { int value = memory.readVolatileInt(address); if (value != 0) return value; } } return 0; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int byteCheckSum() throws IORuntimeException { if (readLimit() >= Integer.MAX_VALUE || start() != 0) return super.byteCheckSum(); byte b = 0; NativeBytesStore bytesStore = (NativeBytesStore) bytesStore(); for (int i = (int) readPosition(), lim = (int) readLimit(); i < lim; i++) { b += bytesStore.memory.readByte(bytesStore.address + i); } return b & 0xFF; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public int byteCheckSum() throws IORuntimeException { if (readLimit() >= Integer.MAX_VALUE || start() != 0) return super.byteCheckSum(); byte b = 0; NativeBytesStore bytesStore = (NativeBytesStore) bytesStore(); Memory memory = bytesStore.memory; assert memory != null; for (int i = (int) readPosition(), lim = (int) readLimit(); i < lim; i++) { b += memory.readByte(bytesStore.address + i); } return b & 0xFF; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void toHexString() { Bytes bytes = NativeBytes.nativeBytes(1020); bytes.append("Hello World"); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello Wo rld \n", bytes.toHexString()); bytes.readLimit(bytes.realCapacity()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000003f0 00 00 00 00 00 00 00 00 00 00 00 00 ········ ···· \n", bytes.toHexString()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + ".... truncated", bytes.toHexString(256)); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void toHexString() { Bytes bytes = Bytes.allocateElasticDirect(1020); bytes.append("Hello World"); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello Wo rld \n", bytes.toHexString()); bytes.readLimit(bytes.realCapacity()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000003f0 00 00 00 00 00 00 00 00 00 00 00 00 ········ ···· \n", bytes.toHexString()); assertEquals("00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 00 00 00 00 Hello Wo rld·····\n" + "00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + "........\n" + "000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ········ ········\n" + ".... truncated", bytes.toHexString(256)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldBeReadOnly() throws Exception { final File tempFile = File.createTempFile("mapped", "bytes"); final RandomAccessFile raf = new RandomAccessFile(tempFile, "rw"); raf.setLength(4096); assertTrue(tempFile.setWritable(false)); final MappedBytes mappedBytes = MappedBytes.readOnly(tempFile); assertTrue(mappedBytes. isBackingFileReadOnly()); mappedBytes.release(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void shouldBeReadOnly() throws Exception { final File tempFile = File.createTempFile("mapped", "bytes"); tempFile.deleteOnExit(); try (RandomAccessFile raf = new RandomAccessFile(tempFile, "rw")) { raf.setLength(4096); assertTrue(tempFile.setWritable(false)); try (MappedBytes mappedBytes = MappedBytes.readOnly(tempFile)) { assertTrue(mappedBytes.isBackingFileReadOnly()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Nullable public MappedBytesStore acquireByteStore(long position) throws IOException { if (closed.get()) throw new IOException("Closed"); int chunk = (int) (position / chunkSize); synchronized (stores) { while (stores.size() <= chunk) { stores.add(null); } WeakReference<MappedBytesStore> mbsRef = stores.get(chunk); if (mbsRef != null) { MappedBytesStore mbs = mbsRef.get(); if (mbs != null && mbs.tryReserve()) { return mbs; } } long minSize = (chunk + 1L) * chunkSize + overlapSize; long size = fileChannel.size(); if (size < minSize) { // handle a possible race condition between processes. try (FileLock lock = fileChannel.lock()) { size = fileChannel.size(); if (size < minSize) { raf.setLength(minSize); } } } long start = System.nanoTime(); long mappedSize = chunkSize + overlapSize; long address = OS.map(fileChannel, FileChannel.MapMode.READ_WRITE, chunk * chunkSize, mappedSize); MappedBytesStore mbs2 = new MappedBytesStore(this, chunk * chunkSize, address, mappedSize, chunkSize); stores.set(chunk, new WeakReference<>(mbs2)); mbs2.reserve(); System.out.printf("Took %,d us to acquire chunk %,d%n", (System.nanoTime() - start) / 1000, chunk); // new Throwable("chunk "+chunk).printStackTrace(); return mbs2; } } #location 34 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code @Nullable public MappedBytesStore acquireByteStore(long position) throws IOException { if (closed.get()) throw new IOException("Closed"); int chunk = (int) (position / chunkSize); synchronized (stores) { while (stores.size() <= chunk) { stores.add(null); } WeakReference<MappedBytesStore> mbsRef = stores.get(chunk); if (mbsRef != null) { MappedBytesStore mbs = mbsRef.get(); if (mbs != null && mbs.tryReserve()) { return mbs; } } long minSize = (chunk + 1L) * chunkSize + overlapSize; long size = fileChannel.size(); if (size < minSize) { // handle a possible race condition between processes. try (FileLock lock = fileChannel.lock()) { size = fileChannel.size(); if (size < minSize) { raf.setLength(minSize); } } } long start = System.nanoTime(); long mappedSize = chunkSize + overlapSize; long address = OS.map(fileChannel, FileChannel.MapMode.READ_WRITE, chunk * chunkSize, mappedSize); MappedBytesStore mbs2 = new MappedBytesStore(this, chunk * chunkSize, address, mappedSize, chunkSize); stores.set(chunk, new WeakReference<>(mbs2)); mbs2.reserve(); LOG.warn("Took %,d us to acquire chunk %,d%n", (System.nanoTime() - start) / 1000, chunk); // new Throwable("chunk "+chunk).printStackTrace(); return mbs2; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCapacity() { assertEquals(SIZE, bytes.capacity()); assertEquals(10, NativeBytesStore.nativeStoreWithFixedCapacity(10).capacity()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCapacity() { assertEquals(SIZE, bytes.capacity()); assertEquals(10, Bytes.allocateDirect(10).capacity()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ProtocolProcessor init(IConfig props) { subscriptions = new SubscriptionsStore(); //TODO use a property to select the storage path m_mapStorage = new MapDBPersistentStore(props.getProperty(PERSISTENT_STORE_PROPERTY_NAME, "")); m_mapStorage.initStore(); IMessagesStore messagesStore = m_mapStorage.messagesStore(); ISessionsStore sessionsStore = m_mapStorage.sessionsStore(messagesStore); List<InterceptHandler> observers = new ArrayList<>(); String interceptorClassName = props.getProperty("intercept.handler"); if (interceptorClassName != null && !interceptorClassName.isEmpty()) { try { InterceptHandler handler = Class.forName(interceptorClassName).asSubclass(InterceptHandler.class).newInstance(); observers.add(handler); } catch (Throwable ex) { LOG.error("Can't load the intercept handler {}", ex); } } m_interceptor = new BrokerInterceptor(observers); subscriptions.init(sessionsStore); String configPath = System.getProperty("moquette.path", null); String authenticatorClassName = props.getProperty(Constants.AUTHENTICATOR_CLASS_NAME, ""); IAuthenticator authenticator = null; if (!authenticatorClassName.isEmpty()) { authenticator = (IAuthenticator)loadClass(authenticatorClassName, IAuthenticator.class); LOG.info("Loaded custom authenticator {}", authenticatorClassName); } if (authenticator == null) { String passwdPath = props.getProperty(PASSWORD_FILE_PROPERTY_NAME, ""); if (passwdPath.isEmpty()) { authenticator = new AcceptAllAuthenticator(); } else { authenticator = new FileAuthenticator(configPath, passwdPath); } } IAuthorizator authorizator = null; String authorizatorClassName = props.getProperty(Constants.AUTHORIZATOR_CLASS_NAME, ""); if (!authorizatorClassName.isEmpty()) { authorizator = (IAuthorizator)loadClass(authorizatorClassName, IAuthorizator.class); LOG.info("Loaded custom authorizator {}", authorizatorClassName); } if (authorizator == null) { String aclFilePath = props.getProperty(ACL_FILE_PROPERTY_NAME, ""); if (aclFilePath != null && !aclFilePath.isEmpty()) { authorizator = new DenyAllAuthorizator(); File aclFile = new File(configPath, aclFilePath); try { authorizator = ACLFileParser.parse(aclFile); } catch (ParseException pex) { LOG.error(String.format("Format error in parsing acl file %s", aclFile), pex); } LOG.info("Using acl file defined at path {}", aclFilePath); } else { authorizator = new PermitAllAuthorizator(); LOG.info("Starting without ACL definition"); } } boolean allowAnonymous = Boolean.parseBoolean(props.getProperty(ALLOW_ANONYMOUS_PROPERTY_NAME, "true")); m_processor.init(subscriptions, messagesStore, sessionsStore, authenticator, allowAnonymous, authorizator, m_interceptor); return m_processor; } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code public ProtocolProcessor init(IConfig props) { subscriptions = new SubscriptionsStore(); m_mapStorage = new MapDBPersistentStore(props); m_mapStorage.initStore(); IMessagesStore messagesStore = m_mapStorage.messagesStore(); ISessionsStore sessionsStore = m_mapStorage.sessionsStore(messagesStore); List<InterceptHandler> observers = new ArrayList<>(); String interceptorClassName = props.getProperty("intercept.handler"); if (interceptorClassName != null && !interceptorClassName.isEmpty()) { try { InterceptHandler handler = Class.forName(interceptorClassName).asSubclass(InterceptHandler.class).newInstance(); observers.add(handler); } catch (Throwable ex) { LOG.error("Can't load the intercept handler {}", ex); } } m_interceptor = new BrokerInterceptor(observers); subscriptions.init(sessionsStore); String configPath = System.getProperty("moquette.path", null); String authenticatorClassName = props.getProperty(Constants.AUTHENTICATOR_CLASS_NAME, ""); IAuthenticator authenticator = null; if (!authenticatorClassName.isEmpty()) { authenticator = (IAuthenticator)loadClass(authenticatorClassName, IAuthenticator.class); LOG.info("Loaded custom authenticator {}", authenticatorClassName); } if (authenticator == null) { String passwdPath = props.getProperty(PASSWORD_FILE_PROPERTY_NAME, ""); if (passwdPath.isEmpty()) { authenticator = new AcceptAllAuthenticator(); } else { authenticator = new FileAuthenticator(configPath, passwdPath); } } IAuthorizator authorizator = null; String authorizatorClassName = props.getProperty(Constants.AUTHORIZATOR_CLASS_NAME, ""); if (!authorizatorClassName.isEmpty()) { authorizator = (IAuthorizator)loadClass(authorizatorClassName, IAuthorizator.class); LOG.info("Loaded custom authorizator {}", authorizatorClassName); } if (authorizator == null) { String aclFilePath = props.getProperty(ACL_FILE_PROPERTY_NAME, ""); if (aclFilePath != null && !aclFilePath.isEmpty()) { authorizator = new DenyAllAuthorizator(); File aclFile = new File(configPath, aclFilePath); try { authorizator = ACLFileParser.parse(aclFile); } catch (ParseException pex) { LOG.error(String.format("Format error in parsing acl file %s", aclFile), pex); } LOG.info("Using acl file defined at path {}", aclFilePath); } else { authorizator = new PermitAllAuthorizator(); LOG.info("Starting without ACL definition"); } } boolean allowAnonymous = Boolean.parseBoolean(props.getProperty(ALLOW_ANONYMOUS_PROPERTY_NAME, "true")); m_processor.init(subscriptions, messagesStore, sessionsStore, authenticator, allowAnonymous, authorizator, m_interceptor); return m_processor; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleConnect(IoSession session, ConnectMessage msg) { LOG.info("handleConnect invoked"); if (msg.getProcotolVersion() != 0x03) { ConnAckMessage badProto = new ConnAckMessage(); badProto.setReturnCode(ConnAckMessage.UNNACEPTABLE_PROTOCOL_VERSION); session.write(badProto); session.close(false); return; } if (msg.getClientID() == null || msg.getClientID().length() > 23) { ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.IDENTIFIER_REJECTED); session.write(okResp); return; } m_clientIDsLock.lock(); try { //if an old client with the same ID already exists close its session. if (m_clientIDs.containsKey(msg.getClientID())) { //clean the subscriptions if the old used a cleanSession = true IoSession oldSession = m_clientIDs.get(msg.getClientID()).getSession(); boolean cleanSession = (Boolean) oldSession.getAttribute(Constants.CLEAN_SESSION); if (cleanSession) { //cleanup topic subscriptions m_messaging.removeSubscriptions(msg.getClientID()); } m_clientIDs.get(msg.getClientID()).getSession().close(false); } ConnectionDescriptor connDescr = new ConnectionDescriptor(msg.getClientID(), session, msg.isCleanSession()); m_clientIDs.put(msg.getClientID(), connDescr); } finally { m_clientIDsLock.unlock(); } int keepAlive = msg.getKeepAlive(); session.setAttribute("keepAlive", keepAlive); session.setAttribute(Constants.CLEAN_SESSION, msg.isCleanSession()); //used to track the client in the subscription and publishing phases. session.setAttribute(Constants.ATTR_CLIENTID, msg.getClientID()); session.getConfig().setIdleTime(IdleStatus.READER_IDLE, Math.round(keepAlive * 1.5f)); //Handle will flag if (msg.isWillFlag()) { QOSType willQos = QOSType.values()[msg.getWillQos()]; m_messaging.publish(msg.getWillTopic(), msg.getWillMessage().getBytes(), willQos, msg.isWillRetain(), msg.getClientID(), session); } //handle user authentication if (msg.isUserFlag()) { String pwd = null; if (msg.isPasswordFlag()) { pwd = msg.getPassword(); } if (!m_authenticator.checkValid(msg.getUsername(), pwd)) { ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.BAD_USERNAME_OR_PASSWORD); session.write(okResp); return; } } //handle clean session flag if (msg.isCleanSession()) { //remove all prev subscriptions //cleanup topic subscriptions m_messaging.removeSubscriptions(msg.getClientID()); } else { //force the republish of stored QoS1 and QoS2 m_messaging.republishStored(msg.getClientID()); } ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.CONNECTION_ACCEPTED); session.write(okResp); } #location 60 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleConnect(IoSession session, ConnectMessage msg) { LOG.info("handleConnect invoked"); m_messaging.connect(session, msg); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPublishWithQoS2() throws Exception { LOG.info("*** testPublishWithQoS2 ***"); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); m_client.connect(options); m_client.subscribe("/topic", 2); m_client.disconnect(); //publish a QoS 1 message another client publish a message on the topic publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 2); m_callback.reinit(); m_client.connect(options); assertEquals("Hello MQTT", m_callback.getMessage().toString()); assertEquals(2, m_callback.getMessage().getQos()); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPublishWithQoS2() throws Exception { LOG.info("*** testPublishWithQoS2 ***"); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); m_client.connect(options); m_client.subscribe("/topic", 2); m_client.disconnect(); //publish a QoS 1 message another client publish a message on the topic publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 2); m_callback.reinit(); m_client.connect(options); MqttMessage message = m_callback.getMessage(true); assertEquals("Hello MQTT", message.toString()); assertEquals(2, message.getQos()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleDisconnect(IoSession session, DisconnectMessage disconnectMessage) { String clientID = (String) session.getAttribute(ATTR_CLIENTID); //remove from clientIDs m_clientIDsLock.lock(); try { m_clientIDs.remove(clientID); } finally { m_clientIDsLock.unlock(); } boolean cleanSession = (Boolean) session.getAttribute("cleanSession"); if (cleanSession) { //cleanup topic subscriptions m_messaging.removeSubscriptions(clientID); } //close the TCP connection session.close(true); } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleDisconnect(IoSession session, DisconnectMessage disconnectMessage) { String clientID = (String) session.getAttribute(ATTR_CLIENTID); //remove from clientIDs // m_clientIDsLock.lock(); // try { // m_clientIDs.remove(clientID); // } finally { // m_clientIDsLock.unlock(); // } boolean cleanSession = (Boolean) session.getAttribute("cleanSession"); if (cleanSession) { //cleanup topic subscriptions m_messaging.removeSubscriptions(clientID); } //close the TCP connection //session.close(true); m_messaging.disconnect(session); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void removeSubscription(String topic, String clientID) { TreeNode matchNode = findMatchingNode(topic); //search for the subscription to remove Subscription toBeRemoved = null; for (Subscription sub : matchNode.subscriptions()) { if (sub.topicFilter.equals(topic) && sub.getClientId().equals(clientID)) { toBeRemoved = sub; break; } } if (toBeRemoved != null) { matchNode.subscriptions().remove(toBeRemoved); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public void removeSubscription(String topic, String clientID) { TreeNode oldRoot; NodeCouple couple; do { oldRoot = subscriptions.get(); couple = recreatePath(topic, oldRoot); //do the job //search for the subscription to remove Subscription toBeRemoved = null; for (Subscription sub : couple.createdNode.subscriptions()) { if (sub.topicFilter.equals(topic) && sub.getClientId().equals(clientID)) { toBeRemoved = sub; break; } } if (toBeRemoved != null) { couple.createdNode.subscriptions().remove(toBeRemoved); } //spin lock repeating till we can, swap root, if can't swap just re-do the operation } while(!subscriptions.compareAndSet(oldRoot, couple.root)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleConnect(IoSession session, ConnectMessage msg) { LOG.info("handleConnect invoked"); if (msg.getProcotolVersion() != 0x03) { ConnAckMessage badProto = new ConnAckMessage(); badProto.setReturnCode(ConnAckMessage.UNNACEPTABLE_PROTOCOL_VERSION); session.write(badProto); session.close(false); return; } if (msg.getClientID() == null || msg.getClientID().length() > 23) { ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.IDENTIFIER_REJECTED); session.write(okResp); return; } m_clientIDsLock.lock(); try { //if an old client with the same ID already exists close its session. if (m_clientIDs.containsKey(msg.getClientID())) { //clean the subscriptions if the old used a cleanSession = true IoSession oldSession = m_clientIDs.get(msg.getClientID()).getSession(); boolean cleanSession = (Boolean) oldSession.getAttribute(Constants.CLEAN_SESSION); if (cleanSession) { //cleanup topic subscriptions m_messaging.removeSubscriptions(msg.getClientID()); } m_clientIDs.get(msg.getClientID()).getSession().close(false); } ConnectionDescriptor connDescr = new ConnectionDescriptor(msg.getClientID(), session, msg.isCleanSession()); m_clientIDs.put(msg.getClientID(), connDescr); } finally { m_clientIDsLock.unlock(); } int keepAlive = msg.getKeepAlive(); session.setAttribute("keepAlive", keepAlive); session.setAttribute(Constants.CLEAN_SESSION, msg.isCleanSession()); //used to track the client in the subscription and publishing phases. session.setAttribute(Constants.ATTR_CLIENTID, msg.getClientID()); session.getConfig().setIdleTime(IdleStatus.READER_IDLE, Math.round(keepAlive * 1.5f)); //Handle will flag if (msg.isWillFlag()) { QOSType willQos = QOSType.values()[msg.getWillQos()]; m_messaging.publish(msg.getWillTopic(), msg.getWillMessage().getBytes(), willQos, msg.isWillRetain(), msg.getClientID(), session); } //handle user authentication if (msg.isUserFlag()) { String pwd = null; if (msg.isPasswordFlag()) { pwd = msg.getPassword(); } if (!m_authenticator.checkValid(msg.getUsername(), pwd)) { ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.BAD_USERNAME_OR_PASSWORD); session.write(okResp); return; } } //handle clean session flag if (msg.isCleanSession()) { //remove all prev subscriptions //cleanup topic subscriptions m_messaging.removeSubscriptions(msg.getClientID()); } else { //force the republish of stored QoS1 and QoS2 m_messaging.republishStored(msg.getClientID()); } ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.CONNECTION_ACCEPTED); session.write(okResp); } #location 75 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleConnect(IoSession session, ConnectMessage msg) { LOG.info("handleConnect invoked"); m_messaging.connect(session, msg); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void processInit(Properties props) { benchmarkEnabled = Boolean.parseBoolean(System.getProperty("moquette.processor.benchmark", "false")); //TODO use a property to select the storage path MapDBPersistentStore mapStorage = new MapDBPersistentStore(props.getProperty(PERSISTENT_STORE_PROPERTY_NAME, "")); m_storageService = mapStorage; m_sessionsStore = mapStorage; m_storageService.initStore(); //List<Subscription> storedSubscriptions = m_sessionsStore.listAllSubscriptions(); //subscriptions.init(storedSubscriptions); subscriptions.init(m_sessionsStore); String passwdPath = props.getProperty(PASSWORD_FILE_PROPERTY_NAME, ""); String configPath = System.getProperty("moquette.path", null); IAuthenticator authenticator; if (passwdPath.isEmpty()) { authenticator = new AcceptAllAuthenticator(); } else { authenticator = new FileAuthenticator(configPath, passwdPath); } String aclFilePath = props.getProperty(ACL_FILE_PROPERTY_NAME, ""); IAuthorizator authorizator; if (aclFilePath != null && !aclFilePath.isEmpty()) { authorizator = new DenyAllAuthorizator(); File aclFile = new File(configPath, aclFilePath); try { authorizator = ACLFileParser.parse(aclFile); } catch (ParseException pex) { LOG.error(String.format("Format error in parsing acl file %s", aclFile), pex); } LOG.info("Using acl file defined at path {}", aclFilePath); } else { authorizator = new PermitAllAuthorizator(); LOG.info("Starting without ACL definition"); } boolean allowAnonymous = Boolean.parseBoolean(props.getProperty(ALLOW_ANONYMOUS_PROPERTY_NAME, "true")); m_processor.init(subscriptions, m_storageService, m_sessionsStore, authenticator, allowAnonymous, authorizator); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code private void processInit(Properties props) { benchmarkEnabled = Boolean.parseBoolean(System.getProperty("moquette.processor.benchmark", "false")); //TODO use a property to select the storage path MapDBPersistentStore mapStorage = new MapDBPersistentStore(props.getProperty(PERSISTENT_STORE_PROPERTY_NAME, "")); m_storageService = mapStorage; m_sessionsStore = mapStorage; m_storageService.initStore(); //List<Subscription> storedSubscriptions = m_sessionsStore.listAllSubscriptions(); //subscriptions.init(storedSubscriptions); subscriptions.init(m_sessionsStore); IAuthenticator authenticator = null; String configPath = System.getProperty("moquette.path", null); String authenticatorClassName = props.getProperty(Constants.AUTHENTICATOR_CLASS_NAME, ""); if(!authenticatorClassName.isEmpty()) { try { authenticator = this.getClass().getClassLoader() .loadClass(authenticatorClassName) .asSubclass(IAuthenticator.class) .newInstance(); LOG.info("Loaded custom authenticator {}", authenticatorClassName); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) { LOG.error("Cannot load custom authenticator class " + authenticatorClassName, ex); } } if(authenticator == null) { String passwdPath = props.getProperty(PASSWORD_FILE_PROPERTY_NAME, ""); if (passwdPath.isEmpty()) { authenticator = new AcceptAllAuthenticator(); } else { authenticator = new FileAuthenticator(configPath, passwdPath); } } IAuthorizator authorizator = null; String authorizatorClassName = props.getProperty(Constants.AUTHORIZATOR_CLASS_NAME, ""); if(!authorizatorClassName.isEmpty()) { try { authorizator = this.getClass().getClassLoader() .loadClass(authorizatorClassName) .asSubclass(IAuthorizator.class) .newInstance(); LOG.info("Loaded custom authorizator {}", authorizatorClassName); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) { LOG.error("Cannot load custom authorizator class " + authenticatorClassName, ex); } } if(authorizator == null) { String aclFilePath = props.getProperty(ACL_FILE_PROPERTY_NAME, ""); if (aclFilePath != null && !aclFilePath.isEmpty()) { authorizator = new DenyAllAuthorizator(); File aclFile = new File(configPath, aclFilePath); try { authorizator = ACLFileParser.parse(aclFile); } catch (ParseException pex) { LOG.error(String.format("Format error in parsing acl file %s", aclFile), pex); } LOG.info("Using acl file defined at path {}", aclFilePath); } else { authorizator = new PermitAllAuthorizator(); LOG.info("Starting without ACL definition"); } } boolean allowAnonymous = Boolean.parseBoolean(props.getProperty(ALLOW_ANONYMOUS_PROPERTY_NAME, "true")); m_processor.init(subscriptions, m_storageService, m_sessionsStore, authenticator, allowAnonymous, authorizator); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static GitRepositoryState getGitRepositoryState() throws IOException { Properties properties = new Properties(); try { properties.load(new FileInputStream("config/git.properties")); } catch (IOException e) { } GitRepositoryState gitRepositoryState = new GitRepositoryState(properties); return gitRepositoryState; } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public static GitRepositoryState getGitRepositoryState() throws IOException { Properties properties = new Properties(); try { InputStream inputStream = new FileInputStream("config/git.properties"); BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream)); properties.load(bf); } catch (IOException e) { } GitRepositoryState gitRepositoryState = new GitRepositoryState(properties); return gitRepositoryState; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException { startServer(config, handlers, null); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException { startServer(config, handlers, null, null, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public WFCMessage.PullMessageResult fetchChatroomMessage(String fromUser, String chatroomId, String exceptClientId, long fromMessageId) { WFCMessage.PullMessageResult.Builder builder = WFCMessage.PullMessageResult.newBuilder(); HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); IMap<Long, MessageBundle> mIMap = hzInstance.getMap(MESSAGES_MAP); long head = fromMessageId; long current = fromMessageId; TreeMap<Long, Long> maps = chatroomMessages.get(chatroomId); if (maps == null) { mWriteLock.lock(); try { maps = chatroomMessages.get(chatroomId); if (maps == null) { maps = new TreeMap<>(); chatroomMessages.put(chatroomId, maps); } } finally { mWriteLock.unlock(); } } mReadLock.lock(); int size = 0; try { maps = chatroomMessages.get(chatroomId); while (true) { Map.Entry<Long, Long> entry = maps.higherEntry(current); if (entry == null) { break; } current = entry.getKey(); long targetMessageId = entry.getValue(); MessageBundle bundle = mIMap.get(targetMessageId); if (bundle == null) { bundle = databaseStore.getMessage(targetMessageId); } if (bundle != null) { if (exceptClientId == null || !exceptClientId.equals(bundle.getFromClientId()) || !fromUser.equals(bundle.getFromUser())) { size += bundle.getMessage().getSerializedSize(); if (size >= 3 * 1024 * 1024) { //3M break; } builder.addMessage(bundle.getMessage()); } } } Map.Entry<Long, Long> lastEntry = maps.lastEntry(); if (lastEntry != null) { head = lastEntry.getKey(); } } finally { mReadLock.unlock(); } builder.setCurrent(current); builder.setHead(head); return builder.build(); } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public WFCMessage.PullMessageResult fetchChatroomMessage(String fromUser, String chatroomId, String exceptClientId, long fromMessageId) { WFCMessage.PullMessageResult.Builder builder = WFCMessage.PullMessageResult.newBuilder(); HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); IMap<Long, MessageBundle> mIMap = hzInstance.getMap(MESSAGES_MAP); long head = fromMessageId; long current = fromMessageId; TreeMap<Long, Long> maps = chatroomMessages.get(chatroomId); if (maps == null) { mWriteLock.lock(); try { maps = chatroomMessages.get(chatroomId); if (maps == null) { maps = new TreeMap<>(); chatroomMessages.put(chatroomId, maps); } } finally { mWriteLock.unlock(); } } mReadLock.lock(); int size = 0; try { maps = chatroomMessages.get(chatroomId); while (true) { Map.Entry<Long, Long> entry = maps.higherEntry(current); if (entry == null) { break; } current = entry.getKey(); long targetMessageId = entry.getValue(); MessageBundle bundle = mIMap.get(targetMessageId); if (bundle != null) { if (exceptClientId == null || !exceptClientId.equals(bundle.getFromClientId()) || !fromUser.equals(bundle.getFromUser())) { size += bundle.getMessage().getSerializedSize(); if (size >= 3 * 1024 * 1024) { //3M break; } builder.addMessage(bundle.getMessage()); } } } Map.Entry<Long, Long> lastEntry = maps.lastEntry(); if (lastEntry != null) { head = lastEntry.getKey(); } } finally { mReadLock.unlock(); } builder.setCurrent(current); builder.setHead(head); return builder.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1() throws Exception { LOG.info("*** avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1, issue #16 ***"); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); m_client.connect(options); m_client.subscribe("/topic", 1); m_client.disconnect(); publishFromAnotherClient("/topic", "Hello MQTT 1".getBytes(), 1); m_callback.reinit(); m_client.connect(options); assertNotNull(m_callback); assertNotNull(m_callback.getMessage()); assertEquals("Hello MQTT 1", m_callback.getMessage().toString()); m_client.disconnect(); //publish other message publishFromAnotherClient("/topic", "Hello MQTT 2".getBytes(), 1); //reconnect the second time m_callback.reinit(); m_client.connect(options); assertNotNull(m_callback); assertNotNull(m_callback.getMessage()); assertEquals("Hello MQTT 2", m_callback.getMessage().toString()); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1() throws Exception { LOG.info("*** avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1, issue #16 ***"); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); m_client.connect(options); m_client.subscribe("/topic", 1); m_client.disconnect(); publishFromAnotherClient("/topic", "Hello MQTT 1".getBytes(), 1); m_callback.reinit(); m_client.connect(options); assertNotNull(m_callback); MqttMessage message = m_callback.getMessage(true); assertNotNull(message); assertEquals("Hello MQTT 1", message.toString()); m_client.disconnect(); //publish other message publishFromAnotherClient("/topic", "Hello MQTT 2".getBytes(), 1); //reconnect the second time m_callback.reinit(); m_client.connect(options); assertNotNull(m_callback); message = m_callback.getMessage(true); assertNotNull(message); assertEquals("Hello MQTT 2", message.toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int getNotifyReceivers(String fromUser, WFCMessage.Message.Builder messageBuilder, Set<String> notifyReceivers, boolean ignoreMsg) { WFCMessage.Message message = messageBuilder.build(); HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); int type = message.getConversation().getType(); int pullType = ProtoConstants.PullType.Pull_Normal; if (ignoreMsg) { if (type == ProtoConstants.ConversationType.ConversationType_ChatRoom) { pullType = ProtoConstants.PullType.Pull_ChatRoom; } if (message.getContent().getPersistFlag() != Transparent) { notifyReceivers.add(fromUser); } return pullType; } if (type == ProtoConstants.ConversationType.ConversationType_Private) { notifyReceivers.add(fromUser); notifyReceivers.add(message.getConversation().getTarget()); pullType = ProtoConstants.PullType.Pull_Normal; } else if (type == ProtoConstants.ConversationType.ConversationType_Group) { notifyReceivers.add(fromUser); if (!StringUtil.isNullOrEmpty(message.getToUser())) { notifyReceivers.add(message.getToUser()); } else if(message.getToList()!=null && !message.getToList().isEmpty()) { MultiMap<String, WFCMessage.GroupMember> groupMembers = hzInstance.getMultiMap(GROUP_MEMBERS); Collection<WFCMessage.GroupMember> members = groupMembers.get(message.getConversation().getTarget()); if (members == null || members.size() == 0) { members = loadGroupMemberFromDB(hzInstance, message.getConversation().getTarget()); } for (WFCMessage.GroupMember member : members) { if (member.getType() != GroupMemberType_Removed && message.getToList().contains(member.getMemberId())) { notifyReceivers.add(member.getMemberId()); } } } else { MultiMap<String, WFCMessage.GroupMember> groupMembers = hzInstance.getMultiMap(GROUP_MEMBERS); Collection<WFCMessage.GroupMember> members = groupMembers.get(message.getConversation().getTarget()); if (members == null || members.size() == 0) { members = loadGroupMemberFromDB(hzInstance, message.getConversation().getTarget()); } for (WFCMessage.GroupMember member : members) { if (member.getType() != GroupMemberType_Removed) { notifyReceivers.add(member.getMemberId()); } } } //如果是群助手的消息,返回pull type group,否则返回normal //群助手还没有实现 pullType = ProtoConstants.PullType.Pull_Normal; } else if (type == ProtoConstants.ConversationType.ConversationType_ChatRoom) { boolean isDirect = !StringUtil.isNullOrEmpty(message.getToUser()); Collection<UserClientEntry> entries = getChatroomMembers(message.getConversation().getTarget()); for (UserClientEntry entry : entries) { if (isDirect) { if (entry.userId.equals(message.getToUser())) { notifyReceivers.add(message.getToUser()); break; } } else { notifyReceivers.add(entry.userId); } } pullType = ProtoConstants.PullType.Pull_ChatRoom; } else if(type == ProtoConstants.ConversationType.ConversationType_Channel) { WFCMessage.ChannelInfo channelInfo = getChannelInfo(message.getConversation().getTarget()); if (channelInfo != null) { notifyReceivers.add(fromUser); if (channelInfo.getOwner().equals(fromUser)) { MultiMap<String, String> listeners = hzInstance.getMultiMap(CHANNEL_LISTENERS); if (!StringUtil.isNullOrEmpty(message.getToUser())) { if (listeners.values().contains(message.getToUser())) { notifyReceivers.add(message.getToUser()); } } else if(message.getToList() != null && !message.getToList().isEmpty()) { Collection<String> ls = listeners.get(message.getConversation().getTarget()); for (String to:message.getToList()) { if (ls.contains(to)) { notifyReceivers.add(to); } } } else { notifyReceivers.addAll(listeners.get(message.getConversation().getTarget())); } } else { if (StringUtil.isNullOrEmpty(channelInfo.getCallback()) || channelInfo.getAutomatic() == 0) { notifyReceivers.add(channelInfo.getOwner()); } } } else { LOG.error("Channel not exist"); } } if (message.getContent().getPersistFlag() == Transparent) { notifyReceivers.remove(fromUser); } return pullType; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int getNotifyReceivers(String fromUser, WFCMessage.Message.Builder messageBuilder, Set<String> notifyReceivers, boolean ignoreMsg) { WFCMessage.Message message = messageBuilder.build(); HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); int type = message.getConversation().getType(); int pullType = ProtoConstants.PullType.Pull_Normal; if (ignoreMsg) { if (type == ProtoConstants.ConversationType.ConversationType_ChatRoom) { pullType = ProtoConstants.PullType.Pull_ChatRoom; } if (message.getContent().getPersistFlag() != Transparent) { notifyReceivers.add(fromUser); } return pullType; } if (type == ProtoConstants.ConversationType.ConversationType_Private) { notifyReceivers.add(fromUser); notifyReceivers.add(message.getConversation().getTarget()); pullType = ProtoConstants.PullType.Pull_Normal; } else if (type == ProtoConstants.ConversationType.ConversationType_Group) { notifyReceivers.add(fromUser); if (!StringUtil.isNullOrEmpty(message.getToUser())) { notifyReceivers.add(message.getToUser()); } else if(message.getToList()!=null && !message.getToList().isEmpty()) { MultiMap<String, WFCMessage.GroupMember> groupMembers = hzInstance.getMultiMap(GROUP_MEMBERS); Collection<WFCMessage.GroupMember> members = groupMembers.get(message.getConversation().getTarget()); if (members == null || members.size() == 0) { members = loadGroupMemberFromDB(hzInstance, message.getConversation().getTarget()); } for (WFCMessage.GroupMember member : members) { if (member.getType() != GroupMemberType_Removed && message.getToList().contains(member.getMemberId())) { notifyReceivers.add(member.getMemberId()); } } } else { MultiMap<String, WFCMessage.GroupMember> groupMembers = hzInstance.getMultiMap(GROUP_MEMBERS); Collection<WFCMessage.GroupMember> members = groupMembers.get(message.getConversation().getTarget()); if (members == null || members.size() == 0) { members = loadGroupMemberFromDB(hzInstance, message.getConversation().getTarget()); } for (WFCMessage.GroupMember member : members) { if (member.getType() != GroupMemberType_Removed) { notifyReceivers.add(member.getMemberId()); } } } //如果是群助手的消息,返回pull type group,否则返回normal //群助手还没有实现 pullType = ProtoConstants.PullType.Pull_Normal; } else if (type == ProtoConstants.ConversationType.ConversationType_ChatRoom) { boolean isDirect = !StringUtil.isNullOrEmpty(message.getToUser()); Collection<UserClientEntry> entries = getChatroomMembers(message.getConversation().getTarget()); for (UserClientEntry entry : entries) { if (isDirect) { if (entry.userId.equals(message.getToUser())) { notifyReceivers.add(message.getToUser()); break; } } else { notifyReceivers.add(entry.userId); } } pullType = ProtoConstants.PullType.Pull_ChatRoom; } else if(type == ProtoConstants.ConversationType.ConversationType_Channel) { WFCMessage.ChannelInfo channelInfo = getChannelInfo(message.getConversation().getTarget()); if (channelInfo != null) { notifyReceivers.add(fromUser); if (channelInfo.getOwner().equals(fromUser)) { Collection<String> listeners = getChannelListener(message.getConversation().getTarget()); if (!StringUtil.isNullOrEmpty(message.getToUser())) { if (listeners.contains(message.getToUser())) { notifyReceivers.add(message.getToUser()); } } else if(message.getToList() != null && !message.getToList().isEmpty()) { for (String to:message.getToList()) { if (listeners.contains(to)) { notifyReceivers.add(to); } } } else { notifyReceivers.addAll(listeners); } } else { if (StringUtil.isNullOrEmpty(channelInfo.getCallback()) || channelInfo.getAutomatic() == 0) { notifyReceivers.add(channelInfo.getOwner()); } } } else { LOG.error("Channel not exist"); } } if (message.getContent().getPersistFlag() == Transparent) { notifyReceivers.remove(fromUser); } return pullType; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void checkWillMessageIsWiredOnClientKeepAliveExpiry() throws Exception { LOG.info("*** checkWillMessageIsWiredOnClientKeepAliveExpiry ***"); String willTestamentTopic = "/will/test"; String willTestamentMsg = "Bye bye"; m_willSubscriber.connect(); m_willSubscriber.subscribe(willTestamentTopic, 0); int keepAlive = 2; //secs ConnectMessage connectMessage = new ConnectMessage(); connectMessage.setProtocolVersion((byte) 3); connectMessage.setClientID("FAKECLNT"); connectMessage.setKeepAlive(keepAlive); connectMessage.setWillFlag(true); connectMessage.setWillMessage(willTestamentMsg.getBytes()); connectMessage.setWillTopic(willTestamentTopic); connectMessage.setWillQos(QOSType.MOST_ONE.byteValue()); //Execute m_client.sendMessage(connectMessage); long connectTime = System.currentTimeMillis(); //but after the 2 KEEP ALIVE timeout expires it gets fired, //NB it's 1,5 * KEEP_ALIVE so 3 secs and some millis to propagate the message MqttMessage msg = m_messageCollector.getMessage(3300); long willMessageReceiveTime = System.currentTimeMillis(); if (msg == null) { LOG.warn("testament message is null"); } assertNotNull("the will message should be fired after keep alive!", msg); //the will message hasn't to be received before the elapsing of Keep Alive timeout assertTrue(willMessageReceiveTime - connectTime > 3000); assertEquals(willTestamentMsg, new String(msg.getPayload())); m_willSubscriber.disconnect(); } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void checkWillMessageIsWiredOnClientKeepAliveExpiry() throws Exception { LOG.info("*** checkWillMessageIsWiredOnClientKeepAliveExpiry ***"); String willTestamentTopic = "/will/test"; String willTestamentMsg = "Bye bye"; m_willSubscriber.connect(); m_willSubscriber.subscribe(willTestamentTopic, 0); connect(willTestamentTopic, willTestamentMsg); long connectTime = System.currentTimeMillis(); //but after the 2 KEEP ALIVE timeout expires it gets fired, //NB it's 1,5 * KEEP_ALIVE so 3 secs and some millis to propagate the message MqttMessage msg = m_messageCollector.getMessage(3300); long willMessageReceiveTime = System.currentTimeMillis(); assertNotNull("the will message should be fired after keep alive!", msg); //the will message hasn't to be received before the elapsing of Keep Alive timeout assertTrue(willMessageReceiveTime - connectTime > 3000); assertEquals(willTestamentMsg, new String(msg.getPayload())); m_willSubscriber.disconnect(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public WFCMessage.Message getMessage(long messageId) { HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); IMap<Long, MessageBundle> mIMap = hzInstance.getMap(MESSAGES_MAP); MessageBundle bundle = mIMap.get(messageId); if (bundle != null) { return bundle.getMessage(); } else { bundle = databaseStore.getMessage(messageId); if (bundle != null) return bundle.getMessage(); } return null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public WFCMessage.Message getMessage(long messageId) { HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); IMap<Long, MessageBundle> mIMap = hzInstance.getMap(MESSAGES_MAP); MessageBundle bundle = mIMap.get(messageId); if (bundle != null) { return bundle.getMessage(); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { NettyChannel channel = m_channelMapper.get(ctx); String clientID = (String) channel.getAttribute(NettyChannel.ATTR_KEY_CLIENTID); m_messaging.lostConnection(channel, clientID); ctx.close(/*false*/); synchronized(m_channelMapper) { m_channelMapper.remove(ctx); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { // NettyChannel channel = m_channelMapper.get(ctx); // String clientID = (String) channel.getAttribute(NettyChannel.ATTR_KEY_CLIENTID); String clientID = (String) NettyUtils.getAttribute(ctx, NettyChannel.ATTR_KEY_CLIENTID); m_messaging.lostConnection(clientID); ctx.close(/*false*/); // synchronized(m_channelMapper) { // m_channelMapper.remove(ctx); // } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPublishReceiveWithQoS2() throws Exception { LOG.info("*** testPublishReceiveWithQoS2 ***"); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); m_client.connect(options); m_client.subscribe("/topic", 2); m_client.disconnect(); //publish a QoS 2 message another client publish a message on the topic publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 2); m_callback.reinit(); m_client.connect(options); assertNotNull(m_callback); assertNotNull(m_callback.getMessage()); assertEquals("Hello MQTT", m_callback.getMessage().toString()); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPublishReceiveWithQoS2() throws Exception { LOG.info("*** testPublishReceiveWithQoS2 ***"); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); m_client.connect(options); m_client.subscribe("/topic", 2); m_client.disconnect(); //publish a QoS 2 message another client publish a message on the topic publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 2); m_callback.reinit(); m_client.connect(options); assertNotNull(m_callback); MqttMessage message = m_callback.getMessage(true); assertNotNull(message); assertEquals("Hello MQTT", message.toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator) throws IOException { LOG.info("Initializing Netty acceptor..."); nettySoBacklog = Integer.parseInt(props.getProperty(BrokerConstants.NETTY_SO_BACKLOG_PROPERTY_NAME, "128")); nettySoReuseaddr = Boolean .parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_REUSEADDR_PROPERTY_NAME, "true")); nettyTcpNodelay = Boolean .parseBoolean(props.getProperty(BrokerConstants.NETTY_TCP_NODELAY_PROPERTY_NAME, "true")); nettySoKeepalive = Boolean .parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_KEEPALIVE_PROPERTY_NAME, "true")); nettyChannelTimeoutSeconds = Integer .parseInt(props.getProperty(BrokerConstants.NETTY_CHANNEL_TIMEOUT_SECONDS_PROPERTY_NAME, "10")); boolean epoll = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_EPOLL_PROPERTY_NAME, "false")); if (epoll) { // 由于目前只支持TCP MQTT, 所以bossGroup的线程数配置为1 LOG.info("Netty is using Epoll"); m_bossGroup = new EpollEventLoopGroup(1); m_workerGroup = new EpollEventLoopGroup(); channelClass = EpollServerSocketChannel.class; } else { LOG.info("Netty is using NIO"); m_bossGroup = new NioEventLoopGroup(1); m_workerGroup = new NioEventLoopGroup(); channelClass = NioServerSocketChannel.class; } final NettyMQTTHandler mqttHandler = new NettyMQTTHandler(processor); final boolean useFineMetrics = Boolean.parseBoolean(props.getProperty(METRICS_ENABLE_PROPERTY_NAME, "false")); if (useFineMetrics) { DropWizardMetricsHandler metricsHandler = new DropWizardMetricsHandler(); metricsHandler.init(props); this.metrics = Optional.of(metricsHandler); } else { this.metrics = Optional.empty(); } final boolean useBugSnag = Boolean.parseBoolean(props.getProperty(BUGSNAG_ENABLE_PROPERTY_NAME, "false")); if (useBugSnag) { BugSnagErrorsHandler bugSnagHandler = new BugSnagErrorsHandler(); bugSnagHandler.init(props); this.errorsCather = Optional.of(bugSnagHandler); } else { this.errorsCather = Optional.empty(); } initializePlainTCPTransport(mqttHandler, props); initializeWebSocketTransport(mqttHandler, props); String sslTcpPortProp = props.getProperty(BrokerConstants.SSL_PORT_PROPERTY_NAME); String wssPortProp = props.getProperty(BrokerConstants.WSS_PORT_PROPERTY_NAME); if (sslTcpPortProp != null || wssPortProp != null) { SSLContext sslContext = sslCtxCreator.initSSLContext(); if (sslContext == null) { LOG.error("Can't initialize SSLHandler layer! Exiting, check your configuration of jks"); return; } initializeSSLTCPTransport(mqttHandler, props, sslContext); initializeWSSTransport(mqttHandler, props, sslContext); } } #location 45 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator) throws IOException { LOG.info("Initializing Netty acceptor..."); nettySoBacklog = Integer.parseInt(props.getProperty(BrokerConstants.NETTY_SO_BACKLOG_PROPERTY_NAME, "128")); nettySoReuseaddr = Boolean .parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_REUSEADDR_PROPERTY_NAME, "true")); nettyTcpNodelay = Boolean .parseBoolean(props.getProperty(BrokerConstants.NETTY_TCP_NODELAY_PROPERTY_NAME, "true")); nettySoKeepalive = Boolean .parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_KEEPALIVE_PROPERTY_NAME, "true")); nettyChannelTimeoutSeconds = Integer .parseInt(props.getProperty(BrokerConstants.NETTY_CHANNEL_TIMEOUT_SECONDS_PROPERTY_NAME, "10")); boolean epoll = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_EPOLL_PROPERTY_NAME, "false")); if (epoll) { // 由于目前只支持TCP MQTT, 所以bossGroup的线程数配置为1 LOG.info("Netty is using Epoll"); m_bossGroup = new EpollEventLoopGroup(1); m_workerGroup = new EpollEventLoopGroup(); channelClass = EpollServerSocketChannel.class; } else { LOG.info("Netty is using NIO"); m_bossGroup = new NioEventLoopGroup(1); m_workerGroup = new NioEventLoopGroup(); channelClass = NioServerSocketChannel.class; } final NettyMQTTHandler mqttHandler = new NettyMQTTHandler(processor); final boolean useFineMetrics = Boolean.parseBoolean(props.getProperty(METRICS_ENABLE_PROPERTY_NAME, "false")); if (useFineMetrics) { DropWizardMetricsHandler metricsHandler = new DropWizardMetricsHandler(); metricsHandler.init(props); this.metrics = Optional.of(metricsHandler); } else { this.metrics = Optional.empty(); } this.errorsCather = Optional.empty(); initializePlainTCPTransport(mqttHandler, props); initializeWebSocketTransport(mqttHandler, props); String sslTcpPortProp = props.getProperty(BrokerConstants.SSL_PORT_PROPERTY_NAME); String wssPortProp = props.getProperty(BrokerConstants.WSS_PORT_PROPERTY_NAME); if (sslTcpPortProp != null || wssPortProp != null) { SSLContext sslContext = sslCtxCreator.initSSLContext(); if (sslContext == null) { LOG.error("Can't initialize SSLHandler layer! Exiting, check your configuration of jks"); return; } initializeSSLTCPTransport(mqttHandler, props, sslContext); initializeWSSTransport(mqttHandler, props, sslContext); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public WFCMessage.PullMessageResult fetchMessage(String user, String exceptClientId, long fromMessageId, int pullType) { WFCMessage.PullMessageResult.Builder builder = WFCMessage.PullMessageResult.newBuilder(); HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); IMap<Long, MessageBundle> mIMap = hzInstance.getMap(MESSAGES_MAP); MemorySessionStore.Session session = m_Server.getStore().sessionsStore().getSession(exceptClientId); session.refreshLastActiveTime(); if (pullType != ProtoConstants.PullType.Pull_ChatRoom) { session.setUnReceivedMsgs(0); } else { session.refreshLastChatroomActiveTime(); } String chatroomId = null; if (pullType == ProtoConstants.PullType.Pull_ChatRoom) { chatroomId = (String)m_Server.getHazelcastInstance().getMap(USER_CHATROOM).get(user); } long head = fromMessageId; long current = fromMessageId; TreeMap<Long, Long> maps; if (pullType != ProtoConstants.PullType.Pull_ChatRoom) { maps = userMessages.get(user); if (maps == null) { loadUserMessages(user); } maps = userMessages.get(user); } else { maps = chatroomMessages.get(user); if (maps == null) { mWriteLock.lock(); try { maps = chatroomMessages.get(user); if (maps == null) { maps = new TreeMap<>(); chatroomMessages.put(user, maps); } } finally { mWriteLock.unlock(); } } } mReadLock.lock(); int size = 0; try { if (pullType != ProtoConstants.PullType.Pull_ChatRoom) { userMaxPullSeq.compute(user, (s, aLong) -> { if (aLong == null || aLong < fromMessageId) { return fromMessageId; } else { return aLong; } }); } while (true) { Map.Entry<Long, Long> entry = maps.higherEntry(current); if (entry == null) { break; } current = entry.getKey(); long targetMessageId = entry.getValue(); MessageBundle bundle = mIMap.get(targetMessageId); if (bundle == null) { bundle = databaseStore.getMessage(targetMessageId); } if (bundle != null) { if (exceptClientId == null || !exceptClientId.equals(bundle.getFromClientId()) || !user.equals(bundle.getFromUser())) { if (pullType == ProtoConstants.PullType.Pull_ChatRoom) { if (!bundle.getMessage().getConversation().getTarget().equals(chatroomId)) { continue; } } size += bundle.getMessage().getSerializedSize(); if (size >= 1 * 1024 * 1024) { //3M break; } builder.addMessage(bundle.getMessage()); } } } Map.Entry<Long, Long> lastEntry = maps.lastEntry(); if (lastEntry != null) { head = lastEntry.getKey(); } } finally { mReadLock.unlock(); } builder.setCurrent(current); builder.setHead(head); return builder.build(); } #location 72 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public WFCMessage.PullMessageResult fetchMessage(String user, String exceptClientId, long fromMessageId, int pullType) { WFCMessage.PullMessageResult.Builder builder = WFCMessage.PullMessageResult.newBuilder(); HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); IMap<Long, MessageBundle> mIMap = hzInstance.getMap(MESSAGES_MAP); MemorySessionStore.Session session = m_Server.getStore().sessionsStore().getSession(exceptClientId); session.refreshLastActiveTime(); if (pullType != ProtoConstants.PullType.Pull_ChatRoom) { session.setUnReceivedMsgs(0); } else { session.refreshLastChatroomActiveTime(); } String chatroomId = null; if (pullType == ProtoConstants.PullType.Pull_ChatRoom) { chatroomId = (String)m_Server.getHazelcastInstance().getMap(USER_CHATROOM).get(user); } long head = fromMessageId; long current = fromMessageId; TreeMap<Long, Long> maps; if (pullType != ProtoConstants.PullType.Pull_ChatRoom) { maps = userMessages.get(user); if (maps == null) { loadUserMessages(user); } maps = userMessages.get(user); } else { maps = chatroomMessages.get(user); if (maps == null) { mWriteLock.lock(); try { maps = chatroomMessages.get(user); if (maps == null) { maps = new TreeMap<>(); chatroomMessages.put(user, maps); } } finally { mWriteLock.unlock(); } } } mReadLock.lock(); int size = 0; try { if (pullType != ProtoConstants.PullType.Pull_ChatRoom) { userMaxPullSeq.compute(user, (s, aLong) -> { if (aLong == null || aLong < fromMessageId) { return fromMessageId; } else { return aLong; } }); } while (true) { Map.Entry<Long, Long> entry = maps.higherEntry(current); if (entry == null) { break; } current = entry.getKey(); long targetMessageId = entry.getValue(); MessageBundle bundle = mIMap.get(targetMessageId); if (bundle != null) { if (exceptClientId == null || !exceptClientId.equals(bundle.getFromClientId()) || !user.equals(bundle.getFromUser())) { if (pullType == ProtoConstants.PullType.Pull_ChatRoom) { if (!bundle.getMessage().getConversation().getTarget().equals(chatroomId)) { continue; } } size += bundle.getMessage().getSerializedSize(); if (size >= 1 * 1024 * 1024) { //3M break; } builder.addMessage(bundle.getMessage()); } } } Map.Entry<Long, Long> lastEntry = maps.lastEntry(); if (lastEntry != null) { head = lastEntry.getKey(); } } finally { mReadLock.unlock(); } builder.setCurrent(current); builder.setHead(head); return builder.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRead(ChannelHandlerContext ctx, Object message) { AbstractMessage msg = (AbstractMessage) message; LOG.info("Received a message of type {}", Utils.msgType2String(msg.getMessageType())); try { switch (msg.getMessageType()) { case CONNECT: case SUBSCRIBE: case UNSUBSCRIBE: case PUBLISH: case PUBREC: case PUBCOMP: case PUBREL: case DISCONNECT: case PUBACK: NettyChannel channel; synchronized(m_channelMapper) { if (!m_channelMapper.containsKey(ctx)) { m_channelMapper.put(ctx, new NettyChannel(ctx)); } channel = m_channelMapper.get(ctx); } m_messaging.handleProtocolMessage(channel, msg); break; case PINGREQ: PingRespMessage pingResp = new PingRespMessage(); ctx.writeAndFlush(pingResp); break; } } catch (Exception ex) { LOG.error("Bad error in processing the message", ex); } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void channelRead(ChannelHandlerContext ctx, Object message) { AbstractMessage msg = (AbstractMessage) message; LOG.info("Received a message of type {}", Utils.msgType2String(msg.getMessageType())); try { switch (msg.getMessageType()) { case CONNECT: case SUBSCRIBE: case UNSUBSCRIBE: case PUBLISH: case PUBREC: case PUBCOMP: case PUBREL: case DISCONNECT: case PUBACK: // NettyChannel channel; // synchronized(m_channelMapper) { // if (!m_channelMapper.containsKey(ctx)) { // m_channelMapper.put(ctx, new NettyChannel(ctx)); // } // channel = m_channelMapper.get(ctx); // } m_messaging.handleProtocolMessage(new NettyChannel(ctx), msg); break; case PINGREQ: PingRespMessage pingResp = new PingRespMessage(); ctx.writeAndFlush(pingResp); break; } } catch (Exception ex) { LOG.error("Bad error in processing the message", ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ErrorCode handleFriendRequest(String userId, WFCMessage.HandleFriendRequest request, WFCMessage.Message.Builder msgBuilder, long[] heads, boolean isAdmin) { HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); if (isAdmin) { MultiMap<String, FriendData> friendsMap = hzInstance.getMultiMap(USER_FRIENDS); FriendData friendData1 = null; Collection<FriendData> friendDatas = friendsMap.get(userId); if (friendDatas == null || friendDatas.size() == 0) { friendDatas = loadFriend(friendsMap, userId); } for (FriendData fd : friendDatas) { if (fd.getFriendUid().equals(request.getTargetUid())) { friendData1 = fd; break; } } if (friendData1 == null) { friendData1 = new FriendData(userId, request.getTargetUid(), "", request.getStatus(), System.currentTimeMillis()); } else { friendData1.setState(request.getStatus()); friendData1.setTimestamp(System.currentTimeMillis()); } databaseStore.persistOrUpdateFriendData(friendData1); if (request.getStatus() != 2) { FriendData friendData2 = null; friendDatas = friendsMap.get(request.getTargetUid()); for (FriendData fd : friendDatas) { if (fd.getFriendUid().equals(userId)) { friendData2 = fd; break; } } if (friendData2 == null) { friendData2 = new FriendData(request.getTargetUid(), userId, "", request.getStatus(), friendData1.getTimestamp()); } else { friendsMap.remove(request.getTargetUid(), friendData2); friendData2.setState(request.getStatus()); friendData2.setTimestamp(System.currentTimeMillis()); } databaseStore.persistOrUpdateFriendData(friendData2); heads[0] = friendData2.getTimestamp(); } else { heads[0] = 0; } heads[1] = friendData1.getTimestamp(); friendsMap.remove(userId); friendsMap.remove(request.getTargetUid()); return ErrorCode.ERROR_CODE_SUCCESS; } MultiMap<String, WFCMessage.FriendRequest> requestMap = hzInstance.getMultiMap(USER_FRIENDS_REQUEST); Collection<WFCMessage.FriendRequest> requests = requestMap.get(userId); if (requests == null || requests.size() == 0) { requests = databaseStore.getPersistFriendRequests(userId); if (requests != null) { for (WFCMessage.FriendRequest r : requests ) { requestMap.put(userId, r); } } } WFCMessage.FriendRequest existRequest = null; for (WFCMessage.FriendRequest tmpRequest : requests) { if (tmpRequest.getFromUid().equals(request.getTargetUid())) { existRequest = tmpRequest; break; } } if (existRequest != null) { if (System.currentTimeMillis() - existRequest.getUpdateDt() > 7 * 24 * 60 * 60 * 1000) { return ErrorCode.ERROR_CODE_FRIEND_REQUEST_OVERTIME; } else { existRequest = existRequest.toBuilder().setStatus(ProtoConstants.FriendRequestStatus.RequestStatus_Accepted).setUpdateDt(System.currentTimeMillis()).build(); databaseStore.persistOrUpdateFriendRequest(existRequest); MultiMap<String, FriendData> friendsMap = hzInstance.getMultiMap(USER_FRIENDS); FriendData friendData1 = new FriendData(userId, request.getTargetUid(), "", 0, System.currentTimeMillis()); databaseStore.persistOrUpdateFriendData(friendData1); FriendData friendData2 = new FriendData(request.getTargetUid(), userId, "", 0, friendData1.getTimestamp()); databaseStore.persistOrUpdateFriendData(friendData2); requestMap.remove(userId); requestMap.remove(request.getTargetUid()); friendsMap.remove(userId); friendsMap.remove(request.getTargetUid()); heads[0] = friendData2.getTimestamp(); heads[1] = friendData1.getTimestamp(); msgBuilder.setConversation(WFCMessage.Conversation.newBuilder().setTarget(userId).setLine(0).setType(ProtoConstants.ConversationType.ConversationType_Private).build()); msgBuilder.setContent(WFCMessage.MessageContent.newBuilder().setType(1).setSearchableContent(existRequest.getReason()).build()); return ErrorCode.ERROR_CODE_SUCCESS; } } else { return ErrorCode.ERROR_CODE_NOT_EXIST; } } #location 71 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ErrorCode handleFriendRequest(String userId, WFCMessage.HandleFriendRequest request, WFCMessage.Message.Builder msgBuilder, long[] heads, boolean isAdmin) { HazelcastInstance hzInstance = m_Server.getHazelcastInstance(); if (isAdmin) { MultiMap<String, FriendData> friendsMap = hzInstance.getMultiMap(USER_FRIENDS); FriendData friendData1 = null; Collection<FriendData> friendDatas = friendsMap.get(userId); if (friendDatas == null || friendDatas.size() == 0) { friendDatas = loadFriend(friendsMap, userId); } for (FriendData fd : friendDatas) { if (fd.getFriendUid().equals(request.getTargetUid())) { friendData1 = fd; break; } } if (friendData1 == null) { friendData1 = new FriendData(userId, request.getTargetUid(), "", request.getStatus(), System.currentTimeMillis()); } else { friendData1.setState(request.getStatus()); friendData1.setTimestamp(System.currentTimeMillis()); } databaseStore.persistOrUpdateFriendData(friendData1); if (request.getStatus() != 2) { FriendData friendData2 = null; friendDatas = friendsMap.get(request.getTargetUid()); if (friendDatas == null || friendDatas.size() == 0) { friendDatas = loadFriend(friendsMap, request.getTargetUid()); } for (FriendData fd : friendDatas) { if (fd.getFriendUid().equals(userId)) { friendData2 = fd; break; } } if (friendData2 == null) { friendData2 = new FriendData(request.getTargetUid(), userId, "", request.getStatus(), friendData1.getTimestamp()); } else { friendsMap.remove(request.getTargetUid(), friendData2); friendData2.setState(request.getStatus()); friendData2.setTimestamp(System.currentTimeMillis()); } databaseStore.persistOrUpdateFriendData(friendData2); heads[0] = friendData2.getTimestamp(); } else { heads[0] = 0; } heads[1] = friendData1.getTimestamp(); friendsMap.remove(userId); friendsMap.remove(request.getTargetUid()); return ErrorCode.ERROR_CODE_SUCCESS; } MultiMap<String, WFCMessage.FriendRequest> requestMap = hzInstance.getMultiMap(USER_FRIENDS_REQUEST); Collection<WFCMessage.FriendRequest> requests = requestMap.get(userId); if (requests == null || requests.size() == 0) { requests = loadFriendRequest(requestMap, userId); } WFCMessage.FriendRequest existRequest = null; for (WFCMessage.FriendRequest tmpRequest : requests) { if (tmpRequest.getFromUid().equals(request.getTargetUid())) { existRequest = tmpRequest; break; } } if (existRequest != null) { if (System.currentTimeMillis() - existRequest.getUpdateDt() > 7 * 24 * 60 * 60 * 1000) { return ErrorCode.ERROR_CODE_FRIEND_REQUEST_OVERTIME; } else { existRequest = existRequest.toBuilder().setStatus(ProtoConstants.FriendRequestStatus.RequestStatus_Accepted).setUpdateDt(System.currentTimeMillis()).build(); databaseStore.persistOrUpdateFriendRequest(existRequest); MultiMap<String, FriendData> friendsMap = hzInstance.getMultiMap(USER_FRIENDS); FriendData friendData1 = new FriendData(userId, request.getTargetUid(), "", 0, System.currentTimeMillis()); databaseStore.persistOrUpdateFriendData(friendData1); FriendData friendData2 = new FriendData(request.getTargetUid(), userId, "", 0, friendData1.getTimestamp()); databaseStore.persistOrUpdateFriendData(friendData2); requestMap.remove(userId); requestMap.remove(request.getTargetUid()); friendsMap.remove(userId); friendsMap.remove(request.getTargetUid()); heads[0] = friendData2.getTimestamp(); heads[1] = friendData1.getTimestamp(); msgBuilder.setConversation(WFCMessage.Conversation.newBuilder().setTarget(userId).setLine(0).setType(ProtoConstants.ConversationType.ConversationType_Private).build()); msgBuilder.setContent(WFCMessage.MessageContent.newBuilder().setType(1).setSearchableContent(existRequest.getReason()).build()); return ErrorCode.ERROR_CODE_SUCCESS; } } else { return ErrorCode.ERROR_CODE_NOT_EXIST; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { m_startMillis = System.currentTimeMillis(); MQTT mqtt = new MQTT(); try { // mqtt.setHost("test.mosquitto.org", 1883); mqtt.setHost("localhost", 1883); } catch (URISyntaxException ex) { LOG.error(null, ex); return; } mqtt.setClientId(m_clientID); BlockingConnection connection = mqtt.blockingConnection(); try { connection.connect(); } catch (Exception ex) { LOG.error("Cant't CONNECT to the server", ex); return; } long time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s connected in %d ms", Thread.currentThread().getName(), time)); m_startMillis = System.currentTimeMillis(); for (int i = m_starIndex; i < m_starIndex + m_len; i++) { try { // LOG.info("Publishing"); String payload = "Hello world MQTT!!" + i; connection.publish("/topic", payload.getBytes(), QoS.AT_MOST_ONCE, false); m_benchMarkOut.println(String.format("%d, %d", i, System.nanoTime())); } catch (Exception ex) { LOG.error("Cant't PUBLISH to the server", ex); return; } } time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s published %d messages in %d ms", Thread.currentThread().getName(), m_len, time)); m_startMillis = System.currentTimeMillis(); try { LOG.info("Disconneting"); connection.disconnect(); LOG.info("Disconnected"); } catch (Exception ex) { LOG.error("Cant't DISCONNECT to the server", ex); } time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s disconnected in %d ms", Thread.currentThread().getName(), time)); m_benchMarkOut.close(); try { FileWriter fw = new FileWriter(BENCHMARK_FILE); fw.write(m_baos.toString()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } #location 56 #vulnerability type RESOURCE_LEAK
#fixed code public void run() { m_startMillis = System.currentTimeMillis(); MQTT mqtt = new MQTT(); try { // mqtt.setHost("test.mosquitto.org", 1883); mqtt.setHost("localhost", 1883); } catch (URISyntaxException ex) { LOG.error(null, ex); return; } mqtt.setClientId(m_clientID); BlockingConnection connection = mqtt.blockingConnection(); try { connection.connect(); } catch (Exception ex) { LOG.error("Cant't CONNECT to the server", ex); return; } long time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s connected in %d ms", Thread.currentThread().getName(), time)); LOG.info("Starting from index " + m_starIndex + " up to " + (m_starIndex + m_len)); m_startMillis = System.currentTimeMillis(); for (int i = m_starIndex; i < m_starIndex + m_len; i++) { try { // LOG.info("Publishing"); String payload = "Hello world MQTT!!" + i; connection.publish("/topic", payload.getBytes(), QoS.AT_MOST_ONCE, false); m_benchMarkOut.println(String.format("%d, %d", i, System.nanoTime())); } catch (Exception ex) { LOG.error("Cant't PUBLISH to the server", ex); return; } } time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s published %d messages in %d ms", Thread.currentThread().getName(), m_len, time)); m_startMillis = System.currentTimeMillis(); try { LOG.info("Disconneting"); connection.disconnect(); LOG.info("Disconnected"); } catch (Exception ex) { LOG.error("Cant't DISCONNECT to the server", ex); } time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s disconnected in %d ms", Thread.currentThread().getName(), time)); m_benchMarkOut.flush(); m_benchMarkOut.close(); try { FileOutputStream fw = new FileOutputStream(String.format(BENCHMARK_FILE, m_clientID)); fw.write(m_baos.toByteArray()); fw.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testLazyLoading() throws Exception { final AtomicBoolean requestWasSent = new AtomicBoolean(false); TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public void sendRequest(URL url, Session session) { requestWasSent.set(true); assertThat(url, is(locationUrl)); } @Override public JSON readJsonResponse() { return getJSON("updateAuthorizationResponse"); } @Override public void handleRetryAfter(String message) throws AcmeException { // Just do nothing } }; Login login = provider.createLogin(); provider.putTestChallenge("http-01", Http01Challenge::new); provider.putTestChallenge("dns-01", Dns01Challenge::new); Authorization auth = new Authorization(login, locationUrl); // Lazy loading assertThat(requestWasSent.get(), is(false)); assertThat(auth.getDomain(), is("example.org")); assertThat(requestWasSent.get(), is(true)); // Subsequent queries do not trigger another load requestWasSent.set(false); assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is(Status.VALID)); assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); assertThat(requestWasSent.get(), is(false)); provider.close(); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testLazyLoading() throws Exception { final AtomicBoolean requestWasSent = new AtomicBoolean(false); TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public void sendRequest(URL url, Session session) { requestWasSent.set(true); assertThat(url, is(locationUrl)); } @Override public JSON readJsonResponse() { return getJSON("updateAuthorizationResponse"); } @Override public void handleRetryAfter(String message) throws AcmeException { // Just do nothing } }; Login login = provider.createLogin(); provider.putTestChallenge("http-01", Http01Challenge::new); provider.putTestChallenge("dns-01", Dns01Challenge::new); Authorization auth = new Authorization(login, locationUrl); // Lazy loading assertThat(requestWasSent.get(), is(false)); assertThat(auth.getDomain(), is("example.org")); assertThat(requestWasSent.get(), is(true)); // Subsequent queries do not trigger another load requestWasSent.set(false); assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is(Status.VALID)); assertThat(auth.isWildcard(), is(false)); assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); assertThat(requestWasSent.get(), is(false)); provider.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRestoreChallenge() throws AcmeException { Connection connection = new DummyConnection() { @Override public int sendRequest(URI uri) throws AcmeException { assertThat(uri, is(locationUri)); return HttpURLConnection.HTTP_ACCEPTED; } @Override public Map<String, Object> readJsonResponse() throws AcmeException { return getJsonAsMap("updateHttpChallengeResponse"); } }; TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); client.putTestChallenge(Http01Challenge.TYPE, new Http01Challenge()); Challenge challenge = client.restoreChallenge(locationUri); assertThat(challenge.getStatus(), is(Status.VALID)); assertThat(challenge.getLocation(), is(locationUri)); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testRestoreChallenge() throws AcmeException { Connection connection = new DummyConnection() { @Override public int sendRequest(URI uri) { assertThat(uri, is(locationUri)); return HttpURLConnection.HTTP_ACCEPTED; } @Override public Map<String, Object> readJsonResponse() { return getJsonAsMap("updateHttpChallengeResponse"); } }; TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); client.putTestChallenge(Http01Challenge.TYPE, new Http01Challenge()); Challenge challenge = client.restoreChallenge(locationUri); assertThat(challenge.getStatus(), is(Status.VALID)); assertThat(challenge.getLocation(), is(locationUri)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Challenge> fetchChallenges(JSON json) { JSON.Array jsonChallenges = json.get("challenges").asArray(); List<Challenge> cr = new ArrayList<>(); for (JSON.Value c : jsonChallenges) { Challenge ch = getSession().createChallenge(c.asObject()); if (ch != null) { cr.add(ch); } } return cr; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private List<Challenge> fetchChallenges(JSON json) { Session session = getSession(); return Collections.unmodifiableList(json.get("challenges").asArray().stream() .map(JSON.Value::asObject) .map(session::createChallenge) .collect(toList())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNewAuthorization() throws AcmeException { Authorization auth = new Authorization(); auth.setDomain("example.org"); Connection connection = new DummyConnection() { @Override public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { assertThat(uri, is(resourceUri)); assertThat(claims.toString(), sameJSONAs(getJson("newAuthorizationRequest"))); assertThat(session, is(notNullValue())); assertThat(account, is(sameInstance(testAccount))); return HttpURLConnection.HTTP_CREATED; } @Override public Map<String, Object> readJsonResponse() throws AcmeException { return getJsonAsMap("newAuthorizationResponse"); } }; HttpChallenge httpChallenge = new HttpChallenge(); DnsChallenge dnsChallenge = new DnsChallenge(); TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); client.putTestResource(Resource.NEW_AUTHZ, resourceUri); client.putTestChallenge("http-01", httpChallenge); client.putTestChallenge("dns-01", dnsChallenge); client.newAuthorization(testAccount, auth); assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is("pending")); assertThat(auth.getExpires(), is(nullValue())); assertThat(auth.getChallenges(), containsInAnyOrder( (Challenge) httpChallenge, (Challenge) dnsChallenge)); assertThat(auth.getCombinations(), hasSize(2)); assertThat(auth.getCombinations().get(0), containsInAnyOrder( (Challenge) httpChallenge)); assertThat(auth.getCombinations().get(1), containsInAnyOrder( (Challenge) httpChallenge, (Challenge) dnsChallenge)); } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNewAuthorization() throws AcmeException { Authorization auth = new Authorization(); auth.setDomain("example.org"); Connection connection = new DummyConnection() { @Override public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { assertThat(uri, is(resourceUri)); assertThat(claims.toString(), sameJSONAs(getJson("newAuthorizationRequest"))); assertThat(session, is(notNullValue())); assertThat(account, is(sameInstance(testAccount))); return HttpURLConnection.HTTP_CREATED; } @Override public Map<String, Object> readJsonResponse() throws AcmeException { return getJsonAsMap("newAuthorizationResponse"); } @Override public URI getLocation() throws AcmeException { return locationUri; } }; HttpChallenge httpChallenge = new HttpChallenge(); DnsChallenge dnsChallenge = new DnsChallenge(); TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); client.putTestResource(Resource.NEW_AUTHZ, resourceUri); client.putTestChallenge("http-01", httpChallenge); client.putTestChallenge("dns-01", dnsChallenge); client.newAuthorization(testAccount, auth); assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is("pending")); assertThat(auth.getExpires(), is(nullValue())); assertThat(auth.getLocation(), is(locationUri)); assertThat(auth.getChallenges(), containsInAnyOrder( (Challenge) httpChallenge, (Challenge) dnsChallenge)); assertThat(auth.getCombinations(), hasSize(2)); assertThat(auth.getCombinations().get(0), containsInAnyOrder( (Challenge) httpChallenge)); assertThat(auth.getCombinations().get(1), containsInAnyOrder( (Challenge) httpChallenge, (Challenge) dnsChallenge)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testUpdate() throws Exception { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public void sendRequest(URL url, Session session) { assertThat(url, is(locationUrl)); } @Override public int accept(int... httpStatus) throws AcmeException { assertThat(httpStatus, isIntArrayContainingInAnyOrder(HttpURLConnection.HTTP_OK)); return HttpURLConnection.HTTP_OK; } @Override public JSON readJsonResponse() { return getJSON("updateAuthorizationResponse"); } @Override public void handleRetryAfter(String message) throws AcmeException { // Just do nothing } }; Session session = provider.createSession(); Http01Challenge httpChallenge = new Http01Challenge(session); Dns01Challenge dnsChallenge = new Dns01Challenge(session); provider.putTestChallenge("http-01", httpChallenge); provider.putTestChallenge("dns-01", dnsChallenge); Authorization auth = new Authorization(session, locationUrl); auth.update(); assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is(Status.VALID)); assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); assertThat(auth.getLocation(), is(locationUrl)); assertThat(auth.getScope().getLocation(), is(url("https://example.com/order/123"))); assertThat(auth.getChallenges(), containsInAnyOrder( (Challenge) httpChallenge, (Challenge) dnsChallenge)); provider.close(); } #location 40 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testUpdate() throws Exception { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public void sendRequest(URL url, Session session) { assertThat(url, is(locationUrl)); } @Override public int accept(int... httpStatus) throws AcmeException { assertThat(httpStatus, isIntArrayContainingInAnyOrder(HttpURLConnection.HTTP_OK)); return HttpURLConnection.HTTP_OK; } @Override public JSON readJsonResponse() { return getJSON("updateAuthorizationResponse"); } @Override public void handleRetryAfter(String message) throws AcmeException { // Just do nothing } }; Session session = provider.createSession(); Http01Challenge httpChallenge = new Http01Challenge(session); Dns01Challenge dnsChallenge = new Dns01Challenge(session); provider.putTestChallenge("http-01", httpChallenge); provider.putTestChallenge("dns-01", dnsChallenge); Authorization auth = new Authorization(session, locationUrl); auth.update(); assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is(Status.VALID)); assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); assertThat(auth.getLocation(), is(locationUrl)); assertThat(auth.getChallenges(), containsInAnyOrder( (Challenge) httpChallenge, (Challenge) dnsChallenge)); provider.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Challenge> fetchChallenges(JSON json) { JSON.Array jsonChallenges = json.get("challenges").asArray(); List<Challenge> cr = new ArrayList<>(); for (JSON.Value c : jsonChallenges) { Challenge ch = getSession().createChallenge(c.asObject()); if (ch != null) { cr.add(ch); } } return cr; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private List<Challenge> fetchChallenges(JSON json) { Session session = getSession(); return Collections.unmodifiableList(json.get("challenges").asArray().stream() .map(JSON.Value::asObject) .map(session::createChallenge) .collect(toList())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAuthorizeBadDomain() throws Exception { TestableConnectionProvider provider = new TestableConnectionProvider(); Session session = provider.createSession(); Registration registration = Registration.bind(session, locationUrl); try { registration.authorizeDomain(null); fail("null domain was accepted"); } catch (NullPointerException ex) { // expected } try { registration.authorizeDomain(""); fail("empty domain string was accepted"); } catch (IllegalArgumentException ex) { // expected } provider.close(); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAuthorizeBadDomain() throws Exception { TestableConnectionProvider provider = new TestableConnectionProvider(); // just provide a resource record so the provider returns a directory provider.putTestResource(Resource.NEW_NONCE, resourceUrl); Session session = provider.createSession(); Registration registration = Registration.bind(session, locationUrl); try { registration.preAuthorizeDomain(null); fail("null domain was accepted"); } catch (NullPointerException ex) { // expected } try { registration.preAuthorizeDomain(""); fail("empty domain string was accepted"); } catch (IllegalArgumentException ex) { // expected } try { registration.preAuthorizeDomain("example.com"); fail("preauthorization was accepted"); } catch (AcmeException ex) { // expected assertThat(ex.getMessage(), is("Server does not allow pre-authorization")); } provider.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSendRequest() throws Exception { when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.sendRequest(requestUrl, session); } verify(mockUrlConnection).setRequestMethod("GET"); verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setDoOutput(false); verify(mockUrlConnection).connect(); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSendRequest() throws Exception { when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public String getNonce() { return null; } }) { conn.sendRequest(requestUrl, session); } verify(mockUrlConnection).setRequestMethod("GET"); verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setDoOutput(false); verify(mockUrlConnection).connect(); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testUpdateRetryAfter() throws Exception { final Instant retryAfter = Instant.now().plus(Duration.ofSeconds(30)); TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public void sendRequest(URL url, Session session) { assertThat(url, is(locationUrl)); } @Override public JSON readJsonResponse() { return getJSON("updateAuthorizationResponse"); } @Override public void handleRetryAfter(String message) throws AcmeException { throw new AcmeRetryAfterException(message, retryAfter); } }; Login login = provider.createLogin(); provider.putTestChallenge("http-01", Http01Challenge::new); provider.putTestChallenge("dns-01", Dns01Challenge::new); Authorization auth = new Authorization(login, locationUrl); try { auth.update(); fail("Expected AcmeRetryAfterException"); } catch (AcmeRetryAfterException ex) { assertThat(ex.getRetryAfter(), is(retryAfter)); } assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is(Status.VALID)); assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); assertThat(auth.getLocation(), is(locationUrl)); assertThat(auth.getChallenges(), containsInAnyOrder( provider.getChallenge(Http01Challenge.TYPE), provider.getChallenge(Dns01Challenge.TYPE))); provider.close(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testUpdateRetryAfter() throws Exception { final Instant retryAfter = Instant.now().plus(Duration.ofSeconds(30)); TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public void sendRequest(URL url, Session session) { assertThat(url, is(locationUrl)); } @Override public JSON readJsonResponse() { return getJSON("updateAuthorizationResponse"); } @Override public void handleRetryAfter(String message) throws AcmeException { throw new AcmeRetryAfterException(message, retryAfter); } }; Login login = provider.createLogin(); provider.putTestChallenge("http-01", Http01Challenge::new); provider.putTestChallenge("dns-01", Dns01Challenge::new); Authorization auth = new Authorization(login, locationUrl); try { auth.update(); fail("Expected AcmeRetryAfterException"); } catch (AcmeRetryAfterException ex) { assertThat(ex.getRetryAfter(), is(retryAfter)); } assertThat(auth.getDomain(), is("example.org")); assertThat(auth.getStatus(), is(Status.VALID)); assertThat(auth.isWildcard(), is(false)); assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); assertThat(auth.getLocation(), is(locationUrl)); assertThat(auth.getChallenges(), containsInAnyOrder( provider.getChallenge(Http01Challenge.TYPE), provider.getChallenge(Dns01Challenge.TYPE))); provider.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSendCertificateRequest() throws Exception { when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.sendCertificateRequest(requestUrl, session); } verify(mockUrlConnection).setRequestMethod("GET"); verify(mockUrlConnection).setRequestProperty("Accept", "application/pem-certificate-chain"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setDoOutput(false); verify(mockUrlConnection).connect(); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSendCertificateRequest() throws Exception { final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public void resetNonce(Session session) { assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); if (session.getNonce() == null) { session.setNonce(nonce1); } else { fail("unknown nonce"); } } @Override public String getNonce() { assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); if (session.getNonce() == nonce1) { return nonce2; } else { fail("unknown nonce"); return null; } } }) { conn.sendCertificateRequest(requestUrl, login); } verify(mockUrlConnection).setRequestMethod("POST"); verify(mockUrlConnection).setRequestProperty("Accept", "application/pem-certificate-chain"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); verify(mockUrlConnection).setDoOutput(true); verify(mockUrlConnection).connect(); verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection).getOutputStream(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testArray() { JSON json = TestUtils.getJsonAsObject("json"); JSON.Array array = json.get("array").asArray(); assertThat(array.size(), is(4)); assertThat(array.get(0), is(notNullValue())); assertThat(array.get(1), is(notNullValue())); assertThat(array.get(2), is(notNullValue())); assertThat(array.get(3), is(notNullValue())); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testArray() { JSON json = TestUtils.getJsonAsObject("json"); JSON.Array array = json.get("array").asArray(); assertThat(array.size(), is(4)); assertThat(array.isEmpty(), is(false)); assertThat(array.get(0), is(notNullValue())); assertThat(array.get(1), is(notNullValue())); assertThat(array.get(2), is(notNullValue())); assertThat(array.get(3), is(notNullValue())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void throwAcmeException() throws AcmeException { try { String contentType = AcmeUtils.getContentType(conn.getHeaderField(CONTENT_TYPE_HEADER)); if (!"application/problem+json".equals(contentType)) { throw new AcmeException("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage()); } Problem problem = new Problem(readJsonResponse(), conn.getURL()); if (problem.getType() == null) { throw new AcmeException(problem.getDetail()); } String error = AcmeUtils.stripErrorPrefix(problem.getType().toString()); if ("unauthorized".equals(error)) { throw new AcmeUnauthorizedException(problem); } if ("userActionRequired".equals(error)) { URI tos = collectLinks("terms-of-service").stream() .findFirst() .map(this::resolveUri) .orElse(null); throw new AcmeUserActionRequiredException(problem, tos); } if ("rateLimited".equals(error)) { Optional<Instant> retryAfter = getRetryAfterHeader(); Collection<URL> rateLimits = getLinks("urn:ietf:params:acme:documentation"); throw new AcmeRateLimitedException(problem, retryAfter.orElse(null), rateLimits); } throw new AcmeServerException(problem); } catch (IOException ex) { throw new AcmeNetworkException(ex); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code private void throwAcmeException() throws AcmeException { try { String contentType = AcmeUtils.getContentType(conn.getHeaderField(CONTENT_TYPE_HEADER)); if (!"application/problem+json".equals(contentType)) { throw new AcmeException("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage()); } JSON problemJson = readJsonResponse(); if (problemJson == null) { throw new AcmeProtocolException("Empty problem response"); } Problem problem = new Problem(problemJson, conn.getURL()); String error = AcmeUtils.stripErrorPrefix(problem.getType().toString()); if ("unauthorized".equals(error)) { throw new AcmeUnauthorizedException(problem); } if ("userActionRequired".equals(error)) { URI tos = collectLinks("terms-of-service").stream() .findFirst() .map(this::resolveUri) .orElse(null); throw new AcmeUserActionRequiredException(problem, tos); } if ("rateLimited".equals(error)) { Optional<Instant> retryAfter = getRetryAfterHeader(); Collection<URL> rateLimits = getLinks("urn:ietf:params:acme:documentation"); throw new AcmeRateLimitedException(problem, retryAfter.orElse(null), rateLimits); } throw new AcmeServerException(problem); } catch (IOException ex) { throw new AcmeNetworkException(ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSendRequest() throws Exception { when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.sendRequest(requestUrl, session); } verify(mockUrlConnection).setRequestMethod("GET"); verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setDoOutput(false); verify(mockUrlConnection).connect(); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSendRequest() throws Exception { when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public String getNonce() { return null; } }) { conn.sendRequest(requestUrl, session); } verify(mockUrlConnection).setRequestMethod("GET"); verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setDoOutput(false); verify(mockUrlConnection).connect(); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private AcmeException createAcmeException(Problem problem) { if (problem.getType() == null) { return new AcmeException(problem.getDetail()); } String error = AcmeUtils.stripErrorPrefix(problem.getType().toString()); if ("unauthorized".equals(error)) { return new AcmeUnauthorizedException(problem); } if ("userActionRequired".equals(error)) { URI tos = getLinks("terms-of-service").stream().findFirst().orElse(null); return new AcmeUserActionRequiredException(problem, tos); } if ("rateLimited".equals(error)) { Optional<Instant> retryAfter = getRetryAfterHeader(); Collection<URI> rateLimits = getLinks("urn:ietf:params:acme:documentation"); return new AcmeRateLimitExceededException(problem, retryAfter.orElse(null), rateLimits); } return new AcmeServerException(problem); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code private AcmeException createAcmeException(Problem problem) { if (problem.getType() == null) { return new AcmeException(problem.getDetail()); } String error = AcmeUtils.stripErrorPrefix(problem.getType().toString()); if ("unauthorized".equals(error)) { return new AcmeUnauthorizedException(problem); } if ("userActionRequired".equals(error)) { Collection<URI> links = getLinks("terms-of-service"); URI tos = links != null ? links.stream().findFirst().orElse(null) : null; return new AcmeUserActionRequiredException(problem, tos); } if ("rateLimited".equals(error)) { Optional<Instant> retryAfter = getRetryAfterHeader(); Collection<URI> rateLimits = getLinks("urn:ietf:params:acme:documentation"); return new AcmeRateLimitExceededException(problem, retryAfter.orElse(null), rateLimits); } return new AcmeServerException(problem); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public AcmeProvider provider() { synchronized (this) { if (provider == null) { List<AcmeProvider> candidates = new ArrayList<>(); for (AcmeProvider acp : ServiceLoader.load(AcmeProvider.class)) { if (acp.accepts(serverUri)) { candidates.add(acp); } } if (candidates.isEmpty()) { throw new IllegalArgumentException("No ACME provider found for " + serverUri); } else if (candidates.size() > 1) { throw new IllegalStateException("There are " + candidates.size() + " " + AcmeProvider.class.getSimpleName() + " accepting " + serverUri + ". Please check your classpath."); } else { provider = candidates.get(0); } } } return provider; } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public AcmeProvider provider() { return provider; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSendCertificateRequest() throws Exception { when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.sendCertificateRequest(requestUrl, session); } verify(mockUrlConnection).setRequestMethod("GET"); verify(mockUrlConnection).setRequestProperty("Accept", "application/pem-certificate-chain"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setDoOutput(false); verify(mockUrlConnection).connect(); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSendCertificateRequest() throws Exception { final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public void resetNonce(Session session) { assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); if (session.getNonce() == null) { session.setNonce(nonce1); } else { fail("unknown nonce"); } } @Override public String getNonce() { assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); if (session.getNonce() == nonce1) { return nonce2; } else { fail("unknown nonce"); return null; } } }) { conn.sendCertificateRequest(requestUrl, login); } verify(mockUrlConnection).setRequestMethod("POST"); verify(mockUrlConnection).setRequestProperty("Accept", "application/pem-certificate-chain"); verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); verify(mockUrlConnection).setDoOutput(true); verify(mockUrlConnection).connect(); verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); verify(mockUrlConnection).getResponseCode(); verify(mockUrlConnection).getOutputStream(); verify(mockUrlConnection, atLeast(0)).getHeaderFields(); verifyNoMoreInteractions(mockUrlConnection); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int accept(int... httpStatus) throws AcmeException { assertConnectionIsOpen(); try { int rc = conn.getResponseCode(); OptionalInt match = Arrays.stream(httpStatus).filter(s -> s == rc).findFirst(); if (match.isPresent()) { return match.getAsInt(); } if (!"application/problem+json".equals(conn.getHeaderField(CONTENT_TYPE_HEADER))) { throw new AcmeException("HTTP " + rc + ": " + conn.getResponseMessage()); } JSON json = readJsonResponse(); if (rc == HttpURLConnection.HTTP_CONFLICT) { throw new AcmeConflictException(json.get("detail").asString(), getLocation()); } throw createAcmeException(json); } catch (IOException ex) { throw new AcmeNetworkException(ex); } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public int accept(int... httpStatus) throws AcmeException { assertConnectionIsOpen(); try { int rc = conn.getResponseCode(); OptionalInt match = Arrays.stream(httpStatus).filter(s -> s == rc).findFirst(); if (match.isPresent()) { return match.getAsInt(); } if (!"application/problem+json".equals(conn.getHeaderField(CONTENT_TYPE_HEADER))) { throw new AcmeException("HTTP " + rc + ": " + conn.getResponseMessage()); } throw createAcmeException(readJsonResponse()); } catch (IOException ex) { throw new AcmeNetworkException(ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException { HttpURLConnection conn = super.openConnection(url, proxy); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setSSLSocketFactory(createSocketFactory()); } return conn; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Override public HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException { HttpURLConnection conn = super.openConnection(url, proxy); if (conn instanceof HttpsURLConnection) { HttpsURLConnection conns = (HttpsURLConnection) conn; conns.setSSLSocketFactory(createSocketFactory()); conns.setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER); } return conn; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Registration registration) throws AcmeException { if (uri == null) { throw new NullPointerException("uri must not be null"); } if (claims == null) { throw new NullPointerException("claims must not be null"); } if (session == null) { throw new NullPointerException("session must not be null"); } if (registration == null) { throw new NullPointerException("registration must not be null"); } if (conn != null) { throw new IllegalStateException("Connection was not closed. Race condition?"); } try { KeyPair keypair = registration.getKeyPair(); if (session.getNonce() == null) { LOG.debug("Getting initial nonce, HEAD {}", uri); conn = httpConnector.openConnection(uri); conn.setRequestMethod("HEAD"); conn.connect(); updateSession(session); conn = null; } if (session.getNonce() == null) { throw new AcmeException("No nonce available"); } LOG.debug("POST {} with claims: {}", uri, claims); conn = httpConnector.openConnection(uri); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); final PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(keypair.getPublic()); JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toString()); jws.getHeaders().setObjectHeaderValue("nonce", Base64Url.encode(session.getNonce())); jws.getHeaders().setJwkHeaderValue("jwk", jwk); jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); jws.setKey(keypair.getPrivate()); byte[] outputData = jws.getCompactSerialization().getBytes("utf-8"); conn.setFixedLengthStreamingMode(outputData.length); conn.connect(); try (OutputStream out = conn.getOutputStream()) { out.write(outputData); } logHeaders(); updateSession(session); return conn.getResponseCode(); } catch (JoseException | IOException ex) { throw new AcmeException("Request failed: " + uri, ex); } } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code @Override public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Registration registration) throws AcmeException { if (uri == null) { throw new NullPointerException("uri must not be null"); } if (claims == null) { throw new NullPointerException("claims must not be null"); } if (session == null) { throw new NullPointerException("session must not be null"); } if (registration == null) { throw new NullPointerException("registration must not be null"); } if (conn != null) { throw new IllegalStateException("Connection was not closed. Race condition?"); } try { KeyPair keypair = registration.getKeyPair(); if (session.getNonce() == null) { LOG.debug("Getting initial nonce, HEAD {}", uri); conn = httpConnector.openConnection(uri); conn.setRequestMethod("HEAD"); conn.connect(); updateSession(session); conn = null; } if (session.getNonce() == null) { throw new AcmeException("No nonce available"); } LOG.debug("POST {} with claims: {}", uri, claims); conn = httpConnector.openConnection(uri); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); final PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(keypair.getPublic()); JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toString()); jws.getHeaders().setObjectHeaderValue("nonce", Base64Url.encode(session.getNonce())); jws.getHeaders().setJwkHeaderValue("jwk", jwk); jws.setAlgorithmHeaderValue(SignatureUtils.keyAlgorithm(jwk)); jws.setKey(keypair.getPrivate()); byte[] outputData = jws.getCompactSerialization().getBytes("utf-8"); conn.setFixedLengthStreamingMode(outputData.length); conn.connect(); try (OutputStream out = conn.getOutputStream()) { out.write(outputData); } logHeaders(); updateSession(session); return conn.getResponseCode(); } catch (JoseException | IOException ex) { throw new AcmeException("Request failed: " + uri, ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @GetMapping("/employees/{id}") public Mono<EntityModel<Employee>> findOne(@PathVariable Integer id) { WebFluxEmployeeController controller = methodOn(WebFluxEmployeeController.class); Mono<Link> selfLink = linkTo(controller.findOne(id)).withSelfRel() // .andAffordance(controller.updateEmployee(null, id)) // .andAffordance(controller.partiallyUpdateEmployee(null, id)) // .toMono(); Mono<Link> employeesLink = linkTo(controller.all()).withRel("employees") // .toMono(); return selfLink.zipWith(employeesLink) // .map(function((left, right) -> Links.of(left, right))) // .map(links -> new EntityModel<>(EMPLOYEES.get(id), links)); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @GetMapping("/employees/{id}") public Mono<EntityModel<Employee>> findOne(@PathVariable Integer id) { WebFluxEmployeeController controller = methodOn(WebFluxEmployeeController.class); Mono<Link> selfLink = linkTo(controller.findOne(id)).withSelfRel() // .andAffordance(controller.updateEmployee(null, id)) // .andAffordance(controller.partiallyUpdateEmployee(null, id)) // .toMono(); Mono<Link> employeesLink = linkTo(controller.all()).withRel("employees") // .toMono(); return selfLink.zipWith(employeesLink) // .map(function((left, right) -> Links.of(left, right))) // .map(links -> { return new EntityModel<>(EMPLOYEES.get(id), links); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static HalLinkRelation of(@Nullable LinkRelation relation) { Assert.notNull(relation, "LinkRelation must not be null!"); if (HalLinkRelation.class.isInstance(relation)) { return HalLinkRelation.class.cast(relation); } return of(relation.value()); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static HalLinkRelation of(@Nullable LinkRelation relation) { Assert.notNull(relation, "LinkRelation must not be null!"); if (relation instanceof HalLinkRelation) { return (HalLinkRelation) relation; } return of(relation.value()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static UriComponentsBuilder getBuilder() { if (RequestContextHolder.getRequestAttributes() == null) { return UriComponentsBuilder.fromPath("/"); } HttpServletRequest request = getCurrentRequest(); UriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request); // special case handling for X-Forwarded-Ssl: // apply it, but only if X-Forwarded-Proto is unset. String forwardedSsl = request.getHeader("X-Forwarded-Ssl"); ForwardedHeader forwarded = ForwardedHeader.of(request.getHeader(ForwardedHeader.NAME)); String proto = hasText(forwarded.getProto()) ? forwarded.getProto() : request.getHeader("X-Forwarded-Proto"); if (!hasText(proto) && hasText(forwardedSsl) && forwardedSsl.equalsIgnoreCase("on")) { builder.scheme("https"); } return builder; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public static UriComponentsBuilder getBuilder() { if (RequestContextHolder.getRequestAttributes() == null) { return UriComponentsBuilder.fromPath("/"); } HttpServletRequest request = getCurrentRequest(); ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request); // Spring 5.1 can handle X-Forwarded-Ssl headers... if (isSpringAtLeast5_1()) { return builder; } else { return handleXForwardedSslHeader(request, builder); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String... args) { RestTemplate template = new RestTemplate(); HttpEntity<String> response = template.getForEntity(URI_TEMPLATE, String.class, MILESTONE_ID); boolean keepChecking = true; boolean printHeader = true; while (keepChecking) { readPage(response.getBody(), printHeader); printHeader = false; String linkHeader = response.getHeaders().get("Link").get(0); Links links = Arrays.stream(linkHeader.split(", ")) // .map(Link::valueOf) // .collect(Collectors.collectingAndThen(Collectors.toList(), Links::of)); if (links.getLink(IanaLinkRelations.NEXT).isPresent()) { response = template.getForEntity(links.getRequiredLink(IanaLinkRelations.NEXT).expand().getHref(), String.class); } else { keepChecking = false; } } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String... args) { /* * If you run into github rate limiting issues, you can always use a Github Personal Token by adding * {@code .header(HttpHeaders.AUTHORIZATION, "token your-github-token")} to the webClient call. */ WebClient webClient = WebClient.create(); HttpEntity<String> response = webClient // .get().uri(URI_TEMPLATE, MILESTONE_ID) // .exchange() // .flatMap(clientResponse -> clientResponse.toEntity(String.class)) // .block(Duration.ofSeconds(10)); boolean keepChecking = true; boolean printHeader = true; while (keepChecking) { readPage(response.getBody(), printHeader); printHeader = false; Links links = Links.parse(response.getHeaders().get(HttpHeaders.LINK).get(0)); if (links.getLink(IanaLinkRelations.NEXT).isPresent()) { response = webClient // .get().uri(links.getRequiredLink(IanaLinkRelations.NEXT).expand().getHref()) // .exchange() // .flatMap(clientResponse -> clientResponse.toEntity(String.class)) // .block(Duration.ofSeconds(10)); } else { keepChecking = false; } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static UriComponentsBuilder getBuilder() { if (RequestContextHolder.getRequestAttributes() == null) { return UriComponentsBuilder.fromPath("/"); } HttpServletRequest request = getCurrentRequest(); ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request); // Spring 5.1 can handle X-Forwarded-Ssl headers... if (isSpringAtLeast5_1()) { return builder; } else { return handleXForwardedSslHeader(request, builder); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public static UriComponentsBuilder getBuilder() { if (RequestContextHolder.getRequestAttributes() == null) { return UriComponentsBuilder.fromPath("/"); } return ServletUriComponentsBuilder.fromServletMapping(getCurrentRequest()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCreate() throws IOException { Dataset dataset = repo.create("test1", testSchema); Assert.assertTrue("Dataset data directory exists", fileSystem.exists(new Path(testDirectory, "data/test1/data"))); Assert.assertTrue("Dataset metadata file exists", fileSystem.exists(new Path(testDirectory, "data/test1/schema.avsc"))); Schema serializedSchema = new Schema.Parser().parse(new File(testDirectory .toUri().getPath(), "data/test1/schema.avsc")); Schema schema = dataset.getSchema(); Assert.assertEquals("Dataset schema matches what's serialized to disk", schema, serializedSchema); Assert.assertNotNull(schema); Assert.assertTrue(schema.getType().equals(Type.RECORD)); Assert.assertNotNull(schema.getField("name")); Assert.assertTrue(schema.getField("name").schema().getType() .equals(Type.STRING)); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCreate() throws IOException { HDFSDataset dataset = repo.create("test1", testSchema); Assert.assertTrue("HDFSDataset data directory exists", fileSystem.exists(new Path(testDirectory, "data/test1/data"))); Assert.assertTrue("HDFSDataset metadata file exists", fileSystem.exists(new Path(testDirectory, "data/test1/schema.avsc"))); Schema serializedSchema = new Schema.Parser().parse(new File(testDirectory .toUri().getPath(), "data/test1/schema.avsc")); Schema schema = dataset.getSchema(); Assert.assertEquals("HDFSDataset schema matches what's serialized to disk", schema, serializedSchema); Assert.assertNotNull(schema); Assert.assertTrue(schema.getType().equals(Type.RECORD)); Assert.assertNotNull(schema.getField("name")); Assert.assertTrue(schema.getField("name").schema().getType() .equals(Type.STRING)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<Word> segImpl(String text) { if(text.length() > PROCESS_TEXT_LENGTH_LESS_THAN){ return RMM.segImpl(text); } //获取全切分结果 List<Word>[] array = fullSeg(text); //利用ngram计算分值 Map<List<Word>, Float> words = ngram(array); //歧义消解(ngram分值优先、词个数少优先) List<Word> result = disambiguity(words); return result; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<Word> segImpl(String text) { //文本长度 final int textLen = text.length(); //开始虚拟节点,注意值的长度只能为1 Node start = new Node("S", 0); start.score = 1F; //结束虚拟节点 Node end = new Node("END", textLen+1); //以文本中每一个字的位置(从1开始)作为二维数组的横坐标 //以每一个字开始所能切分出来的所有的词的顺序作为纵坐标(从0开始) Node[][] dag = new Node[textLen+2][0]; dag[0] = new Node[] { start }; dag[textLen+1] = new Node[] { end }; for(int i=0; i<textLen; i++){ dag[i+1] = fullSeg(text, i); } dump(dag); //标注路径 int following = 0; Node node = null; for (int i = 0; i < dag.length - 1; i++) { for (int j = 0; j < dag[i].length; j++) { node = dag[i][j]; following = node.getFollowing(); for (int k = 0; k < dag[following].length; k++) { dag[following][k].setPrevious(node); } } } dump(dag); return toWords(end); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGet() { Assert.assertEquals(100, trie.get("杨尚川"), 0); Assert.assertEquals(99, trie.get("杨尚喜"), 0); Assert.assertEquals(98, trie.get("杨尚丽"), 0); Assert.assertEquals(1, trie.get("中华人民共和国"), 0); Assert.assertEquals(null, trie.get("杨")); Assert.assertEquals(null, trie.get("杨尚")); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGet() { assertEquals(100, genericTrie.get("杨尚川").intValue()); assertEquals(99, genericTrie.get("杨尚喜").intValue()); assertEquals(98, genericTrie.get("杨尚丽").intValue()); assertEquals(1, genericTrie.get("中华人民共和国").intValue()); assertEquals(null, genericTrie.get("杨")); assertEquals(null, genericTrie.get("杨尚")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<Word> seg(String text) { List<Word> result = new ArrayList<>(); List<String> sentences = Punctuation.seg(text, KEEP_PUNCTUATION); if(sentences.size() == 1){ result = segSentence(sentences.get(0)); }else { //如果是多个句子,可以利用多线程提升分词速度 List<Future<List<Word>>> futures = new ArrayList<>(sentences.size()); for (String sentence : sentences) { futures.add(submit(sentence)); } sentences.clear(); for (Future<List<Word>> future : futures) { List<Word> words; try { words = future.get(); if (words != null) { result.addAll(words); } } catch (InterruptedException | ExecutionException ex) { LOGGER.error("获取分词结果失败", ex); } } futures.clear(); } if(refine) { LOGGER.debug("对分词结果进行refine之前:{}", result); List<Word> finalResult = refine(result); LOGGER.debug("对分词结果进行refine之后:{}", finalResult); result.clear(); return finalResult; }else{ return result; } } #location 31 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<Word> seg(String text) { List<String> sentences = Punctuation.seg(text, KEEP_PUNCTUATION); if(sentences.size() == 1){ return segSentence(sentences.get(0)); } //如果是多个句子,可以利用多线程提升分词速度 List<Future<List<Word>>> futures = new ArrayList<>(sentences.size()); for(String sentence : sentences){ futures.add(submit(sentence)); } sentences.clear(); List<Word> result = new ArrayList<>(); for(Future<List<Word>> future : futures){ List<Word> words; try { words = future.get(); if(words != null){ result.addAll(words); } } catch (InterruptedException | ExecutionException ex) { LOGGER.error("获取分词结果失败", ex); } } futures.clear(); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testClear() { Assert.assertEquals(100, trie.get("杨尚川"), 0); Assert.assertEquals(1, trie.get("中华人民共和国"), 0); trie.clear(); Assert.assertEquals(null, trie.get("杨尚川")); Assert.assertEquals(null, trie.get("中华人民共和国")); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testClear() { assertEquals(100, genericTrie.get("杨尚川").intValue()); assertEquals(1, genericTrie.get("中华人民共和国").intValue()); genericTrie.clear(); assertEquals(null, genericTrie.get("杨尚川")); assertEquals(null, genericTrie.get("中华人民共和国")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<Word> segImpl(String text) { if(text.length() > PROCESS_TEXT_LENGTH_LESS_THAN){ return RMM.segImpl(text); } //获取全切分结果 List<Word>[] array = fullSeg(text); //利用ngram计算分值 Map<List<Word>, Float> words = ngram(array); //歧义消解(ngram分值优先、词个数少优先) List<Word> result = disambiguity(words); return result; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<Word> segImpl(String text) { if(text.length() > PROCESS_TEXT_LENGTH_LESS_THAN){ return RMM.segImpl(text); } //获取全切分结果 List<Word>[] array = fullSeg(text); Set<Word> words = new HashSet<Word>(); for(List<Word> wordList : array){ words.addAll(wordList); } List<Word> result = new ArrayList<Word>(words); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public final boolean incrementToken() throws IOException { Word word = getWord(); if (word != null) { int positionIncrement = 1; //忽略停用词 while(StopWord.is(word.getText())){ positionIncrement++; startOffset += word.getText().length(); LOGGER.debug("忽略停用词:"+word.getText()); word = getWord(); if(word == null){ return false; } } charTermAttribute.setEmpty().append(word.getText()); offsetAttribute.setOffset(startOffset, startOffset+word.getText().length()); positionIncrementAttribute.setPositionIncrement(positionIncrement); startOffset += word.getText().length(); //词性标注 if(POS){ PartOfSpeechTagging.process(Arrays.asList(word)); partOfSpeechAttribute.setEmpty().append(word.getPartOfSpeech().getPos()); } //拼音标注 if(PINYIN){ PinyinTagging.process(Arrays.asList(word)); acronymPinyinAttribute.setEmpty().append(word.getAcronymPinYin()); fullPinyinAttribute.setEmpty().append(word.getFullPinYin()); } //同义标注 if(SYNONYM){ SynonymTagging.process(Arrays.asList(word)); StringBuilder synonym = new StringBuilder(); word.getSynonym().forEach(w -> synonym.append(w.getText()).append(" ")); synonymAttribute.setEmpty().append(synonym.toString().trim()); } //反义标注 if(ANTONYM){ AntonymTagging.process(Arrays.asList(word)); StringBuilder antonym = new StringBuilder(); word.getAntonym().forEach(w -> antonym.append(w.getText()).append(" ")); antonymAttribute.setEmpty().append(antonym.toString().trim()); } return true; } return false; } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public final boolean incrementToken() throws IOException { String token = getToken(); if (token != null) { charTermAttribute.setEmpty().append(token); return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void doStartProxy(KubernetesContainerProxy proxy) throws Exception { String kubeNamespace = getProperty(PROPERTY_NAMESPACE, proxy.getApp(), DEFAULT_NAMESPACE); String[] volumeStrings = Optional.ofNullable(proxy.getApp().getDockerVolumes()).orElse(new String[] {}); Volume[] volumes = new Volume[volumeStrings.length]; VolumeMount[] volumeMounts = new VolumeMount[volumeStrings.length]; for (int i = 0; i < volumeStrings.length; i++) { String[] volume = volumeStrings[i].split(":"); String hostSource = volume[0]; String containerDest = volume[1]; String name = "shinyproxy-volume-" + i; volumes[i] = new VolumeBuilder() .withNewHostPath(hostSource) .withName(name) .build(); volumeMounts[i] = new VolumeMountBuilder() .withMountPath(containerDest) .withName(name) .build(); } List<EnvVar> envVars = new ArrayList<>(); for (String envString : buildEnv(proxy.getUserId(), proxy.getApp())) { int idx = envString.indexOf('='); if (idx == -1) log.warn("Invalid environment variable: " + envString); envVars.add(new EnvVar(envString.substring(0, idx), envString.substring(idx + 1), null)); } SecurityContext security = new SecurityContextBuilder() .withPrivileged(Boolean.valueOf(getProperty(PROPERTY_PRIVILEGED, proxy.getApp(), DEFAULT_PRIVILEGED))) .build(); ContainerBuilder containerBuilder = new ContainerBuilder() .withImage(proxy.getApp().getDockerImage()) .withName("shiny-container") .withPorts(new ContainerPortBuilder().withContainerPort(getAppPort(proxy)).build()) .withVolumeMounts(volumeMounts) .withSecurityContext(security) .withEnv(envVars); String imagePullPolicy = getProperty(PROPERTY_IMG_PULL_POLICY, proxy.getApp(), null); if (imagePullPolicy != null) containerBuilder.withImagePullPolicy(imagePullPolicy); if (proxy.getApp().getDockerCmd() != null) containerBuilder.withCommand(proxy.getApp().getDockerCmd()); String[] imagePullSecrets = getProperty(PROPERTY_IMG_PULL_SECRETS, proxy.getApp(), String[].class, null); if (imagePullSecrets == null) { String imagePullSecret = getProperty(PROPERTY_IMG_PULL_SECRET, proxy.getApp(), null); if (imagePullSecret != null) { imagePullSecrets = new String[] {imagePullSecret}; } else { imagePullSecrets = new String[0]; } } Pod pod = kubeClient.pods().inNamespace(kubeNamespace).createNew() .withApiVersion("v1") .withKind("Pod") .withNewMetadata() .withName(proxy.getName()) .addToLabels("app", proxy.getName()) .endMetadata() .withNewSpec() .withContainers(Collections.singletonList(containerBuilder.build())) .withVolumes(volumes) .withImagePullSecrets(Arrays.asList(imagePullSecrets).stream() .map(LocalObjectReference::new).collect(Collectors.toList())) .endSpec() .done(); proxy.setPod(kubeClient.resource(pod).waitUntilReady(600, TimeUnit.SECONDS)); if (!isUseInternalNetwork()) { // If SP runs outside the cluster, a NodePort service is needed to access the pod externally. Service service = kubeClient.services().inNamespace(kubeNamespace).createNew() .withApiVersion("v1") .withKind("Service") .withNewMetadata() .withName(proxy.getName() + "service") .endMetadata() .withNewSpec() .addToSelector("app", proxy.getName()) .withType("NodePort") .withPorts(new ServicePortBuilder() .withPort(getAppPort(proxy)) .build()) .endSpec() .done(); proxy.setService(kubeClient.resource(service).waitUntilReady(600, TimeUnit.SECONDS)); releasePort(proxy.getPort()); proxy.setPort(proxy.getService().getSpec().getPorts().get(0).getNodePort()); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void doStartProxy(KubernetesContainerProxy proxy) throws Exception { String kubeNamespace = getProperty(PROPERTY_NAMESPACE, proxy.getApp(), DEFAULT_NAMESPACE); String apiVersion = getProperty(PROPERTY_API_VERSION, proxy.getApp(), DEFAULT_API_VERSION); String[] volumeStrings = Optional.ofNullable(proxy.getApp().getDockerVolumes()).orElse(new String[] {}); Volume[] volumes = new Volume[volumeStrings.length]; VolumeMount[] volumeMounts = new VolumeMount[volumeStrings.length]; for (int i = 0; i < volumeStrings.length; i++) { String[] volume = volumeStrings[i].split(":"); String hostSource = volume[0]; String containerDest = volume[1]; String name = "shinyproxy-volume-" + i; volumes[i] = new VolumeBuilder() .withNewHostPath(hostSource) .withName(name) .build(); volumeMounts[i] = new VolumeMountBuilder() .withMountPath(containerDest) .withName(name) .build(); } List<EnvVar> envVars = new ArrayList<>(); for (String envString : buildEnv(proxy.getUserId(), proxy.getApp())) { int idx = envString.indexOf('='); if (idx == -1) log.warn("Invalid environment variable: " + envString); envVars.add(new EnvVar(envString.substring(0, idx), envString.substring(idx + 1), null)); } SecurityContext security = new SecurityContextBuilder() .withPrivileged(Boolean.valueOf(getProperty(PROPERTY_PRIVILEGED, proxy.getApp(), DEFAULT_PRIVILEGED))) .build(); ContainerBuilder containerBuilder = new ContainerBuilder() .withImage(proxy.getApp().getDockerImage()) .withName("shiny-container") .withPorts(new ContainerPortBuilder().withContainerPort(getAppPort(proxy)).build()) .withVolumeMounts(volumeMounts) .withSecurityContext(security) .withEnv(envVars); String imagePullPolicy = getProperty(PROPERTY_IMG_PULL_POLICY, proxy.getApp(), null); if (imagePullPolicy != null) containerBuilder.withImagePullPolicy(imagePullPolicy); if (proxy.getApp().getDockerCmd() != null) containerBuilder.withCommand(proxy.getApp().getDockerCmd()); String[] imagePullSecrets = getProperty(PROPERTY_IMG_PULL_SECRETS, proxy.getApp(), String[].class, null); if (imagePullSecrets == null) { String imagePullSecret = getProperty(PROPERTY_IMG_PULL_SECRET, proxy.getApp(), null); if (imagePullSecret != null) { imagePullSecrets = new String[] {imagePullSecret}; } else { imagePullSecrets = new String[0]; } } Pod pod = kubeClient.pods().inNamespace(kubeNamespace).createNew() .withApiVersion(apiVersion) .withKind("Pod") .withNewMetadata() .withName(proxy.getName()) .addToLabels("app", proxy.getName()) .endMetadata() .withNewSpec() .withContainers(Collections.singletonList(containerBuilder.build())) .withVolumes(volumes) .withImagePullSecrets(Arrays.asList(imagePullSecrets).stream() .map(LocalObjectReference::new).collect(Collectors.toList())) .endSpec() .done(); proxy.setPod(kubeClient.resource(pod).waitUntilReady(600, TimeUnit.SECONDS)); if (!isUseInternalNetwork()) { // If SP runs outside the cluster, a NodePort service is needed to access the pod externally. Service service = kubeClient.services().inNamespace(kubeNamespace).createNew() .withApiVersion(apiVersion) .withKind("Service") .withNewMetadata() .withName(proxy.getName() + "service") .endMetadata() .withNewSpec() .addToSelector("app", proxy.getName()) .withType("NodePort") .withPorts(new ServicePortBuilder() .withPort(getAppPort(proxy)) .build()) .endSpec() .done(); // Retry, because if this is done too fast, an 'endpoint not found' exception will be thrown. Utils.retry(i -> { try { proxy.setService(kubeClient.resource(service).waitUntilReady(600, TimeUnit.SECONDS)); } catch (Exception e) { return false; } return true; }, 5, 1000); releasePort(proxy.getPort()); proxy.setPort(proxy.getService().getSpec().getPorts().get(0).getNodePort()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public HttpResponse execute(HttpRequest request) throws HttpClientException { HttpResponse response = null; try { URI uri = new URI(request.getURI().toString(), false, Consts.UTF_8.name()); org.apache.commons.httpclient.HttpMethod httpMethod = methodMap .get(request.getMethod()); if (request.getMethod() == HttpMethod.TRACE) { httpMethod = new TraceMethod(uri.getEscapedURI()); } else { httpMethod.setURI(uri); } HttpParams params = request.getParams(); if (params != null) { Proxy proxy = params.getProxy(); if (proxy != null) { InetSocketAddress socketAddress = (InetSocketAddress) proxy .address(); httpClient.getHostConfiguration().setProxy( socketAddress.getHostName(), socketAddress.getPort()); } SSLContext sslContext = params.getSSLContext(); if (sslContext != null) { Protocol.registerProtocol("https", new Protocol("https", new SSLProtocolSocketFactory(sslContext), 443)); } httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(params.getConnectTimeout()); httpClient.getHttpConnectionManager().getParams() .setSendBufferSize(params.getChunkSize()); httpMethod.getParams().setUriCharset(Consts.UTF_8.name()); httpMethod.getParams().setSoTimeout(params.getSocketTimeout()); httpMethod.getParams().setContentCharset(Consts.UTF_8.name()); } com.foxinmy.weixin4j.http.HttpHeaders headers = request .getHeaders(); if (headers == null) { headers = new HttpHeaders(); } if (!headers.containsKey(HttpHeaders.HOST)) { headers.set(HttpHeaders.HOST, uri.getHost()); } // Add default accept headers if (!headers.containsKey(HttpHeaders.ACCEPT)) { headers.set(HttpHeaders.ACCEPT, "*/*"); } // Add default user agent if (!headers.containsKey(HttpHeaders.USER_AGENT)) { headers.set(HttpHeaders.USER_AGENT, "apache/httpclient3"); } for (Iterator<Entry<String, List<String>>> headerIterator = headers .entrySet().iterator(); headerIterator.hasNext();) { Entry<String, List<String>> header = headerIterator.next(); if (HttpHeaders.COOKIE.equalsIgnoreCase(header.getKey())) { httpMethod.setRequestHeader(header.getKey(), StringUtil.join(header.getValue(), ';')); } else { for (String headerValue : header.getValue()) { httpMethod.addRequestHeader(header.getKey(), headerValue != null ? headerValue : ""); } } } HttpEntity entity = request.getEntity(); if (entity != null) { if (entity.getContentLength() > 0l) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength())); } if (entity.getContentType() != null) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, entity.getContentType().toString()); } RequestEntity requestEntity = null; if (entity instanceof MultipartEntity) { ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); os.flush(); requestEntity = new ByteArrayRequestEntity( os.toByteArray(), entity.getContentType() .toString()); os.close(); } else { requestEntity = new InputStreamRequestEntity( entity.getContent(), entity.getContentType() .toString()); } ((EntityEnclosingMethod) httpMethod) .setRequestEntity(requestEntity); } httpClient.executeMethod(httpMethod); response = new HttpComponent3Response(httpMethod); handleResponse(response); } catch (IOException e) { throw new HttpClientException("I/O error on " + request.getMethod().name() + " request for \"" + request.getURI().toString() + "\":" + e.getMessage(), e); } finally { if (response != null) { response.close(); } } return response; } #location 83 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public HttpResponse execute(HttpRequest request) throws HttpClientException { HttpResponse response = null; try { URI uri = new URI(request.getURI().toString(), false, Consts.UTF_8.name()); org.apache.commons.httpclient.HttpMethod httpMethod = method2method(request .getMethod()); if (request.getMethod() == HttpMethod.TRACE) { httpMethod = new TraceMethod(uri.getEscapedURI()); } else { httpMethod.setURI(uri); } HttpParams params = request.getParams(); if (params != null) { Proxy proxy = params.getProxy(); if (proxy != null) { InetSocketAddress socketAddress = (InetSocketAddress) proxy .address(); httpClient.getHostConfiguration().setProxy( socketAddress.getHostName(), socketAddress.getPort()); } SSLContext sslContext = params.getSSLContext(); if (sslContext != null) { Protocol.registerProtocol("https", new Protocol("https", new SSLProtocolSocketFactory(sslContext), 443)); } httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(params.getConnectTimeout()); httpClient.getHttpConnectionManager().getParams() .setSendBufferSize(params.getChunkSize()); httpMethod.getParams().setUriCharset(Consts.UTF_8.name()); httpMethod.getParams().setSoTimeout(params.getSocketTimeout()); httpMethod.getParams().setContentCharset(Consts.UTF_8.name()); } com.foxinmy.weixin4j.http.HttpHeaders headers = request .getHeaders(); if (headers == null) { headers = new HttpHeaders(); } if (!headers.containsKey(HttpHeaders.HOST)) { headers.set(HttpHeaders.HOST, uri.getHost()); } // Add default accept headers if (!headers.containsKey(HttpHeaders.ACCEPT)) { headers.set(HttpHeaders.ACCEPT, "*/*"); } // Add default user agent if (!headers.containsKey(HttpHeaders.USER_AGENT)) { headers.set(HttpHeaders.USER_AGENT, "apache/httpclient3"); } for (Iterator<Entry<String, List<String>>> headerIterator = headers .entrySet().iterator(); headerIterator.hasNext();) { Entry<String, List<String>> header = headerIterator.next(); if (HttpHeaders.COOKIE.equalsIgnoreCase(header.getKey())) { httpMethod.setRequestHeader(header.getKey(), StringUtil.join(header.getValue(), ';')); } else { for (String headerValue : header.getValue()) { httpMethod.addRequestHeader(header.getKey(), headerValue != null ? headerValue : ""); } } } HttpEntity entity = request.getEntity(); if (entity != null) { if (entity.getContentLength() > 0l) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength())); } if (entity.getContentType() != null) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, entity.getContentType().toString()); } RequestEntity requestEntity = null; if (entity instanceof MultipartEntity) { ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); os.flush(); requestEntity = new ByteArrayRequestEntity( os.toByteArray(), entity.getContentType() .toString()); os.close(); } else { requestEntity = new InputStreamRequestEntity( entity.getContent(), entity.getContentType() .toString()); } ((EntityEnclosingMethod) httpMethod) .setRequestEntity(requestEntity); } httpClient.executeMethod(httpMethod); response = new HttpComponent3Response(httpMethod); handleResponse(response); } catch (IOException e) { throw new HttpClientException("I/O error on " + request.getMethod().name() + " request for \"" + request.getURI().toString() + "\":" + e.getMessage(), e); } finally { if (response != null) { response.close(); } } return response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MchPayRequest createMicroPayRequest(String authCode, String body, String outTradeNo, double totalFee, String createIp, String attach) throws WeixinException { // 刷卡支付不需要设置TradeType.MICROPAY MchPayPackage payPackage = new MchPayPackage(body, outTradeNo, totalFee, null, createIp, null, null, authCode, null, attach); return createPayRequest(payPackage); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public MchPayRequest createMicroPayRequest(String authCode, String body, String outTradeNo, double totalFee, String createIp, String attach) throws WeixinException { MchPayPackage payPackage = new MchPayPackage(body, outTradeNo, totalFee, null, createIp, TradeType.MICROPAY, null, authCode, null, attach); return createPayRequest(payPackage); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Order orderQuery(IdQuery idQuery) throws WeixinException { Map<String, String> map = baseMap(idQuery); String sign = PayUtil.paysignMd5(map, weixinAccount.getPaySignKey()); map.put("sign", sign); String param = XmlStream.map2xml(map); String orderquery_uri = getRequestUri("orderquery_v3_uri"); WeixinResponse response = weixinClient.post(orderquery_uri, param); return ListsuffixResultDeserializer.containCouponDeserialize( response.getAsString(), Order.class); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public Order orderQuery(IdQuery idQuery) throws WeixinException { Map<String, String> map = baseMap(idQuery); String sign = PayUtil.paysignMd5(map, weixinAccount.getPaySignKey()); map.put("sign", sign); String param = XmlStream.map2xml(map); String orderquery_uri = getRequestUri("orderquery_v3_uri"); WeixinResponse response = weixinClient.post(orderquery_uri, param); return ListsuffixResultDeserializer.deserialize(response.getAsString(), Order.class, "couponList"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public HttpResponse execute(HttpRequest request) throws HttpClientException { HttpResponse response = null; try { URI uri = new URI(request.getURI().toString(), false, Consts.UTF_8.name()); org.apache.commons.httpclient.HttpMethod httpMethod = method2method(request .getMethod()); if (request.getMethod() == HttpMethod.TRACE) { httpMethod = new TraceMethod(uri.getEscapedURI()); } else { httpMethod.setURI(uri); } boolean useSSL = "https".equals(uri.getScheme()); SSLContext sslContext = null; HttpParams params = request.getParams(); if (params != null) { Proxy proxy = params.getProxy(); if (proxy != null) { InetSocketAddress socketAddress = (InetSocketAddress) proxy .address(); httpClient.getHostConfiguration().setProxy( socketAddress.getHostName(), socketAddress.getPort()); useSSL = false; } sslContext = params.getSSLContext(); httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(params.getConnectTimeout()); httpClient.getHttpConnectionManager().getParams() .setSendBufferSize(params.getChunkSize()); httpMethod.getParams().setUriCharset(Consts.UTF_8.name()); httpMethod.getParams().setSoTimeout(params.getSocketTimeout()); httpMethod.getParams().setContentCharset(Consts.UTF_8.name()); } if (useSSL) { if (sslContext == null) { sslContext = HttpClientFactory.allowSSLContext(); } Protocol.registerProtocol("https", new Protocol("https", new SSLProtocolSocketFactory(sslContext), 443)); } com.foxinmy.weixin4j.http.HttpHeaders headers = request .getHeaders(); if (headers == null) { headers = new HttpHeaders(); } if (!headers.containsKey(HttpHeaders.HOST)) { headers.set(HttpHeaders.HOST, uri.getHost()); } // Add default accept headers if (!headers.containsKey(HttpHeaders.ACCEPT)) { headers.set(HttpHeaders.ACCEPT, "*/*"); } // Add default user agent if (!headers.containsKey(HttpHeaders.USER_AGENT)) { headers.set(HttpHeaders.USER_AGENT, "apache/httpclient3"); } for (Iterator<Entry<String, List<String>>> headerIterator = headers .entrySet().iterator(); headerIterator.hasNext();) { Entry<String, List<String>> header = headerIterator.next(); if (HttpHeaders.COOKIE.equalsIgnoreCase(header.getKey())) { httpMethod.setRequestHeader(header.getKey(), StringUtil.join(header.getValue(), ';')); } else { for (String headerValue : header.getValue()) { httpMethod.addRequestHeader(header.getKey(), headerValue != null ? headerValue : ""); } } } HttpEntity entity = request.getEntity(); if (entity != null) { if (entity.getContentLength() > 0l) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength())); } if (entity.getContentType() != null) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, entity.getContentType().toString()); } RequestEntity requestEntity = null; if (entity instanceof MultipartEntity) { ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); os.flush(); requestEntity = new ByteArrayRequestEntity( os.toByteArray(), entity.getContentType() .toString()); os.close(); } else { requestEntity = new InputStreamRequestEntity( entity.getContent(), entity.getContentType() .toString()); } ((EntityEnclosingMethod) httpMethod) .setRequestEntity(requestEntity); } httpClient.executeMethod(httpMethod); response = new HttpComponent3Response(httpMethod); handleResponse(response); } catch (IOException e) { throw new HttpClientException("I/O error on " + request.getMethod().name() + " request for \"" + request.getURI().toString() + "\":" + e.getMessage(), e); } finally { if (response != null) { response.close(); } } return response; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public HttpResponse execute(HttpRequest request) throws HttpClientException { HttpResponse response = null; try { org.apache.commons.httpclient.HttpMethod httpMethod = createHttpMethod( request.getMethod(), request.getURI()); boolean useSSL = "https".equals(request.getURI().getScheme()); SSLContext sslContext = null; HttpParams params = request.getParams(); if (params != null) { Proxy proxy = params.getProxy(); if (proxy != null) { InetSocketAddress socketAddress = (InetSocketAddress) proxy .address(); httpClient.getHostConfiguration().setProxy( socketAddress.getHostName(), socketAddress.getPort()); useSSL = false; } sslContext = params.getSSLContext(); httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(params.getConnectTimeout()); httpClient.getHttpConnectionManager().getParams() .setSendBufferSize(params.getChunkSize()); httpMethod.getParams().setUriCharset(Consts.UTF_8.name()); httpMethod.getParams().setSoTimeout(params.getSocketTimeout()); httpMethod.getParams().setContentCharset(Consts.UTF_8.name()); } if (useSSL) { if (sslContext == null) { sslContext = HttpClientFactory.allowSSLContext(); } Protocol.registerProtocol("https", new Protocol("https", new SSLProtocolSocketFactory(sslContext), 443)); } com.foxinmy.weixin4j.http.HttpHeaders headers = request .getHeaders(); if (headers == null) { headers = new HttpHeaders(); } if (!headers.containsKey(HttpHeaders.HOST)) { headers.set(HttpHeaders.HOST, request.getURI().getHost()); } // Add default accept headers if (!headers.containsKey(HttpHeaders.ACCEPT)) { headers.set(HttpHeaders.ACCEPT, "*/*"); } // Add default user agent if (!headers.containsKey(HttpHeaders.USER_AGENT)) { headers.set(HttpHeaders.USER_AGENT, "apache/httpclient3"); } for (Iterator<Entry<String, List<String>>> headerIterator = headers .entrySet().iterator(); headerIterator.hasNext();) { Entry<String, List<String>> header = headerIterator.next(); if (HttpHeaders.COOKIE.equalsIgnoreCase(header.getKey())) { httpMethod.setRequestHeader(header.getKey(), StringUtil.join(header.getValue(), ';')); } else { for (String headerValue : header.getValue()) { httpMethod.addRequestHeader(header.getKey(), headerValue != null ? headerValue : ""); } } } HttpEntity entity = request.getEntity(); if (entity != null) { if (entity.getContentLength() > 0l) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength())); } if (entity.getContentType() != null) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, entity.getContentType().toString()); } RequestEntity requestEntity = null; if (entity instanceof MultipartEntity) { ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); os.flush(); requestEntity = new ByteArrayRequestEntity( os.toByteArray(), entity.getContentType() .toString()); os.close(); } else { requestEntity = new InputStreamRequestEntity( entity.getContent(), entity.getContentType() .toString()); } ((EntityEnclosingMethod) httpMethod) .setRequestEntity(requestEntity); } httpClient.executeMethod(httpMethod); response = new HttpComponent3Response(httpMethod); handleResponse(response); } catch (IOException e) { throw new HttpClientException("I/O error on " + request.getMethod().name() + " request for \"" + request.getURI().toString() + "\":" + e.getMessage(), e); } finally { if (response != null) { response.close(); } } return response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<Class<?>> getClasses(String packageName) { String packageFileName = packageName.replace(POINT, File.separator); URL fullPath = getDefaultClassLoader().getResource(packageFileName); if (fullPath == null) { fullPath = ClassUtil.class.getClassLoader().getResource( packageFileName); } String protocol = fullPath.getProtocol(); if (protocol.equals(ServerToolkits.PROTOCOL_FILE)) { try { File dir = new File(fullPath.toURI()); return findClassesByFile(dir, packageName); } catch (URISyntaxException e) { throw new RuntimeException(e); } } else if (protocol.equals(ServerToolkits.PROTOCOL_JAR)) { try { return findClassesByJar( ((JarURLConnection) fullPath.openConnection()) .getJarFile(), packageName); } catch (IOException e) { throw new RuntimeException(e); } } return null; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public static List<Class<?>> getClasses(String packageName) { String packageFileName = packageName.replace(POINT, File.separator); URL fullPath = getDefaultClassLoader().getResource(packageFileName); if (fullPath == null) { fullPath = ClassUtil.class.getProtectionDomain().getCodeSource().getLocation(); } String protocol = fullPath.getProtocol(); if (protocol.equals(ServerToolkits.PROTOCOL_FILE)) { try { File dir = new File(fullPath.toURI()); return findClassesByFile(dir, packageName); } catch (URISyntaxException e) { throw new RuntimeException(e); } } else if (protocol.equals(ServerToolkits.PROTOCOL_JAR)) { try { return findClassesByJar(((JarURLConnection) fullPath.openConnection()).getJarFile(), packageName); } catch (IOException e) { throw new RuntimeException(e); } } throw new RuntimeException("the " + packageName + " not found classes."); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Order orderQuery(IdQuery idQuery) throws WeixinException { Map<String, String> map = baseMap(idQuery); String sign = PayUtil.paysignMd5(map, weixinAccount.getPaySignKey()); map.put("sign", sign); String param = XmlStream.map2xml(map); String orderquery_uri = getRequestUri("orderquery_v3_uri"); WeixinResponse response = weixinClient.post(orderquery_uri, param); return ListsuffixResultDeserializer.deserialize(response.getAsString(), Order.class, "couponList"); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public Order orderQuery(IdQuery idQuery) throws WeixinException { Map<String, String> map = baseMap(idQuery); String sign = PayUtil.paysignMd5(map, weixinAccount.getPaySignKey()); map.put("sign", sign); String param = XmlStream.map2xml(map); String orderquery_uri = getRequestUri("orderquery_v3_uri"); WeixinResponse response = weixinClient.post(orderquery_uri, param); return ListsuffixResultDeserializer.deserialize(response.getAsString(), Order.class); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException { Socket socket = new Socket(ircCatHost, ircCatPort); Writer out = new OutputStreamWriter(socket.getOutputStream()); try { out.write(format("%s %s\n", channel, message)); out.flush(); } catch (IOException e) { Closeables.closeQuietly(out); socket.close(); } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException { Socket socket = new Socket(ircCatHost, ircCatPort); Closer closer = Closer.create(); try { Writer out = closer.register(new OutputStreamWriter(socket.getOutputStream())); out.write(format("%s %s\n", channel, message)); out.flush(); } catch (IOException e) { socket.close(); throw closer.rethrow(e); } finally { closer.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException { Socket socket = new Socket(ircCatHost, ircCatPort); Writer out = new OutputStreamWriter(socket.getOutputStream()); try { out.write(format("%s %s\n", channel, message)); out.flush(); } catch (IOException e) { Closeables.closeQuietly(out); socket.close(); } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException { Socket socket = new Socket(ircCatHost, ircCatPort); Closer closer = Closer.create(); try { Writer out = closer.register(new OutputStreamWriter(socket.getOutputStream())); out.write(format("%s %s\n", channel, message)); out.flush(); } catch (IOException e) { socket.close(); throw closer.rethrow(e); } finally { closer.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public RulesProfile createProfile(final ValidationMessages messages) { LOGGER.info("Creating Swift Profile"); Reader config = null; final RulesProfile profile = RulesProfile.create("Swift", Swift.KEY); profile.setDefaultProfile(true); try { // add swift lint rules config = new InputStreamReader(getClass().getResourceAsStream(SwiftLintProfile.PROFILE_PATH)); RulesProfile ocLintRulesProfile = this.swiftLintProfileImporter.importProfile(config, messages); for (ActiveRule rule : ocLintRulesProfile.getActiveRules()) { profile.addActiveRule(rule); } //add tailor rules config = new InputStreamReader(getClass().getResourceAsStream(TailorProfile.PROFILE_PATH)); RulesProfile ocTailorRulesProfile = this.tailorProfileImporter.importProfile(config, messages); for (ActiveRule rule : ocTailorRulesProfile.getActiveRules()) { profile.addActiveRule(rule); } return profile; } finally { Closeables.closeQuietly(config); } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Override public RulesProfile createProfile(final ValidationMessages messages) { LOGGER.info("Creating Swift Profile"); Reader config = null; final RulesProfile profile = RulesProfile.create("Swift", Swift.KEY); profile.setDefaultProfile(true); try { // Add swift lint rules config = new InputStreamReader(getClass().getResourceAsStream(SwiftLintProfile.PROFILE_PATH)); RulesProfile ocLintRulesProfile = this.swiftLintProfileImporter.importProfile(config, messages); for (ActiveRule rule : ocLintRulesProfile.getActiveRules()) { profile.addActiveRule(rule); } return profile; } finally { Closeables.closeQuietly(config); } }
Below is the vulnerable code, please generate the patch based on the following information.