output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType, String code, String redirectUri, Boolean wap) { List<NameValuePair> params = new ArrayList<NameValuePair>(); connect.addParameter(params, "client_id", clientId); connect.addParameter(params, "client_secret", clientSecret); connect.addParameter(params, "grant_type", grantType); connect.addParameter(params, "code", code); connect.addParameter(params, "redirect_uri", redirectUri); String url = "https://graph.qq.com/oauth2.0/token"; if (Boolean.TRUE.equals(wap)) { url = "https://graph.z.qq.com/moc2/token"; } String result = connect.get(url, params).trim(); return parseAccessTokenResult(result); }
#vulnerable code public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType, String code, String redirectUri, Boolean wap) { List<NameValuePair> params = new ArrayList<NameValuePair>(); connect.addParameter(params, "client_id", clientId); connect.addParameter(params, "client_secret", clientSecret); connect.addParameter(params, "grant_type", grantType); connect.addParameter(params, "code", code); connect.addParameter(params, "redirect_uri", redirectUri); String url = "https://graph.qq.com/oauth2.0/token"; if (Boolean.TRUE.equals(wap)) { url = "https://graph.z.qq.com/moc2/token"; } String result = connect.get(url, params); String[] results = result.split("\\&"); JSONObject jsonObject = new JSONObject(); for (String param : results) { String[] keyValue = param.split("\\="); jsonObject.put(keyValue[0], keyValue.length > 0 ? keyValue[1] : null); } String errorCode = jsonObject.optString("code", null); if (errorCode != null) { jsonObject.put("ret", errorCode);// To match Error.parse() } return Result.parse(jsonObject, AccessToken.class); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testUserInfo() { String openId = System.getProperty("weixin.openid"); Result<com.belerweb.social.weixin.bean.User> result = weixin.getUser().userInfo(weixin.getAccessToken().getToken(), openId); Assert.assertTrue(result.success()); System.out.println(result.getResult().getJsonObject()); }
#vulnerable code @Test public void testUserInfo() { String accessToken = System.getProperty("weixin.atoken"); String openId = System.getProperty("weixin.openid"); Result<com.belerweb.social.weixin.bean.User> result = weixin.getUser().userInfo(accessToken, openId); Assert.assertTrue(result.success()); System.out.println(result.getResult().getJsonObject()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Result<TokenInfo> getTokenInfo(String accessToken) { List<NameValuePair> params = new ArrayList<NameValuePair>(); weibo.addParameter(params, "access_token", accessToken); String result = weibo.post("https://api.weibo.com/oauth2/get_token_info", params); return Result.parse(result, TokenInfo.class); }
#vulnerable code public Result<TokenInfo> getTokenInfo(String accessToken) { List<NameValuePair> params = new ArrayList<NameValuePair>(); weibo.addParameter(params, "access_token", accessToken); String result = weibo.post("https://api.weibo.com/oauth2/get_token_info", params); return Result.perse(result, TokenInfo.class); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final RemoteRequest request = new RemoteRequest(httpRequest); final LocalResponse response = new LocalResponse(httpResponse); chain.doFilter(request, response); if (isUnauthorized(response)) { final Optional<Correlator> correlator; if (isFirstRequest(request)) { correlator = logbook.write(new UnauthorizedRawHttpRequest(request)); } else { correlator = readCorrelator(request); } if (correlator.isPresent()) { correlator.get().write(response); } } }
#vulnerable code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final TeeRequest request = new TeeRequest(httpRequest); final TeeResponse response = new TeeResponse(httpResponse); chain.doFilter(request, response); if (isUnauthorized(response)) { final Optional<Correlator> correlator; if (isFirstRequest(request)) { correlator = logbook.write(new UnauthorizedRawHttpRequest(request)); } else { correlator = readCorrelator(request); } if (correlator.isPresent()) { correlator.get().write(response); } } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final RemoteRequest request = new RemoteRequest(httpRequest); final LocalResponse response = new LocalResponse(httpResponse); chain.doFilter(request, response); if (isUnauthorized(response)) { final Optional<Correlator> correlator; if (isFirstRequest(request)) { correlator = logbook.write(new UnauthorizedRawHttpRequest(request)); } else { correlator = readCorrelator(request); } if (correlator.isPresent()) { correlator.get().write(response); } } }
#vulnerable code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final TeeRequest request = new TeeRequest(httpRequest); final TeeResponse response = new TeeResponse(httpResponse); chain.doFilter(request, response); if (isUnauthorized(response)) { final Optional<Correlator> correlator; if (isFirstRequest(request)) { correlator = logbook.write(new UnauthorizedRawHttpRequest(request)); } else { correlator = readCorrelator(request); } if (correlator.isPresent()) { correlator.get().write(response); } } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final RemoteRequest request = new RemoteRequest(httpRequest); final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request); if (correlator.isPresent()) { final LocalResponse response = new LocalResponse(httpResponse); chain.doFilter(request, response); response.getWriter().flush(); logResponse(correlator.get(), request, response); } else { chain.doFilter(httpRequest, httpResponse); } }
#vulnerable code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final TeeRequest request = new TeeRequest(httpRequest); final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request); if (correlator.isPresent()) { final TeeResponse response = new TeeResponse(httpResponse); chain.doFilter(request, response); response.getWriter().flush(); logResponse(correlator.get(), request, response); } else { chain.doFilter(httpRequest, httpResponse); } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final RemoteRequest request = new RemoteRequest(httpRequest); final LocalResponse response = new LocalResponse(httpResponse); chain.doFilter(request, response); if (isUnauthorized(response)) { final Optional<Correlator> correlator; if (isFirstRequest(request)) { correlator = logbook.write(new UnauthorizedRawHttpRequest(request)); } else { correlator = readCorrelator(request); } if (correlator.isPresent()) { correlator.get().write(response); } } }
#vulnerable code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final TeeRequest request = new TeeRequest(httpRequest); final TeeResponse response = new TeeResponse(httpResponse); chain.doFilter(request, response); if (isUnauthorized(response)) { final Optional<Correlator> correlator; if (isFirstRequest(request)) { correlator = logbook.write(new UnauthorizedRawHttpRequest(request)); } else { correlator = readCorrelator(request); } if (correlator.isPresent()) { correlator.get().write(response); } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldUseSameBody() throws IOException { unit.getOutputStream().write("test".getBytes()); final byte[] body1 = unit.getBody(); final byte[] body2 = unit.getBody(); assertSame(body1, body2); }
#vulnerable code @Test public void shouldUseSameBody() throws IOException { final HttpServletResponse mock = mock(HttpServletResponse.class); when(mock.getOutputStream()).thenReturn(new ServletOutputStream() { @Override public void write(final int b) throws IOException { } }); final LocalResponse response = new LocalResponse(mock, "1"); response.getOutputStream().write("test".getBytes()); final byte[] body1 = response.getBody(); final byte[] body2 = response.getBody(); assertSame(body1, body2); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public HttpRequest withBody() throws IOException { body = ByteStreams.toByteArray(super.getInputStream()); return this; }
#vulnerable code @Override public HttpRequest withBody() throws IOException { body = ByteStreams.toByteArray(getInputStream()); return this; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldUseSameBody() throws IOException { unit.getOutputStream().write("test".getBytes()); final byte[] body1 = unit.getBody(); final byte[] body2 = unit.getBody(); assertSame(body1, body2); }
#vulnerable code @Test public void shouldUseSameBody() throws IOException { final HttpServletResponse mock = mock(HttpServletResponse.class); when(mock.getOutputStream()).thenReturn(new ServletOutputStream() { @Override public void write(final int b) throws IOException { } }); final LocalResponse response = new LocalResponse(mock, "1"); response.getOutputStream().write("test".getBytes()); final byte[] body1 = response.getBody(); final byte[] body2 = response.getBody(); assertSame(body1, body2); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final RemoteRequest request = new RemoteRequest(httpRequest); final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request); if (correlator.isPresent()) { final LocalResponse response = new LocalResponse(httpResponse); chain.doFilter(request, response); response.getWriter().flush(); logResponse(correlator.get(), request, response); } else { chain.doFilter(httpRequest, httpResponse); } }
#vulnerable code @Override public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException { final TeeRequest request = new TeeRequest(httpRequest); final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request); if (correlator.isPresent()) { final TeeResponse response = new TeeResponse(httpResponse); chain.doFilter(request, response); response.getWriter().flush(); logResponse(correlator.get(), request, response); } else { chain.doFilter(httpRequest, httpResponse); } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public PageBean<User> findAll(PageParams pageParams, User user) { QUser qUser = QUser.user; // 用户名查询条件 Predicate qUserNamePredicate = null; if (null != user && StringHelper.isNotBlank(user.getUsername())) { qUserNamePredicate = qUser.username.like("%" + user.getUsername().trim() + "%"); } Predicate predicate = qUser.statu.eq(0).and(qUserNamePredicate); Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")); PageRequest pageRequest = PageUtil.of(pageParams, sort); Page<User> pageList = userRepository.findAll(predicate, pageRequest); if (null != pageList && null != pageList.getContent()) { for (User dbUser : pageList.getContent()) { dbUser.setRoleList(findRoleListByUserId(dbUser.getUserId())); } } return PageUtil.of(pageList); }
#vulnerable code @Override public PageBean<User> findAll(PageParams pageParams, User user) { QUser qUser = QUser.user; // 用户名查询条件 Predicate qUserNamePredicate = null; if (null != user && StringHelper.isNotBlank(user.getUsername())) { qUserNamePredicate = qUser.username.like("%" + user.getUsername().trim() + "%"); } Predicate predicate = qUser.statu.eq(0).and(qUserNamePredicate); Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")); PageRequest pageRequest = new PageRequest(pageParams.getCurrentPage(), pageParams .getPageSize(), sort); Page<User> pageList = userRepository.findAll(predicate, pageRequest); if (null != pageList && null != pageList.getContent()) { for (User dbUser : pageList.getContent()) { dbUser.setRoleList(findRoleListByUserId(dbUser.getUserId())); } } PageBean<User> pageData = new PageBean<User>(); pageData.setCurrentPage(pageParams.getCurrentPage()); pageData.setPageSize(pageParams.getPageSize()); pageData.setTotal(pageList.getTotalElements()); pageData.setList(pageList.getContent()); return pageData; } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public PaginationDTO list(Integer page, Integer size) { PaginationDTO paginationDTO = new PaginationDTO(); Integer totalPage; Integer totalCount = questionMapper.count(); if (totalCount % size == 0) { totalPage = totalCount / size; } else { totalPage = totalCount / size + 1; } if (page < 1) { page = 1; } if (page > totalPage) { page = totalPage; } paginationDTO.setPagination(totalPage, page); //size*(page-1) Integer offset = size * (page - 1); List<Question> questions = questionMapper.list(offset, size); List<QuestionDTO> questionDTOList = new ArrayList<>(); for (Question question : questions) { User user = userMapper.findById(question.getCreator()); QuestionDTO questionDTO = new QuestionDTO(); BeanUtils.copyProperties(question, questionDTO); questionDTO.setUser(user); questionDTOList.add(questionDTO); } paginationDTO.setQuestions(questionDTOList); return paginationDTO; }
#vulnerable code public PaginationDTO list(Integer page, Integer size) { PaginationDTO paginationDTO = new PaginationDTO(); Integer totalCount = questionMapper.count(); paginationDTO.setPagination(totalCount, page, size); if (page < 1) { page = 1; } if (page > paginationDTO.getTotalPage()) { page = paginationDTO.getTotalPage(); } //size*(page-1) Integer offset = size * (page - 1); List<Question> questions = questionMapper.list(offset, size); List<QuestionDTO> questionDTOList = new ArrayList<>(); for (Question question : questions) { User user = userMapper.findById(question.getCreator()); QuestionDTO questionDTO = new QuestionDTO(); BeanUtils.copyProperties(question, questionDTO); questionDTO.setUser(user); questionDTOList.add(questionDTO); } paginationDTO.setQuestions(questionDTOList); return paginationDTO; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long until(final Temporal endExclusive, final TemporalUnit unit) { final PaxDate end = PaxDate.from(endExclusive); if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case YEARS: return yearsUntil(end); case DECADES: return yearsUntil(end) / YEARS_IN_DECADE; case CENTURIES: return yearsUntil(end) / YEARS_IN_CENTURY; case MILLENNIA: return yearsUntil(end) / YEARS_IN_MILLENNIUM; default: break; } } return super.until(end, unit); }
#vulnerable code @Override public long until(final Temporal endExclusive, final TemporalUnit unit) { final PaxDate end = PaxDate.from(endExclusive); if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case DAYS: return daysUntil(end); case WEEKS: return daysUntil(end) / DAYS_IN_WEEK; case MONTHS: return monthsUntil(end); case YEARS: return yearsUntil(end); case DECADES: return yearsUntil(end) / YEARS_IN_DECADE; case CENTURIES: return yearsUntil(end) / YEARS_IN_CENTURY; case MILLENNIA: return yearsUntil(end) / YEARS_IN_MILLENNIUM; case ERAS: return end.getLong(ERA) - getLong(ERA); default: throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } } return unit.between(this, end); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long until(final Temporal endExclusive, final TemporalUnit unit) { final PaxDate end = PaxDate.from(endExclusive); if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case YEARS: return yearsUntil(end); case DECADES: return yearsUntil(end) / YEARS_IN_DECADE; case CENTURIES: return yearsUntil(end) / YEARS_IN_CENTURY; case MILLENNIA: return yearsUntil(end) / YEARS_IN_MILLENNIUM; default: break; } } return super.until(end, unit); }
#vulnerable code @Override public long until(final Temporal endExclusive, final TemporalUnit unit) { final PaxDate end = PaxDate.from(endExclusive); if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case DAYS: return daysUntil(end); case WEEKS: return daysUntil(end) / DAYS_IN_WEEK; case MONTHS: return monthsUntil(end); case YEARS: return yearsUntil(end); case DECADES: return yearsUntil(end) / YEARS_IN_DECADE; case CENTURIES: return yearsUntil(end) / YEARS_IN_CENTURY; case MILLENNIA: return yearsUntil(end) / YEARS_IN_MILLENNIUM; case ERAS: return end.getLong(ERA) - getLong(ERA); default: throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } } return unit.between(this, end); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long until(final Temporal endExclusive, final TemporalUnit unit) { final PaxDate end = PaxDate.from(endExclusive); if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case YEARS: return yearsUntil(end); case DECADES: return yearsUntil(end) / YEARS_IN_DECADE; case CENTURIES: return yearsUntil(end) / YEARS_IN_CENTURY; case MILLENNIA: return yearsUntil(end) / YEARS_IN_MILLENNIUM; default: break; } } return super.until(end, unit); }
#vulnerable code @Override public long until(final Temporal endExclusive, final TemporalUnit unit) { final PaxDate end = PaxDate.from(endExclusive); if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case DAYS: return daysUntil(end); case WEEKS: return daysUntil(end) / DAYS_IN_WEEK; case MONTHS: return monthsUntil(end); case YEARS: return yearsUntil(end); case DECADES: return yearsUntil(end) / YEARS_IN_DECADE; case CENTURIES: return yearsUntil(end) / YEARS_IN_CENTURY; case MILLENNIA: return yearsUntil(end) / YEARS_IN_MILLENNIUM; case ERAS: return end.getLong(ERA) - getLong(ERA); default: throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } } return unit.between(this, end); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void writeSpecRunnerToSourceSpecDirectory() throws IOException { File runnerDestination = new File(jasmineTargetDir,manualSpecRunnerHtmlFileName); String newRunnerHtml = new SpecRunnerHtmlGenerator(scriptsForRunner(), sourceEncoding).generate(ReporterType.TrivialReporter, customRunnerTemplate); if(newRunnerDiffersFromOldRunner(runnerDestination, newRunnerHtml)) { saveRunner(runnerDestination, newRunnerHtml); } else { getLog().info("Skipping spec runner generation, because an identical spec runner already exists."); } }
#vulnerable code private void writeSpecRunnerToSourceSpecDirectory() throws IOException { Set<String> scripts = relativizesASetOfScripts.relativize(jasmineTargetDir, resolvesCompleteListOfScriptLocations.resolve(sources, specs, preloadSources)); SpecRunnerHtmlGenerator htmlGenerator = new SpecRunnerHtmlGenerator(scripts, sourceEncoding); String runner = htmlGenerator.generate(ReporterType.TrivialReporter, customRunnerTemplate); File destination = new File(jasmineTargetDir,manualSpecRunnerHtmlFileName); String existingRunner = loadExistingManualRunner(destination); if(!StringUtils.equals(runner, existingRunner)) { fileUtilsWrapper.writeStringToFile(destination, runner, sourceEncoding); } else { getLog().info("Skipping spec runner generation, because an identical spec runner already exists."); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException { GenericSignatureParser parser = new GenericSignatureParser(); MethodSignature sig1 = parser.parseMethodSignature("<U:Ljava/lang/Foo;>(Ljava/lang/Class<TU;>;TU;)Ljava/lang/Class<+TU;>;"); MethodSignature sig2 = parser.parseMethodSignature("<K:Ljava/lang/Object;V:Ljava/lang/Object;>(Ljava/util/Map<TK;TV;>;Ljava/lang/Class<TK;>;Ljava/lang/Class<TV;>;)Ljava/util/Map<TK;TV;>;"); MethodSignature sig3 = parser.parseMethodSignature("<T:Ljava/lang/Object;>(Ljava/util/Collection<-TT;>;[TT;)Z"); MethodSignature sig4 = parser.parseMethodSignature("(Ljava/util/Collection<*>;Ljava/util/Collection<*>;)Z"); MethodSignature sig7 = parser.parseMethodSignature("()Lcom/sun/xml/internal/bind/v2/model/impl/ElementInfoImpl<Ljava/lang/reflect/Type;Ljava/lang/Class;Ljava/lang/reflect/Field;Ljava/lang/reflect/Method;>.PropertyImpl;"); ClassSignature sig5 = parser.parseClassSignature("<C:Lio/undertow/server/protocol/framed/AbstractFramedChannel<TC;TR;TS;>;R:Lio/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel<TC;TR;TS;>;S:Lio/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel<TC;TR;TS;>;>Ljava/lang/Object;Lorg/xnio/channels/ConnectedChannel;"); ClassSignature sig6 = parser.parseClassSignature("Lcom/apple/laf/AquaUtils$RecyclableSingleton<Ljavax/swing/text/LayeredHighlighter$LayerPainter;>;"); System.out.println(sig1); System.out.println(sig2); System.out.println(sig3); System.out.println(sig4); System.out.println(sig5); System.out.println(sig6); System.out.println(sig7); // BufferedReader reader = new BufferedReader(new FileReader("/Users/jason/sigmethods.txt")); // String line; // while ((line = reader.readLine()) != null) { // try { // System.out.println(parser.parseMethodSignature(line)); // } catch (Exception e) { // System.err.println(line); // e.printStackTrace(System.err); // System.exit(-1); // } // } }
#vulnerable code public static void main(String[] args) throws IOException { GenericSignatureParser parser = new GenericSignatureParser(); // MethodSignature sig1 = parser.parseMethodSignature("<U:Ljava/lang/Object;>(Ljava/lang/Class<TU;>;)Ljava/lang/Class<+TU;>;"); // MethodSignature sig2 = parser.parseMethodSignature("<K:Ljava/lang/Object;V:Ljava/lang/Object;>(Ljava/util/Map<TK;TV;>;Ljava/lang/Class<TK;>;Ljava/lang/Class<TV;>;)Ljava/util/Map<TK;TV;>;"); // MethodSignature sig3 = parser.parseMethodSignature("<T:Ljava/lang/Object;>(Ljava/util/Collection<-TT;>;[TT;)Z"); // MethodSignature sig4 = parser.parseMethodSignature("(Ljava/util/Collection<*>;Ljava/util/Collection<*>;)Z"); //MethodSignature sig7 = parser.parseMethodSignature("()Lcom/sun/xml/internal/bind/v2/model/impl/ElementInfoImpl<Ljava/lang/reflect/Type;Ljava/lang/Class;Ljava/lang/reflect/Field;Ljava/lang/reflect/Method;>.PropertyImpl;"); // ClassSignature sig5 = parser.parseClassSignature("<C:Lio/undertow/server/protocol/framed/AbstractFramedChannel<TC;TR;TS;>;R:Lio/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel<TC;TR;TS;>;S:Lio/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel<TC;TR;TS;>;>Ljava/lang/Object;Lorg/xnio/channels/ConnectedChannel;"); // ClassSignature sig6 = parser.parseClassSignature("Lcom/apple/laf/AquaUtils$RecyclableSingleton<Ljavax/swing/text/LayeredHighlighter$LayerPainter;>;"); // System.out.println(sig1); // System.out.println(sig2); // System.out.println(sig3); // System.out.println(sig4); // System.out.println(sig5); // System.out.println(sig6); // System.out.println(sig7); BufferedReader reader = new BufferedReader(new FileReader("/Users/jason/sigmethods.txt")); String line; while ((line = reader.readLine()) != null) { try { System.out.println(parser.parseMethodSignature(line)); } catch (Exception e) { System.err.println(line); e.printStackTrace(System.err); System.exit(-1); } } } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Index read() throws IOException { if(version == -1) { readVersion(); } IndexReaderImpl reader = getReader(input, version); if (reader == null) { input.close(); throw new UnsupportedVersion("Version: " + version); } return reader.read(version); }
#vulnerable code public Index read() throws IOException { PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input)); if (stream.readInt() != MAGIC) { stream.close(); throw new IllegalArgumentException("Not a jandex index"); } byte version = stream.readByte(); IndexReaderImpl reader = getReader(stream, version); if (reader == null) { stream.close(); throw new UnsupportedVersion("Version: " + version); } return reader.read(version); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Result createJarIndex(File jarFile, Indexer indexer, boolean modify, boolean newJar, boolean verbose) throws IOException { File tmpCopy = null; ZipOutputStream zo = null; OutputStream out = null; File outputFile = null; JarFile jar = new JarFile(jarFile); if (modify) { tmpCopy = File.createTempFile(jarFile.getName().substring(0, jarFile.getName().lastIndexOf('.')), "jmp"); out = zo = new ZipOutputStream(new FileOutputStream(tmpCopy)); } else if (newJar) { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jandex.jar")); out = zo = new ZipOutputStream(new FileOutputStream(outputFile)); } else { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jar") + ".idx"); out = new FileOutputStream( outputFile); } try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (modify) { zo.putNextEntry(entry); copy(jar.getInputStream(entry), zo); } if (entry.getName().endsWith(".class")) { ClassInfo info = indexer.index(jar.getInputStream(entry)); if (verbose && info != null) printIndexEntryInfo(info); } } if (modify || newJar) { zo.putNextEntry(new ZipEntry("META-INF/jandex.idx")); } IndexWriter writer = new IndexWriter(out); Index index = indexer.complete(); int bytes = writer.write(index); out.close(); zo.close(); jar.close(); if (modify) { jarFile.delete(); tmpCopy.renameTo(jarFile); tmpCopy = null; } return new Result(index, modify ? "META-INF/jandex.idx" : outputFile.getPath(), bytes); } finally { out.flush(); out.close(); if (tmpCopy != null) tmpCopy.delete(); } }
#vulnerable code public static Result createJarIndex(File jarFile, Indexer indexer, boolean modify, boolean newJar, boolean verbose) throws IOException { File tmpCopy = null; ZipOutputStream zo = null; OutputStream out = null; File outputFile = null; JarFile jar = new JarFile(jarFile); if (modify) { tmpCopy = File.createTempFile(jarFile.getName().substring(0, jarFile.getName().lastIndexOf('.')), "jmp"); out = zo = new ZipOutputStream(new FileOutputStream(tmpCopy)); } else if (newJar) { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jandex.jar")); out = zo = new ZipOutputStream(new FileOutputStream(outputFile)); } else { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jar") + ".idx"); out = new FileOutputStream( outputFile); } try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (modify) { zo.putNextEntry(entry); copy(jar.getInputStream(entry), zo); } if (entry.getName().endsWith(".class")) { ClassInfo info = indexer.index(jar.getInputStream(entry)); if (verbose && info != null) printIndexEntryInfo(info); } } if (modify || newJar) { zo.putNextEntry(new ZipEntry("META-INF/jandex.idx")); } IndexWriter writer = new IndexWriter(out); Index index = indexer.complete(); int bytes = writer.write(index); if (modify) { jarFile.delete(); tmpCopy.renameTo(jarFile); tmpCopy = null; } return new Result(index, modify ? "META-INF/jandex.idx" : outputFile.getPath(), bytes); } finally { out.flush(); out.close(); if (tmpCopy != null) tmpCopy.delete(); } } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Index read() throws IOException { if(version == -1) { readVersion(); } IndexReaderImpl reader = getReader(input, version); if (reader == null) { input.close(); throw new UnsupportedVersion("Version: " + version); } return reader.read(version); }
#vulnerable code public Index read() throws IOException { PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input)); if (stream.readInt() != MAGIC) { stream.close(); throw new IllegalArgumentException("Not a jandex index"); } byte version = stream.readByte(); IndexReaderImpl reader = getReader(stream, version); if (reader == null) { stream.close(); throw new UnsupportedVersion("Version: " + version); } return reader.read(version); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Index read() throws IOException { if(version == -1) { readVersion(); } IndexReaderImpl reader = getReader(input, version); if (reader == null) { input.close(); throw new UnsupportedVersion("Version: " + version); } return reader.read(version); }
#vulnerable code public Index read() throws IOException { PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input)); if (stream.readInt() != MAGIC) { stream.close(); throw new IllegalArgumentException("Not a jandex index"); } byte version = stream.readByte(); IndexReaderImpl reader = getReader(stream, version); if (reader == null) { stream.close(); throw new UnsupportedVersion("Version: " + version); } return reader.read(version); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Result createJarIndex(File jarFile, Indexer indexer, boolean modify, boolean newJar, boolean verbose) throws IOException { File tmpCopy = null; ZipOutputStream zo = null; OutputStream out = null; File outputFile = null; JarFile jar = new JarFile(jarFile); if (modify) { tmpCopy = File.createTempFile(jarFile.getName().substring(0, jarFile.getName().lastIndexOf('.')) + "00", "jmp"); out = zo = new ZipOutputStream(new FileOutputStream(tmpCopy)); } else if (newJar) { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jandex.jar")); out = zo = new ZipOutputStream(new FileOutputStream(outputFile)); } else { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jar") + ".idx"); out = new FileOutputStream(outputFile); } try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (modify) { zo.putNextEntry(entry); copy(jar.getInputStream(entry), zo); } if (entry.getName().endsWith(".class")) { ClassInfo info = indexer.index(jar.getInputStream(entry)); if (verbose && info != null) printIndexEntryInfo(info); } } if (modify || newJar) { zo.putNextEntry(new ZipEntry("META-INF/jandex.idx")); } IndexWriter writer = new IndexWriter(out); Index index = indexer.complete(); int bytes = writer.write(index); out.flush(); out.close(); jar.close(); if (modify) { jarFile.delete(); tmpCopy.renameTo(jarFile); tmpCopy = null; } return new Result(index, modify ? "META-INF/jandex.idx" : outputFile.getPath(), bytes); } finally { safeClose(out); safeClose(jar); if (tmpCopy != null) tmpCopy.delete(); } }
#vulnerable code public static Result createJarIndex(File jarFile, Indexer indexer, boolean modify, boolean newJar, boolean verbose) throws IOException { File tmpCopy = null; ZipOutputStream zo = null; OutputStream out = null; File outputFile = null; JarFile jar = new JarFile(jarFile); if (modify) { tmpCopy = File.createTempFile(jarFile.getName().substring(0, jarFile.getName().lastIndexOf('.')), "jmp"); out = zo = new ZipOutputStream(new FileOutputStream(tmpCopy)); } else if (newJar) { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jandex.jar")); out = zo = new ZipOutputStream(new FileOutputStream(outputFile)); } else { outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jar") + ".idx"); out = new FileOutputStream( outputFile); } try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (modify) { zo.putNextEntry(entry); copy(jar.getInputStream(entry), zo); } if (entry.getName().endsWith(".class")) { ClassInfo info = indexer.index(jar.getInputStream(entry)); if (verbose && info != null) printIndexEntryInfo(info); } } if (modify || newJar) { zo.putNextEntry(new ZipEntry("META-INF/jandex.idx")); } IndexWriter writer = new IndexWriter(out); Index index = indexer.complete(); int bytes = writer.write(index); out.close(); zo.close(); jar.close(); if (modify) { jarFile.delete(); tmpCopy.renameTo(jarFile); tmpCopy = null; } return new Result(index, modify ? "META-INF/jandex.idx" : outputFile.getPath(), bytes); } finally { out.flush(); out.close(); if (tmpCopy != null) tmpCopy.delete(); } } #location 56 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code String getStream(int streamId) { return streams.get(streamId); }
#vulnerable code LogRecordSet.Writer getLogRecordSetWriter() { return recordSetWriter; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Around("within(@org.springframework.stereotype.Repository *)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { if (this.enabled) { StopWatch sw = new StopWatch(joinPoint.toShortString()); sw.start("invoke"); try { return joinPoint.proceed(); } finally { sw.stop(); synchronized (this) { this.callCount++; this.accumulatedCallTime += sw.getTotalTimeMillis(); } } } else { return joinPoint.proceed(); } }
#vulnerable code @Around("within(@org.springframework.stereotype.Repository *)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { if (this.isEnabled) { StopWatch sw = new StopWatch(joinPoint.toShortString()); sw.start("invoke"); try { return joinPoint.proceed(); } finally { sw.stop(); synchronized (this) { this.callCount++; this.accumulatedCallTime += sw.getTotalTimeMillis(); } } } else { return joinPoint.proceed(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addAllErrors(BindingResult bindingResult) { for (FieldError fieldError : bindingResult.getFieldErrors()) { BindingError error = new BindingError(); error.setObjectName(fieldError.getObjectName()); error.setFieldName(fieldError.getField()); error.setFieldValue(String.valueOf(fieldError.getRejectedValue())); error.setErrorMessage(fieldError.getDefaultMessage()); addError(error); } }
#vulnerable code public void addAllErrors(BindingResult bindingResult) { for (FieldError fieldError : bindingResult.getFieldErrors()) { BindingError error = new BindingError(); error.setObjectName(fieldError.getObjectName()); error.setFieldName(fieldError.getField()); error.setFieldValue(fieldError.getRejectedValue().toString()); error.setErrorMessage(fieldError.getDefaultMessage()); addError(error); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private RestHighLevelClient buildRestHighLevelClient() throws Exception { Collection<HttpHost> hosts = new ArrayList<>(esNodes.length); for (String esNode : esNodes) { hosts.add(HttpHost.create(esNode)); } RestClientBuilder rcb = RestClient.builder(hosts.toArray(new HttpHost[]{})); // We need to check if we have a user security property String securedUser = properties != null ? properties.getProperty(XPACK_USER, null) : null; if (securedUser != null) { // We split the username and the password String[] split = securedUser.split(":"); if (split.length < 2) { throw new IllegalArgumentException(XPACK_USER + " must have the form username:password"); } String username = split[0]; String password = split[1]; final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); rcb.setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(credentialsProvider)); } return new RestHighLevelClient(rcb); }
#vulnerable code private RestHighLevelClient buildRestHighLevelClient() throws Exception { Collection<HttpHost> hosts = new ArrayList<>(esNodes.length); for (String esNode : esNodes) { Tuple<String, Integer> addressPort = toAddress(esNode); hosts.add(new HttpHost(addressPort.v1(), addressPort.v2(), "http")); } RestClientBuilder rcb = RestClient.builder(hosts.toArray(new HttpHost[]{})); // We need to check if we have a user security property String securedUser = properties != null ? properties.getProperty(XPACK_USER, null) : null; if (securedUser != null) { // We split the username and the password String[] split = securedUser.split(":"); if (split.length < 2) { throw new IllegalArgumentException(XPACK_USER + " must have the form username:password"); } String username = split[0]; String password = split[1]; final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); rcb.setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(credentialsProvider)); } return new RestHighLevelClient(rcb); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String readFileInClasspath(String url) throws Exception { StringBuilder bufferJSON = new StringBuilder(); BufferedReader br = null; try { ClassPathResource classPathResource = new ClassPathResource(url); InputStreamReader ipsr = new InputStreamReader(classPathResource.getInputStream()); br = new BufferedReader(ipsr); String line; while ((line = br.readLine()) != null) { bufferJSON.append(line); } } catch (Exception e) { logger.error(String.format("Failed to load file from url: %s", url), e); return null; } finally { if (br != null) br.close(); } return bufferJSON.toString(); }
#vulnerable code public static String readFileInClasspath(String url) throws Exception { StringBuffer bufferJSON = new StringBuffer(); try { InputStream ips= ElasticsearchAbstractClientFactoryBean.class.getResourceAsStream(url); InputStreamReader ipsr = new InputStreamReader(ips); BufferedReader br = new BufferedReader(ipsr); String line; while ((line=br.readLine())!=null){ bufferJSON.append(line); } br.close(); } catch (Exception e){ return null; } return bufferJSON.toString(); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() { }
#vulnerable code @Test public void test() { MessageHandler messageHandler = SpringContextUtil.getBean("MessageHandler","login"); messageHandler.handle(null,null,null,null); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Bean public ExperimentDAO experimentDAO() { LOGGER.debug("Setting up database."); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "/spring/database/database-context.xml"); ExperimentDAO database = context.getBean(ExperimentDAO.class); database.initialize(); context.close(); return database; }
#vulnerable code @Bean public ExperimentDAO experimentDAO() { LOGGER.debug("Setting up database."); ApplicationContext context = new ClassPathXmlApplicationContext("/spring/database/database-context.xml"); return context.getBean(ExperimentDAO.class); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { WikipediaApiInterface wikiAPI = SingletonWikipediaApi.getInstance(); // ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] { new // ExperimentTaskConfiguration( // new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new KnownNIFFileDatasetConfig( // SingletonWikipediaApi.getInstance(), // NIFDatasets.N3_REUTERS_128), ExperimentType.D2KB, // Matching.STRONG_ANNOTATION_MATCH) }; ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] { new ExperimentTaskConfiguration( new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new AIDACoNLLDatasetConfig( AIDACoNLLChunk.TEST_A, SingletonWikipediaApi.getInstance()), ExperimentType.A2KB, Matching.WEAK_ANNOTATION_MATCH), new ExperimentTaskConfiguration( new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new AIDACoNLLDatasetConfig( AIDACoNLLChunk.TEST_B, SingletonWikipediaApi.getInstance()), ExperimentType.A2KB, Matching.WEAK_ANNOTATION_MATCH) }; Experimenter experimenter = new Experimenter(wikiAPI, new SimpleLoggingDAO4Debugging(), taskConfigs, "BABELFY_TEST"); experimenter.run(); }
#vulnerable code public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { WikipediaApiInterface wikiAPI = SingletonWikipediaApi.getInstance(); ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] { new ExperimentTaskConfiguration( new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new KnownNIFFileDatasetConfig( SingletonWikipediaApi.getInstance(), NIFDatasets.N3_REUTERS_128), ExperimentType.D2KB, Matching.STRONG_ANNOTATION_MATCH) }; Experimenter experimenter = new Experimenter(wikiAPI, new SimpleLoggingDAO4Debugging(), taskConfigs, "BABELFY_TEST"); experimenter.run(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateFileCache() { mp3Files = getFileSet(Directories.MP3); aaxFiles = getFileSet(Directories.AAX); needFileCacheUpdate = System.currentTimeMillis(); synchronized (lock) { toDownload.clear(); toConvert.clear(); long seconds = 0; for (Book b : getBooks()) { if (isIgnoredBook(b)) continue; if (canDownload(b)) toDownload.add(b); if (canConvert(b)) toConvert.add(b); seconds += TimeToSeconds.parseTimeStringToSeconds(b.getDuration()); } totalDuration = seconds; } }
#vulnerable code public void updateFileCache() { mp3Files = getFileSet(Directories.MP3); aaxFiles = getFileSet(Directories.AAX); needFileCacheUpdate = System.currentTimeMillis(); HashSet<Book> c = new HashSet<>(); HashSet<Book> d = new HashSet<>(); long seconds = 0; for (Book b : getBooks()) { if (isIgnoredBook(b)) continue; if (canDownload(b)) d.add(b); if (canConvert(b)) c.add(b); seconds += TimeToSeconds.parseTimeStringToSeconds(b.getDuration()); } synchronized (lock) { toDownload.clear(); toDownload.addAll(d); toConvert.clear(); toConvert.addAll(c); totalDuration = seconds; } } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int mp3Count() {synchronized (lock){ return mp3Files.size();} }
#vulnerable code public int mp3Count() { return mp3Files.size(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void explore() { try { Book b = onlyOneSelected(); File m = audible.getMP3FileDest(b); if (m.exists()) { GUI.explore(m); // Desktop.getDesktop().open(m.getParentFile()); } } catch (Throwable th) { showError(th, "showing file in system"); } }
#vulnerable code public void explore() { try { Book b = onlyOneSelected(); File m = audible.getMP3FileDest(b); if (m.exists()) { String mac = "open -R "; String win = "Explorer /select, "; String cmd = null; if (Platform.isMac()) cmd = mac; if (Platform.isWindows()) cmd = win; // TODO: Support linux. if (cmd != null) { cmd += "\"" + m.getAbsolutePath() + "\""; System.err.println(cmd); Runtime.getRuntime().exec(cmd); } // Desktop.getDesktop().open(m.getParentFile()); } } catch (Throwable th) { showError(th, "showing file in system"); } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateFileCache() { mp3Files = getFileSet(Directories.MP3); aaxFiles = getFileSet(Directories.AAX); needFileCacheUpdate = System.currentTimeMillis(); synchronized (lock) { toDownload.clear(); toConvert.clear(); long seconds = 0; for (Book b : getBooks()) { if (isIgnoredBook(b)) continue; if (canDownload(b)) toDownload.add(b); if (canConvert(b)) toConvert.add(b); seconds += TimeToSeconds.parseTimeStringToSeconds(b.getDuration()); } totalDuration = seconds; } }
#vulnerable code public void updateFileCache() { mp3Files = getFileSet(Directories.MP3); aaxFiles = getFileSet(Directories.AAX); needFileCacheUpdate = System.currentTimeMillis(); HashSet<Book> c = new HashSet<>(); HashSet<Book> d = new HashSet<>(); long seconds = 0; for (Book b : getBooks()) { if (isIgnoredBook(b)) continue; if (canDownload(b)) d.add(b); if (canConvert(b)) c.add(b); seconds += TimeToSeconds.parseTimeStringToSeconds(b.getDuration()); } synchronized (lock) { toDownload.clear(); toDownload.addAll(d); toConvert.clear(); toConvert.addAll(c); totalDuration = seconds; } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int aaxCount() { synchronized (lock) { return aaxFiles.size(); } }
#vulnerable code public int aaxCount() { return aaxFiles.size(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void explore(File m) { ArrayList<String>cmdLine = new ArrayList<>(); switch(Platform.getPlatform()) { case mac: cmdLine.add("open"); if (!m.isDirectory()) { cmdLine.add("-R"); } break; case win: cmdLine.add("Explorer "); cmdLine.add("/select,"); break; case linux: cmdLine.add("gnome-open"); cmdLine.add("PATH"); break; } if (cmdLine.isEmpty()) return; try { cmdLine.add(m.getAbsolutePath()); SimpleProcess p = new SimpleProcess(cmdLine); p.run(); Results r = p.getResults(); } catch (Throwable e) { e.printStackTrace(); } }
#vulnerable code public static void explore(File m) { String mac = "open "; String cmd = null; switch(Platform.getPlatform()) { case mac: cmd = "open "; if (!m.isDirectory()) cmd += "-R "; break; case win: cmd = "Explorer /select, "; break; case linux: cmd = "gnome-open PATH "; break; } if (cmd != null) { cmd += "\"" + m.getAbsolutePath() + "\""; System.err.println(cmd); try { Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); } } } #location 26 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); }
#vulnerable code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); } #location 24 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } synchronized (hca) { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); if (entry == null) { return; } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); pool.freeEntry(entry, reusable, validDuration, timeUnit); } } }
#vulnerable code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { //@@@ log as warning? let pass? if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); if (entry != null) { pool.freeEntry(entry, reusable, validDuration, timeUnit); } } } #location 39 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override InputStream decorate(final InputStream wrapped) throws IOException { return new DeflateInputStream(wrapped); }
#vulnerable code @Override InputStream decorate(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it is just a deflate * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers * implement deflate Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else has already read * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception * handling to do this. If that proves slow, then we could potentially change this to check * the first byte - does it look like a CMF? What about the second byte - does it look like * a FLG, etc. */ /* We read a small buffer to sniff the content. */ final byte[] peeked = new byte[6]; final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); final int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ final byte[] dummy = new byte[1]; final Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* Need dictionary - then it must be zlib stream with DICTID part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. Just need to reset * and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater()); } catch (final DataFormatException e) { /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try * again. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater(true)); } finally { inf.end(); } } #location 81 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleReference(Reference<?> ref) { poolLock.lock(); try { if (ref instanceof BasicPoolEntryRef) { // check if the GCed pool entry was still in use //@@@ find a way to detect this without lookup //@@@ flag in the BasicPoolEntryRef, to be reset when freed? final boolean lost = issuedConnections.remove(ref); if (lost) { final HttpRoute route = ((BasicPoolEntryRef)ref).getRoute(); if (LOG.isDebugEnabled()) { LOG.debug("Connection garbage collected. " + route); } handleLostEntry(route); } } } finally { poolLock.unlock(); } }
#vulnerable code public void handleReference(Reference<?> ref) { poolLock.lock(); try { if (ref instanceof BasicPoolEntryRef) { // check if the GCed pool entry was still in use //@@@ find a way to detect this without lookup //@@@ flag in the BasicPoolEntryRef, to be reset when freed? final boolean lost = issuedConnections.remove(ref); if (lost) { final HttpRoute route = ((BasicPoolEntryRef)ref).getRoute(); if (LOG.isDebugEnabled()) { LOG.debug("Connection garbage collected. " + route); } handleLostEntry(route); } } else if (ref instanceof ConnMgrRef) { if (LOG.isDebugEnabled()) { LOG.debug("Connection manager garbage collected."); } shutdown(); } } finally { poolLock.unlock(); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCreateSocket() throws Exception { HttpParams params = new BasicHttpParams(); String password = "changeit"; char[] pwd = password.toCharArray(); RSAPrivateCrtKeySpec k; k = new RSAPrivateCrtKeySpec(new BigInteger(RSA_PUBLIC_MODULUS, 16), new BigInteger(RSA_PUBLIC_EXPONENT, 10), new BigInteger(RSA_PRIVATE_EXPONENT, 16), new BigInteger(RSA_PRIME1, 16), new BigInteger(RSA_PRIME2, 16), new BigInteger(RSA_EXPONENT1, 16), new BigInteger(RSA_EXPONENT2, 16), new BigInteger(RSA_COEFFICIENT, 16)); PrivateKey pk = KeyFactory.getInstance("RSA").generatePrivate(k); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in1, in2, in3; in1 = new ByteArrayInputStream(X509_FOO); in2 = new ByteArrayInputStream(X509_INTERMEDIATE_CA); in3 = new ByteArrayInputStream(X509_ROOT_CA); X509Certificate[] chain = new X509Certificate[3]; chain[0] = (X509Certificate) cf.generateCertificate(in1); chain[1] = (X509Certificate) cf.generateCertificate(in2); chain[2] = (X509Certificate) cf.generateCertificate(in3); ks.setKeyEntry("RSA_KEY", pk, pwd, chain); ks.setCertificateEntry("CERT", chain[2]); // Let's trust ourselves. :-) KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); kmfactory.init(ks, pwd); KeyManager[] keymanagers = kmfactory.getKeyManagers(); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(ks); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); SSLContext sslcontext = SSLContext.getInstance("TLSv1"); sslcontext.init(keymanagers, trustmanagers, null); LocalTestServer server = new LocalTestServer(null, null, null, sslcontext); server.registerDefaultHandlers(); server.start(); try { TestX509HostnameVerifier hostnameVerifier = new TestX509HostnameVerifier(); SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext); socketFactory.setHostnameVerifier(hostnameVerifier); Scheme https = new Scheme("https", socketFactory, 443); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getConnectionManager().getSchemeRegistry().register(https); HttpHost target = new HttpHost( LocalTestServer.TEST_SERVER_ADDR.getHostName(), server.getServicePort(), "https"); HttpGet httpget = new HttpGet("/random/100"); HttpResponse response = httpclient.execute(target, httpget); assertEquals(200, response.getStatusLine().getStatusCode()); assertTrue(hostnameVerifier.isFired()); } finally { server.stop(); } }
#vulnerable code public void testCreateSocket() throws Exception { HttpParams params = new BasicHttpParams(); String password = "changeit"; char[] pwd = password.toCharArray(); RSAPrivateCrtKeySpec k; k = new RSAPrivateCrtKeySpec(new BigInteger(RSA_PUBLIC_MODULUS, 16), new BigInteger(RSA_PUBLIC_EXPONENT, 10), new BigInteger(RSA_PRIVATE_EXPONENT, 16), new BigInteger(RSA_PRIME1, 16), new BigInteger(RSA_PRIME2, 16), new BigInteger(RSA_EXPONENT1, 16), new BigInteger(RSA_EXPONENT2, 16), new BigInteger(RSA_COEFFICIENT, 16)); PrivateKey pk = KeyFactory.getInstance("RSA").generatePrivate(k); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in1, in2, in3; in1 = new ByteArrayInputStream(X509_FOO); in2 = new ByteArrayInputStream(X509_INTERMEDIATE_CA); in3 = new ByteArrayInputStream(X509_ROOT_CA); X509Certificate[] chain = new X509Certificate[3]; chain[0] = (X509Certificate) cf.generateCertificate(in1); chain[1] = (X509Certificate) cf.generateCertificate(in2); chain[2] = (X509Certificate) cf.generateCertificate(in3); ks.setKeyEntry("RSA_KEY", pk, pwd, chain); ks.setCertificateEntry("CERT", chain[2]); // Let's trust ourselves. :-) File tempFile = File.createTempFile("junit", "jks"); try { String path = tempFile.getCanonicalPath(); tempFile.deleteOnExit(); FileOutputStream fOut = new FileOutputStream(tempFile); ks.store(fOut, pwd); fOut.close(); System.setProperty("javax.net.ssl.keyStore", path); System.setProperty("javax.net.ssl.keyStorePassword", password); System.setProperty("javax.net.ssl.trustStore", path); System.setProperty("javax.net.ssl.trustStorePassword", password); ServerSocketFactory server = SSLServerSocketFactory.getDefault(); // Let the operating system just choose an available port: ServerSocket serverSocket = server.createServerSocket(0); serverSocket.setSoTimeout(30000); int port = serverSocket.getLocalPort(); // System.out.println("\nlistening on port: " + port); SSLSocketFactory ssf = SSLSocketFactory.getSocketFactory(); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Test 1 - createSocket() IOException[] e = new IOException[1]; boolean[] success = new boolean[1]; listen(serverSocket, e, success); Socket s = ssf.connectSocket(null, "localhost", port, null, 0, params); exerciseSocket(s, e, success); // Test 2 - createSocket( Socket ), where we upgrade a plain socket // to SSL. success[0] = false; listen(serverSocket, e, success); s = new Socket("localhost", port); s = ssf.createSocket(s, "localhost", port, true); exerciseSocket(s, e, success); } finally { tempFile.delete(); } } #location 69 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(); if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) ) { throw new MethodNotSupportedException (method + " not supported by " + getClass().getName()); } HttpEntity entity = null; if (request instanceof HttpEntityEnclosingRequest) entity = ((HttpEntityEnclosingRequest)request).getEntity(); // For some reason, just putting the incoming entity into // the response will not work. We have to buffer the message. byte[] data = null; if (entity == null) { data = new byte [0]; } else { data = EntityUtils.toByteArray(entity); } ByteArrayEntity bae = new ByteArrayEntity(data); if (entity != null) { bae.setContentType(entity.getContentType()); } entity = bae; response.setStatusCode(HttpStatus.SC_OK); response.setEntity(entity); }
#vulnerable code public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(); if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) ) { throw new MethodNotSupportedException (method + " not supported by " + getClass().getName()); } HttpEntity entity = null; if (request instanceof HttpEntityEnclosingRequest) entity = ((HttpEntityEnclosingRequest)request).getEntity(); // For some reason, just putting the incoming entity into // the response will not work. We have to buffer the message. byte[] data = null; if (entity == null) { data = new byte [0]; } else { data = EntityUtils.toByteArray(entity); } ByteArrayEntity bae = new ByteArrayEntity(data); bae.setContentType(entity.getContentType()); entity = bae; response.setStatusCode(HttpStatus.SC_OK); response.setEntity(entity); } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } synchronized (hca) { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); if (entry == null) { return; } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); pool.freeEntry(entry, reusable, validDuration, timeUnit); } } }
#vulnerable code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { //@@@ log as warning? let pass? if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); if (entry != null) { pool.freeEntry(entry, reusable, validDuration, timeUnit); } } } #location 37 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void shutdown() { synchronized (this) { this.shutdown = true; try { if (this.poolEntry != null) { this.poolEntry.close(); } } finally { this.poolEntry = null; this.conn = null; } } }
#vulnerable code public void shutdown() { this.shutdown = true; synchronized (this) { try { if (this.poolEntry != null) { this.poolEntry.close(); } } finally { this.poolEntry = null; this.conn = null; } } } #location 2 #vulnerability type UNSAFE_GUARDED_BY_ACCESS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static PublicSuffixMatcher load(final URL url) throws IOException { Args.notNull(url, "URL"); final InputStream in = url.openStream(); try { return load(in); } finally { in.close(); } }
#vulnerable code public static PublicSuffixMatcher load(final URL url) throws IOException { Args.notNull(url, "URL"); final InputStream in = url.openStream(); try { final PublicSuffixList list = new PublicSuffixListParser().parse( new InputStreamReader(in, Consts.UTF_8)); return new PublicSuffixMatcher(list.getRules(), list.getExceptions()); } finally { in.close(); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void releaseConnection(final ManagedClientConnection conn, long keepalive, TimeUnit tunit) { if (!(conn instanceof ManagedClientConnectionImpl)) { throw new IllegalArgumentException("Connection class mismatch, " + "connection not obtained from this manager"); } ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn; synchronized (managedConn) { if (this.log.isDebugEnabled()) { this.log.debug("Releasing connection " + conn); } if (managedConn.getPoolEntry() == null) { return; // already released } ClientConnectionManager manager = managedConn.getManager(); if (manager != null && manager != this) { throw new IllegalStateException("Connection not obtained from this manager"); } synchronized (this) { if (this.shutdown) { shutdownConnection(managedConn); return; } try { if (managedConn.isOpen() && !managedConn.isMarkedReusable()) { shutdownConnection(managedConn); } this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS); if (this.log.isDebugEnabled()) { String s; if (keepalive > 0) { s = "for " + keepalive + " " + tunit; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } } finally { managedConn.detach(); this.conn = null; if (this.poolEntry.isClosed()) { this.poolEntry = null; } } } } }
#vulnerable code public void releaseConnection(final ManagedClientConnection conn, long keepalive, TimeUnit tunit) { assertNotShutdown(); if (!(conn instanceof ManagedClientConnectionImpl)) { throw new IllegalArgumentException("Connection class mismatch, " + "connection not obtained from this manager"); } if (this.log.isDebugEnabled()) { this.log.debug("Releasing connection " + conn); } ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn; synchronized (managedConn) { if (managedConn.getPoolEntry() == null) { return; // already released } ClientConnectionManager manager = managedConn.getManager(); if (manager != null && manager != this) { throw new IllegalStateException("Connection not obtained from this manager"); } synchronized (this) { try { if (managedConn.isOpen() && !managedConn.isMarkedReusable()) { try { managedConn.shutdown(); } catch (IOException iox) { if (this.log.isDebugEnabled()) { this.log.debug("I/O exception shutting down released connection", iox); } } } this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS); if (this.log.isDebugEnabled()) { String s; if (keepalive > 0) { s = "for " + keepalive + " " + tunit; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } } finally { managedConn.detach(); this.conn = null; if (this.poolEntry.isClosed()) { this.poolEntry = null; } } } } } #location 8 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override InputStream decorate(final InputStream wrapped) throws IOException { return new DeflateInputStream(wrapped); }
#vulnerable code @Override InputStream decorate(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it is just a deflate * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers * implement deflate Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else has already read * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception * handling to do this. If that proves slow, then we could potentially change this to check * the first byte - does it look like a CMF? What about the second byte - does it look like * a FLG, etc. */ /* We read a small buffer to sniff the content. */ final byte[] peeked = new byte[6]; final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); final int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ final byte[] dummy = new byte[1]; final Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* Need dictionary - then it must be zlib stream with DICTID part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. Just need to reset * and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater()); } catch (final DataFormatException e) { /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try * again. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater(true)); } finally { inf.end(); } } #location 81 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBasicPoolEntry() { HttpRoute route = new HttpRoute(TARGET); ClientConnectionOperator ccop = new DefaultClientConnectionOperator(supportedSchemes); BasicPoolEntry bpe = null; try { bpe = new BasicPoolEntry(null, null, null); fail("null operator not detected"); } catch (NullPointerException npx) { // expected } catch (IllegalArgumentException iax) { // would be preferred } try { bpe = new BasicPoolEntry(ccop, null, null); fail("null route not detected"); } catch (IllegalArgumentException iax) { // expected } bpe = new BasicPoolEntry(ccop, route, null); assertEquals ("wrong route", route, bpe.getPlannedRoute()); assertNotNull("missing ref", bpe.getWeakRef()); assertEquals("bad weak ref", bpe, bpe.getWeakRef().get()); assertEquals("bad ref route", route, bpe.getWeakRef().getRoute()); }
#vulnerable code public void testBasicPoolEntry() { HttpRoute route = new HttpRoute(TARGET); ClientConnectionOperator ccop = new DefaultClientConnectionOperator(supportedSchemes); BasicPoolEntry bpe = null; try { bpe = new BasicPoolEntry(null, null, null); fail("null operator not detected"); } catch (NullPointerException npx) { // expected } catch (IllegalArgumentException iax) { // would be preferred } try { bpe = new BasicPoolEntry(ccop, null, null); fail("null route not detected"); } catch (IllegalArgumentException iax) { // expected } bpe = new BasicPoolEntry(ccop, route, null); assertEquals ("wrong operator", ccop, bpe.getOperator()); assertEquals ("wrong route", route, bpe.getPlannedRoute()); assertNotNull("missing ref", bpe.getWeakRef()); assertEquals("bad weak ref", bpe, bpe.getWeakRef().get()); assertEquals("bad ref route", route, bpe.getWeakRef().getRoute()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override InputStream decorate(final InputStream wrapped) throws IOException { return new DeflateInputStream(wrapped); }
#vulnerable code @Override InputStream decorate(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it is just a deflate * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers * implement deflate Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else has already read * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception * handling to do this. If that proves slow, then we could potentially change this to check * the first byte - does it look like a CMF? What about the second byte - does it look like * a FLG, etc. */ /* We read a small buffer to sniff the content. */ final byte[] peeked = new byte[6]; final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); final int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ final byte[] dummy = new byte[1]; final Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* Need dictionary - then it must be zlib stream with DICTID part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. Just need to reset * and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater()); } catch (final DataFormatException e) { /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try * again. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater(true)); } finally { inf.end(); } } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } synchronized (hca) { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); if (entry == null) { return; } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); pool.freeEntry(entry, reusable, validDuration, timeUnit); } } }
#vulnerable code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { //@@@ log as warning? let pass? if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); if (entry != null) { pool.freeEntry(entry, reusable, validDuration, timeUnit); } } } #location 35 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public synchronized void generate(final StringBuilder buffer) { this.count++; int rndnum = this.rnd.nextInt(); buffer.append(System.currentTimeMillis()); buffer.append('.'); Formatter formatter = new Formatter(buffer, Locale.US); formatter.format("%1$016x-%2$08x", this.count, rndnum); formatter.close(); buffer.append('.'); buffer.append(this.hostname); }
#vulnerable code public synchronized void generate(final StringBuilder buffer) { this.count++; int rndnum = this.rnd.nextInt(); buffer.append(System.currentTimeMillis()); buffer.append('.'); Formatter formatter = new Formatter(buffer, Locale.US); formatter.format("%1$016x-%2$08x", this.count, rndnum); buffer.append('.'); buffer.append(this.hostname); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } synchronized (hca) { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); if (entry == null) { return; } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); pool.freeEntry(entry, reusable, validDuration, timeUnit); } } }
#vulnerable code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { //@@@ log as warning? let pass? if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); if (entry != null) { pool.freeEntry(entry, reusable, validDuration, timeUnit); } } } #location 44 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCloseExpiredTTLConnections() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager( 100, TimeUnit.MILLISECONDS); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); Assert.assertEquals(1, mgr.getTotalStats().getLeased()); Assert.assertEquals(1, mgr.getStats(route).getLeased()); // Release, let remain idle for forever mgr.releaseConnection(conn, null, -1, TimeUnit.MILLISECONDS); // Released, still active. Assert.assertEquals(1, mgr.getTotalStats().getAvailable()); Assert.assertEquals(1, mgr.getStats(route).getAvailable()); mgr.closeExpiredConnections(); // Time has not expired yet. Assert.assertEquals(1, mgr.getTotalStats().getAvailable()); Assert.assertEquals(1, mgr.getStats(route).getAvailable()); Thread.sleep(150); mgr.closeExpiredConnections(); // TTL expired now, connections are destroyed. Assert.assertEquals(0, mgr.getTotalStats().getAvailable()); Assert.assertEquals(0, mgr.getStats(route).getAvailable()); mgr.shutdown(); }
#vulnerable code @Test public void testCloseExpiredTTLConnections() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager( 100, TimeUnit.MILLISECONDS); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); Assert.assertEquals(1, mgr.getTotalStats().getLeased()); Assert.assertEquals(1, mgr.getStats(route).getLeased()); // Release, let remain idle for forever mgr.releaseConnection(conn, null, -1, TimeUnit.MILLISECONDS); // Released, still active. Assert.assertEquals(1, mgr.getTotalStats().getAvailable()); Assert.assertEquals(1, mgr.getStats(route).getAvailable()); mgr.closeExpiredConnections(); // Time has not expired yet. Assert.assertEquals(1, mgr.getTotalStats().getAvailable()); Assert.assertEquals(1, mgr.getStats(route).getAvailable()); Thread.sleep(150); mgr.closeExpiredConnections(); // TTL expired now, connections are destroyed. Assert.assertEquals(0, mgr.getTotalStats().getAvailable()); Assert.assertEquals(0, mgr.getStats(route).getAvailable()); mgr.shutdown(); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateSecureConnection( final OperatedClientConnection conn, final HttpHost target, final HttpContext context, final HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (!conn.isOpen()) { throw new IllegalStateException("Connection must be open"); } final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); if (!(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory)) { throw new IllegalArgumentException ("Target scheme (" + schm.getName() + ") must have layered socket factory."); } SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory(); Socket sock; try { sock = lsf.createLayeredSocket( conn.getSocket(), target.getHostName(), target.getPort(), params); } catch (ConnectException ex) { throw new HttpHostConnectException(target, ex); } prepareSocket(sock, context, params); conn.update(sock, target, lsf.isSecure(sock), params); }
#vulnerable code public void updateSecureConnection( final OperatedClientConnection conn, final HttpHost target, final HttpContext context, final HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (!conn.isOpen()) { throw new IllegalStateException("Connection must be open"); } final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); if (!(schm.getSchemeSocketFactory() instanceof LayeredSchemeSocketFactory)) { throw new IllegalArgumentException ("Target scheme (" + schm.getName() + ") must have layered socket factory."); } LayeredSchemeSocketFactory lsf = (LayeredSchemeSocketFactory) schm.getSchemeSocketFactory(); Socket sock; try { sock = lsf.createLayeredSocket( conn.getSocket(), target.getHostName(), target.getPort(), true); } catch (ConnectException ex) { throw new HttpHostConnectException(target, ex); } prepareSocket(sock, context, params); conn.update(sock, target, lsf.isSecure(sock), params); } #location 29 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); }
#vulnerable code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); } #location 24 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public CloseableHttpResponse execute( final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { redirectLocations.clear(); } final RequestConfig config = context.getRequestConfig(); final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50; HttpRoute currentRoute = route; HttpRequestWrapper currentRequest = request; for (int redirectCount = 0;;) { final CloseableHttpResponse response = requestExecutor.execute( currentRoute, currentRequest, context, execAware); try { if (config.isRedirectsEnabled() && this.redirectStrategy.isRedirected(currentRequest, response, context)) { if (redirectCount >= maxRedirects) { throw new RedirectException("Maximum redirects ("+ maxRedirects + ") exceeded"); } redirectCount++; final HttpRequest redirect = this.redirectStrategy.getRedirect( currentRequest, response, context); if (!redirect.headerIterator().hasNext()) { final HttpRequest original = request.getOriginal(); redirect.setHeaders(original.getAllHeaders()); } currentRequest = HttpRequestWrapper.wrap(redirect); if (currentRequest instanceof HttpEntityEnclosingRequest) { Proxies.enhanceEntity((HttpEntityEnclosingRequest) currentRequest); } final URI uri = currentRequest.getURI(); final HttpHost newTarget = URIUtils.extractHost(uri); if (newTarget == null) { throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri); } // Reset virtual host and auth states if redirecting to another host if (!currentRoute.getTargetHost().equals(newTarget)) { final AuthState targetAuthState = context.getTargetAuthState(); if (targetAuthState != null) { this.log.debug("Resetting target auth state"); targetAuthState.reset(); } final AuthState proxyAuthState = context.getProxyAuthState(); if (proxyAuthState != null) { final AuthScheme authScheme = proxyAuthState.getAuthScheme(); if (authScheme != null && authScheme.isConnectionBased()) { this.log.debug("Resetting proxy auth state"); proxyAuthState.reset(); } } } currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context); if (this.log.isDebugEnabled()) { this.log.debug("Redirecting to '" + uri + "' via " + currentRoute); } EntityUtils.consume(response.getEntity()); response.close(); } else { return response; } } catch (final RuntimeException ex) { response.close(); throw ex; } catch (final IOException ex) { response.close(); throw ex; } catch (final HttpException ex) { // Protocol exception related to a direct. // The underlying connection may still be salvaged. try { EntityUtils.consume(response.getEntity()); } catch (final IOException ioex) { this.log.debug("I/O error while releasing connection", ioex); } finally { response.close(); } throw ex; } } }
#vulnerable code public CloseableHttpResponse execute( final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { redirectLocations.clear(); } final RequestConfig config = context.getRequestConfig(); final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50; HttpRoute currentRoute = route; HttpRequestWrapper currentRequest = request; for (int redirectCount = 0;;) { final CloseableHttpResponse response = requestExecutor.execute( currentRoute, currentRequest, context, execAware); try { if (config.isRedirectsEnabled() && this.redirectStrategy.isRedirected(currentRequest, response, context)) { if (redirectCount >= maxRedirects) { throw new RedirectException("Maximum redirects ("+ maxRedirects + ") exceeded"); } redirectCount++; final HttpRequest redirect = this.redirectStrategy.getRedirect(currentRequest, response, context); final HttpRequest original = currentRequest.getOriginal(); currentRequest = HttpRequestWrapper.wrap(redirect); currentRequest.setHeaders(original.getAllHeaders()); if (original instanceof HttpEntityEnclosingRequest) { Proxies.enhanceEntity((HttpEntityEnclosingRequest) request); } final URI uri = currentRequest.getURI(); final HttpHost newTarget = URIUtils.extractHost(uri); if (newTarget == null) { throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri); } // Reset virtual host and auth states if redirecting to another host if (!currentRoute.getTargetHost().equals(newTarget)) { final AuthState targetAuthState = context.getTargetAuthState(); if (targetAuthState != null) { this.log.debug("Resetting target auth state"); targetAuthState.reset(); } final AuthState proxyAuthState = context.getProxyAuthState(); if (proxyAuthState != null) { final AuthScheme authScheme = proxyAuthState.getAuthScheme(); if (authScheme != null && authScheme.isConnectionBased()) { this.log.debug("Resetting proxy auth state"); proxyAuthState.reset(); } } } currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context); if (this.log.isDebugEnabled()) { this.log.debug("Redirecting to '" + uri + "' via " + currentRoute); } EntityUtils.consume(response.getEntity()); response.close(); } else { return response; } } catch (final RuntimeException ex) { response.close(); throw ex; } catch (final IOException ex) { response.close(); throw ex; } catch (final HttpException ex) { // Protocol exception related to a direct. // The underlying connection may still be salvaged. try { EntityUtils.consume(response.getEntity()); } catch (final IOException ioex) { this.log.debug("I/O error while releasing connection", ioex); } finally { response.close(); } throw ex; } } } #location 34 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CachingHttpClient(HttpClient backend, CacheValidityPolicy validityPolicy, ResponseCachingPolicy responseCachingPolicy, CacheEntryFactory cacheEntryFactory, URIExtractor uriExtractor, HttpCache responseCache, CachedHttpResponseGenerator responseGenerator, CacheInvalidator cacheInvalidator, CacheableRequestPolicy cacheableRequestPolicy, CachedResponseSuitabilityChecker suitabilityChecker, ConditionalRequestBuilder conditionalRequestBuilder, CacheEntryUpdater entryUpdater, ResponseProtocolCompliance responseCompliance, RequestProtocolCompliance requestCompliance) { CacheConfig config = new CacheConfig(); this.maxObjectSizeBytes = config.getMaxObjectSizeBytes(); this.sharedCache = config.isSharedCache(); this.backend = backend; this.cacheEntryFactory = cacheEntryFactory; this.validityPolicy = validityPolicy; this.responseCachingPolicy = responseCachingPolicy; this.uriExtractor = uriExtractor; this.responseCache = responseCache; this.responseGenerator = responseGenerator; this.cacheInvalidator = cacheInvalidator; this.cacheableRequestPolicy = cacheableRequestPolicy; this.suitabilityChecker = suitabilityChecker; this.conditionalRequestBuilder = conditionalRequestBuilder; this.cacheEntryUpdater = entryUpdater; this.responseCompliance = responseCompliance; this.requestCompliance = requestCompliance; }
#vulnerable code HttpResponse handleBackendResponse( HttpHost target, HttpRequest request, Date requestDate, Date responseDate, HttpResponse backendResponse) throws IOException { log.debug("Handling Backend response"); responseCompliance.ensureProtocolCompliance(request, backendResponse); boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse); HttpResponse corrected = backendResponse; if (cacheable) { SizeLimitedResponseReader responseReader = getResponseReader(backendResponse); if (responseReader.isResponseTooLarge()) { return responseReader.getReconstructedResponse(); } byte[] responseBytes = responseReader.getResponseBytes(); corrected = correctIncompleteResponse(backendResponse, responseBytes); int correctedStatus = corrected.getStatusLine().getStatusCode(); if (HttpStatus.SC_BAD_GATEWAY != correctedStatus) { HttpCacheEntry entry = cacheEntryFactory.generate( request.getRequestLine().getUri(), requestDate, responseDate, corrected.getStatusLine(), corrected.getAllHeaders(), responseBytes); storeInCache(target, request, entry); return responseGenerator.generateResponse(entry); } } String uri = uriExtractor.getURI(target, request); responseCache.removeEntry(uri); return corrected; } #location 27 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void shutdown() { poolLock.lock(); try { if (isShutDown) return; // close all connections that are issued to an application Iterator<BasicPoolEntry> iter = leasedConnections.iterator(); while (iter.hasNext()) { BasicPoolEntry entry = iter.next(); iter.remove(); closeConnection(entry.getConnection()); } idleConnHandler.removeAll(); isShutDown = true; } finally { poolLock.unlock(); } }
#vulnerable code public void shutdown() { poolLock.lock(); try { if (isShutDown) return; // no point in monitoring GC anymore if (refWorker != null) refWorker.shutdown(); // close all connections that are issued to an application Iterator<BasicPoolEntryRef> iter = issuedConnections.iterator(); while (iter.hasNext()) { BasicPoolEntryRef per = iter.next(); iter.remove(); BasicPoolEntry entry = per.get(); if (entry != null) { closeConnection(entry.getConnection()); } } // remove all references to connections //@@@ use this for shutting them down instead? idleConnHandler.removeAll(); isShutDown = true; } finally { poolLock.unlock(); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Socket connectSocket( final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock = socket != null ? socket : this.socketfactory.createSocket(); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } String hostname; if (remoteAddress instanceof HttpInetSocketAddress) { hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { hostname = remoteAddress.getHostName(); } SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslsock = (SSLSocket) this.socketfactory.createSocket(sock, hostname, port, true); prepareSocket(sslsock); } if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(hostname, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } } return sslsock; }
#vulnerable code public Socket connectSocket( final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock = socket != null ? socket : new Socket(); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } String hostname; if (remoteAddress instanceof HttpInetSocketAddress) { hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { hostname = remoteAddress.getHostName(); } SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslsock = (SSLSocket) this.socketfactory.createSocket(sock, hostname, port, true); prepareSocket(sslsock); } if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(hostname, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } } return sslsock; } #location 41 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAbortBeforeSocketCreate() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(1); final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( connectLatch, WaitPolicy.BEFORE_CREATE, PlainSocketFactory.getSocketFactory()); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", stallingSocketFactory) .build(); final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(registry); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>(); final Thread abortingThread = new Thread(new Runnable() { public void run() { try { stallingSocketFactory.waitForState(); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); connectLatch.countDown(); } catch (final Throwable e) { throwRef.set(e); } } }); abortingThread.start(); try { mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); Assert.fail("IOException expected"); } catch(final IOException expected) { } abortingThread.join(5000); if(throwRef.get() != null) { throw new RuntimeException(throwRef.get()); } Assert.assertFalse(conn.isOpen()); Assert.assertEquals(0, localServer.getAcceptedConnectionCount()); // the connection is expected to be released back to the manager final HttpClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn2.isOpen()); mgr.releaseConnection(conn2, null, -1, null); mgr.shutdown(); }
#vulnerable code @Test public void testAbortBeforeSocketCreate() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(1); final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( connectLatch, WaitPolicy.BEFORE_CREATE, PlainSocketFactory.getSocketFactory()); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", stallingSocketFactory) .build(); final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(registry); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>(); final Thread abortingThread = new Thread(new Runnable() { public void run() { try { stallingSocketFactory.waitForState(); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); connectLatch.countDown(); } catch (final Throwable e) { throwRef.set(e); } } }); abortingThread.start(); try { mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); Assert.fail("IOException expected"); } catch(final IOException expected) { } abortingThread.join(5000); if(throwRef.get() != null) { throw new RuntimeException(throwRef.get()); } Assert.assertFalse(conn.isOpen()); Assert.assertEquals(0, localServer.getAcceptedConnectionCount()); // the connection is expected to be released back to the manager final HttpClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn2.isOpen()); mgr.releaseConnection(conn2, null, -1, null); mgr.shutdown(); } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); }
#vulnerable code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); } #location 24 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void close() { if (this.closeables != null) { for (final Closeable closeable: this.closeables) { try { closeable.close(); } catch (final IOException ex) { this.log.error(ex.getMessage(), ex); } } } }
#vulnerable code @Override public void close() { this.connManager.shutdown(); if (this.closeables != null) { for (final Closeable closeable: this.closeables) { try { closeable.close(); } catch (final IOException ex) { this.log.error(ex.getMessage(), ex); } } } } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CachingHttpClient(HttpClient backend, CacheValidityPolicy validityPolicy, ResponseCachingPolicy responseCachingPolicy, CacheEntryFactory cacheEntryFactory, URIExtractor uriExtractor, HttpCache responseCache, CachedHttpResponseGenerator responseGenerator, CacheInvalidator cacheInvalidator, CacheableRequestPolicy cacheableRequestPolicy, CachedResponseSuitabilityChecker suitabilityChecker, ConditionalRequestBuilder conditionalRequestBuilder, CacheEntryUpdater entryUpdater, ResponseProtocolCompliance responseCompliance, RequestProtocolCompliance requestCompliance) { CacheConfig config = new CacheConfig(); this.maxObjectSizeBytes = config.getMaxObjectSizeBytes(); this.sharedCache = config.isSharedCache(); this.backend = backend; this.cacheEntryFactory = cacheEntryFactory; this.validityPolicy = validityPolicy; this.responseCachingPolicy = responseCachingPolicy; this.uriExtractor = uriExtractor; this.responseCache = responseCache; this.responseGenerator = responseGenerator; this.cacheInvalidator = cacheInvalidator; this.cacheableRequestPolicy = cacheableRequestPolicy; this.suitabilityChecker = suitabilityChecker; this.conditionalRequestBuilder = conditionalRequestBuilder; this.cacheEntryUpdater = entryUpdater; this.responseCompliance = responseCompliance; this.requestCompliance = requestCompliance; }
#vulnerable code HttpCacheEntry doGetUpdatedParentEntry( final String requestId, final HttpCacheEntry existing, final HttpCacheEntry entry, final String variantURI) throws IOException { if (existing != null) { return cacheEntryFactory.copyVariant(requestId, existing, variantURI); } else { return cacheEntryFactory.copyVariant(requestId, entry, variantURI); } } #location 7 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code ManagedClientConnection getConnection(final HttpRoute route, final Object state) { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } synchronized (this) { assertNotShutdown(); if (this.log.isDebugEnabled()) { this.log.debug("Get connection for route " + route); } if (this.conn != null) { throw new IllegalStateException(MISUSE_MESSAGE); } if (this.poolEntry != null && !this.poolEntry.getPlannedRoute().equals(route)) { this.poolEntry.close(); this.poolEntry = null; } if (this.poolEntry == null) { String id = Long.toString(COUNTER.getAndIncrement()); OperatedClientConnection conn = this.connOperator.createConnection(); this.poolEntry = new HttpPoolEntry(this.log, id, route, conn, 0, TimeUnit.MILLISECONDS); } long now = System.currentTimeMillis(); if (this.poolEntry.isExpired(now)) { this.poolEntry.close(); this.poolEntry.getTracker().reset(); } this.conn = new ManagedClientConnectionImpl(this, this.connOperator, this.poolEntry); return this.conn; } }
#vulnerable code ManagedClientConnection getConnection(final HttpRoute route, final Object state) { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } assertNotShutdown(); if (this.log.isDebugEnabled()) { this.log.debug("Get connection for route " + route); } synchronized (this) { if (this.conn != null) { throw new IllegalStateException(MISUSE_MESSAGE); } if (this.poolEntry != null && !this.poolEntry.getPlannedRoute().equals(route)) { this.poolEntry.close(); this.poolEntry = null; } if (this.poolEntry == null) { String id = Long.toString(COUNTER.getAndIncrement()); OperatedClientConnection conn = this.connOperator.createConnection(); this.poolEntry = new HttpPoolEntry(this.log, id, route, conn, 0, TimeUnit.MILLISECONDS); } long now = System.currentTimeMillis(); if (this.poolEntry.isExpired(now)) { this.poolEntry.close(); this.poolEntry.getTracker().reset(); } this.conn = new ManagedClientConnectionImpl(this, this.connOperator, this.poolEntry); return this.conn; } } #location 7 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReleaseConnectionOnAbort() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final int rsplen = 8; final String uri = "/random/" + rsplen; final HttpContext context = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); HttpClientConnection conn = getConnection(mgr, route); mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); final HttpProcessor httpProcessor = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() }); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); final HttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // check that there are no connections available try { // this should fail quickly, connection has not been released getConnection(mgr, route, 100L, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException e) { // expected } // abort the connection Assert.assertTrue(conn instanceof HttpClientConnection); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); // the connection is expected to be released back to the manager conn = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn.isOpen()); mgr.releaseConnection(conn, null, -1, null); mgr.shutdown(); }
#vulnerable code @Test public void testReleaseConnectionOnAbort() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final int rsplen = 8; final String uri = "/random/" + rsplen; final HttpContext context = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); HttpClientConnection conn = getConnection(mgr, route); mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); final HttpProcessor httpProcessor = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() }); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); final HttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // check that there are no connections available try { // this should fail quickly, connection has not been released getConnection(mgr, route, 100L, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException e) { // expected } // abort the connection Assert.assertTrue(conn instanceof HttpClientConnection); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); // the connection is expected to be released back to the manager conn = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn.isOpen()); mgr.releaseConnection(conn, null, -1, null); mgr.shutdown(); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CachingExec( final ClientExecChain backend, final HttpCache responseCache, final CacheValidityPolicy validityPolicy, final ResponseCachingPolicy responseCachingPolicy, final CachedHttpResponseGenerator responseGenerator, final CacheableRequestPolicy cacheableRequestPolicy, final CachedResponseSuitabilityChecker suitabilityChecker, final ConditionalRequestBuilder conditionalRequestBuilder, final ResponseProtocolCompliance responseCompliance, final RequestProtocolCompliance requestCompliance, final CacheConfig config, final AsynchronousValidator asynchRevalidator) { this.cacheConfig = config != null ? config : CacheConfig.DEFAULT; this.backend = backend; this.responseCache = responseCache; this.validityPolicy = validityPolicy; this.responseCachingPolicy = responseCachingPolicy; this.responseGenerator = responseGenerator; this.cacheableRequestPolicy = cacheableRequestPolicy; this.suitabilityChecker = suitabilityChecker; this.conditionalRequestBuilder = conditionalRequestBuilder; this.responseCompliance = responseCompliance; this.requestCompliance = requestCompliance; this.asynchRevalidator = asynchRevalidator; }
#vulnerable code CloseableHttpResponse revalidateCacheEntry( final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry cacheEntry) throws IOException, HttpException { final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry); final URI uri = conditionalRequest.getURI(); if (uri != null) { try { request.setURI(URIUtils.rewriteURIForRoute(uri, route)); } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + uri, ex); } } Date requestDate = getCurrentDate(); CloseableHttpResponse backendResponse = backend.execute( route, conditionalRequest, context, execAware); Date responseDate = getCurrentDate(); if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) { backendResponse.close(); final HttpRequestWrapper unconditional = conditionalRequestBuilder .buildUnconditionalRequest(request, cacheEntry); requestDate = getCurrentDate(); backendResponse = backend.execute(route, unconditional, context, execAware); responseDate = getCurrentDate(); } backendResponse.addHeader(HeaderConstants.VIA, generateViaHeader(backendResponse)); final int statusCode = backendResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) { recordCacheUpdate(context); } if (statusCode == HttpStatus.SC_NOT_MODIFIED) { final HttpCacheEntry updatedEntry = responseCache.updateCacheEntry( context.getTargetHost(), request, cacheEntry, backendResponse, requestDate, responseDate); if (suitabilityChecker.isConditional(request) && suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) { return responseGenerator .generateNotModifiedResponse(updatedEntry); } return responseGenerator.generateResponse(updatedEntry); } if (staleIfErrorAppliesTo(statusCode) && !staleResponseNotAllowed(request, cacheEntry, getCurrentDate()) && validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) { try { final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry); cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\""); return cachedResponse; } finally { backendResponse.close(); } } return handleBackendResponse(conditionalRequest, context, requestDate, responseDate, backendResponse); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = SchemeRegistryFactory.createDefault(); ClientConnectionManager connManager = null; HttpParams params = getParams(); ClientConnectionManagerFactory factory = null; String className = (String) params.getParameter( ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME); if (className != null) { try { Class<?> clazz = Class.forName(className); factory = (ClientConnectionManagerFactory) clazz.newInstance(); } catch (ClassNotFoundException ex) { throw new IllegalStateException("Invalid class name: " + className); } catch (IllegalAccessException ex) { throw new IllegalAccessError(ex.getMessage()); } catch (InstantiationException ex) { throw new InstantiationError(ex.getMessage()); } } if (factory != null) { connManager = factory.newInstance(params, registry); } else { connManager = new PoolingClientConnectionManager(registry); } return connManager; }
#vulnerable code protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = SchemeRegistryFactory.createDefault(); ClientConnectionManager connManager = null; HttpParams params = getParams(); ClientConnectionManagerFactory factory = null; String className = (String) params.getParameter( ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME); if (className != null) { try { Class<?> clazz = Class.forName(className); factory = (ClientConnectionManagerFactory) clazz.newInstance(); } catch (ClassNotFoundException ex) { throw new IllegalStateException("Invalid class name: " + className); } catch (IllegalAccessException ex) { throw new IllegalAccessError(ex.getMessage()); } catch (InstantiationException ex) { throw new InstantiationError(ex.getMessage()); } } if (factory != null) { connManager = factory.newInstance(params, registry); } else { connManager = new SingleClientConnManager(registry); } return connManager; } #location 26 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } synchronized (hca) { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); if (entry == null) { return; } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); pool.freeEntry(entry, reusable, validDuration, timeUnit); } } }
#vulnerable code public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { //@@@ log as warning? let pass? if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); if (entry != null) { pool.freeEntry(entry, reusable, validDuration, timeUnit); } } } #location 25 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void releaseConnection(final ManagedClientConnection conn, long keepalive, TimeUnit tunit) { if (!(conn instanceof ManagedClientConnectionImpl)) { throw new IllegalArgumentException("Connection class mismatch, " + "connection not obtained from this manager"); } ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn; synchronized (managedConn) { if (this.log.isDebugEnabled()) { this.log.debug("Releasing connection " + conn); } if (managedConn.getPoolEntry() == null) { return; // already released } ClientConnectionManager manager = managedConn.getManager(); if (manager != null && manager != this) { throw new IllegalStateException("Connection not obtained from this manager"); } synchronized (this) { if (this.shutdown) { shutdownConnection(managedConn); return; } try { if (managedConn.isOpen() && !managedConn.isMarkedReusable()) { shutdownConnection(managedConn); } this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS); if (this.log.isDebugEnabled()) { String s; if (keepalive > 0) { s = "for " + keepalive + " " + tunit; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } } finally { managedConn.detach(); this.conn = null; if (this.poolEntry.isClosed()) { this.poolEntry = null; } } } } }
#vulnerable code public void releaseConnection(final ManagedClientConnection conn, long keepalive, TimeUnit tunit) { assertNotShutdown(); if (!(conn instanceof ManagedClientConnectionImpl)) { throw new IllegalArgumentException("Connection class mismatch, " + "connection not obtained from this manager"); } if (this.log.isDebugEnabled()) { this.log.debug("Releasing connection " + conn); } ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn; synchronized (managedConn) { if (managedConn.getPoolEntry() == null) { return; // already released } ClientConnectionManager manager = managedConn.getManager(); if (manager != null && manager != this) { throw new IllegalStateException("Connection not obtained from this manager"); } synchronized (this) { try { if (managedConn.isOpen() && !managedConn.isMarkedReusable()) { try { managedConn.shutdown(); } catch (IOException iox) { if (this.log.isDebugEnabled()) { this.log.debug("I/O exception shutting down released connection", iox); } } } this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS); if (this.log.isDebugEnabled()) { String s; if (keepalive > 0) { s = "for " + keepalive + " " + tunit; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } } finally { managedConn.detach(); this.conn = null; if (this.poolEntry.isClosed()) { this.poolEntry = null; } } } } } #location 7 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CachingExec( final ClientExecChain backend, final HttpCache responseCache, final CacheValidityPolicy validityPolicy, final ResponseCachingPolicy responseCachingPolicy, final CachedHttpResponseGenerator responseGenerator, final CacheableRequestPolicy cacheableRequestPolicy, final CachedResponseSuitabilityChecker suitabilityChecker, final ConditionalRequestBuilder conditionalRequestBuilder, final ResponseProtocolCompliance responseCompliance, final RequestProtocolCompliance requestCompliance, final CacheConfig config, final AsynchronousValidator asynchRevalidator) { this.cacheConfig = config != null ? config : CacheConfig.DEFAULT; this.backend = backend; this.responseCache = responseCache; this.validityPolicy = validityPolicy; this.responseCachingPolicy = responseCachingPolicy; this.responseGenerator = responseGenerator; this.cacheableRequestPolicy = cacheableRequestPolicy; this.suitabilityChecker = suitabilityChecker; this.conditionalRequestBuilder = conditionalRequestBuilder; this.responseCompliance = responseCompliance; this.requestCompliance = requestCompliance; this.asynchRevalidator = asynchRevalidator; }
#vulnerable code CloseableHttpResponse handleBackendResponse( final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware, final Date requestDate, final Date responseDate, final CloseableHttpResponse backendResponse) throws IOException { log.trace("Handling Backend response"); responseCompliance.ensureProtocolCompliance(request, backendResponse); final HttpHost target = route.getTargetHost(); final boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse); responseCache.flushInvalidatedCacheEntriesFor(target, request, backendResponse); if (cacheable && !alreadyHaveNewerCacheEntry(target, request, backendResponse)) { try { storeRequestIfModifiedSinceFor304Response(request, backendResponse); return Proxies.enhanceResponse(responseCache.cacheAndReturnResponse( target, request, backendResponse, requestDate, responseDate)); } finally { backendResponse.close(); } } if (!cacheable) { try { responseCache.flushCacheEntriesFor(target, request); } catch (final IOException ioe) { log.warn("Unable to flush invalid cache entries", ioe); } } return backendResponse; } #location 22 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateSecureConnection( final OperatedClientConnection conn, final HttpHost target, final HttpContext context, final HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (!conn.isOpen()) { throw new IllegalStateException("Connection must be open"); } final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); if (!(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory)) { throw new IllegalArgumentException ("Target scheme (" + schm.getName() + ") must have layered socket factory."); } SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory(); Socket sock; try { sock = lsf.createLayeredSocket( conn.getSocket(), target.getHostName(), target.getPort(), params); } catch (ConnectException ex) { throw new HttpHostConnectException(target, ex); } prepareSocket(sock, context, params); conn.update(sock, target, lsf.isSecure(sock), params); }
#vulnerable code public void updateSecureConnection( final OperatedClientConnection conn, final HttpHost target, final HttpContext context, final HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (!conn.isOpen()) { throw new IllegalStateException("Connection must be open"); } final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); if (!(schm.getSchemeSocketFactory() instanceof LayeredSchemeSocketFactory)) { throw new IllegalArgumentException ("Target scheme (" + schm.getName() + ") must have layered socket factory."); } LayeredSchemeSocketFactory lsf = (LayeredSchemeSocketFactory) schm.getSchemeSocketFactory(); Socket sock; try { sock = lsf.createLayeredSocket( conn.getSocket(), target.getHostName(), target.getPort(), true); } catch (ConnectException ex) { throw new HttpHostConnectException(target, ex); } prepareSocket(sock, context, params); conn.update(sock, target, lsf.isSecure(sock), params); } #location 35 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void doWriteTo( final HttpMultipartMode mode, final OutputStream out, boolean writeContent) throws IOException { List<BodyPart> bodyParts = getBodyParts(); Charset charset = getCharset(); ByteArrayBuffer boundary = encode(charset, getBoundary()); switch (mode) { case STRICT: String preamble = getPreamble(); if (preamble != null && preamble.length() != 0) { ByteArrayBuffer b = encode(charset, preamble); writeBytes(b, out); writeBytes(CR_LF, out); } for (int i = 0; i < bodyParts.size(); i++) { writeBytes(TWO_DASHES, out); writeBytes(boundary, out); writeBytes(CR_LF, out); BodyPart part = bodyParts.get(i); Header header = part.getHeader(); List<Field> fields = header.getFields(); for (Field field: fields) { writeBytes(field.getRaw(), out); writeBytes(CR_LF, out); } writeBytes(CR_LF, out); if (writeContent) { MessageWriter.DEFAULT.writeBody(part.getBody(), out); } writeBytes(CR_LF, out); } writeBytes(TWO_DASHES, out); writeBytes(boundary, out); writeBytes(TWO_DASHES, out); writeBytes(CR_LF, out); String epilogue = getEpilogue(); if (epilogue != null && epilogue.length() != 0) { ByteArrayBuffer b = encode(charset, epilogue); writeBytes(b, out); writeBytes(CR_LF, out); } break; case BROWSER_COMPATIBLE: // (1) Do not write preamble and epilogue // (2) Only write Content-Disposition // (3) Use content charset for (int i = 0; i < bodyParts.size(); i++) { writeBytes(TWO_DASHES, out); writeBytes(boundary, out); writeBytes(CR_LF, out); BodyPart part = (BodyPart) bodyParts.get(i); Field cd = part.getHeader().getField(MIME.CONTENT_DISPOSITION); StringBuilder s = new StringBuilder(); s.append(cd.getName()); s.append(": "); s.append(cd.getBody()); writeBytes(encode(charset, s.toString()), out); writeBytes(CR_LF, out); writeBytes(CR_LF, out); if (writeContent) { MessageWriter.DEFAULT.writeBody(part.getBody(), out); } writeBytes(CR_LF, out); } writeBytes(TWO_DASHES, out); writeBytes(boundary, out); writeBytes(TWO_DASHES, out); writeBytes(CR_LF, out); break; } }
#vulnerable code private void doWriteTo( final HttpMultipartMode mode, final OutputStream out, boolean writeContent) throws IOException { List<?> bodyParts = getBodyParts(); Charset charset = getCharset(); String boundary = getBoundary(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(out, charset), 8192); switch (mode) { case STRICT: String preamble = getPreamble(); if (preamble != null && preamble.length() != 0) { writer.write(preamble); writer.write("\r\n"); } for (int i = 0; i < bodyParts.size(); i++) { writer.write("--"); writer.write(boundary); writer.write("\r\n"); writer.flush(); BodyPart part = (BodyPart) bodyParts.get(i); part.getHeader().writeTo(out, MessageUtils.STRICT_IGNORE); if (writeContent) { part.getBody().writeTo(out, MessageUtils.STRICT_IGNORE); } writer.write("\r\n"); } writer.write("--"); writer.write(boundary); writer.write("--\r\n"); String epilogue = getEpilogue(); if (epilogue != null && epilogue.length() != 0) { writer.write(epilogue); writer.write("\r\n"); } writer.flush(); break; case BROWSER_COMPATIBLE: // (1) Do not write preamble and epilogue // (2) Only write Content-Disposition // (3) Use content charset for (int i = 0; i < bodyParts.size(); i++) { writer.write("--"); writer.write(boundary); writer.write("\r\n"); writer.flush(); BodyPart part = (BodyPart) bodyParts.get(i); Field cd = part.getHeader().getField(MIME.CONTENT_DISPOSITION); writer.write(cd.toString()); writer.write("\r\n"); writer.write("\r\n"); writer.flush(); if (writeContent) { part.getBody().writeTo(out, MessageUtils.LENIENT); } writer.write("\r\n"); } writer.write("--"); writer.write(boundary); writer.write("--\r\n"); writer.flush(); break; } } #location 26 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); }
#vulnerable code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); } #location 24 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CachingHttpClient(HttpClient backend, CacheValidityPolicy validityPolicy, ResponseCachingPolicy responseCachingPolicy, CacheEntryFactory cacheEntryFactory, URIExtractor uriExtractor, HttpCache responseCache, CachedHttpResponseGenerator responseGenerator, CacheInvalidator cacheInvalidator, CacheableRequestPolicy cacheableRequestPolicy, CachedResponseSuitabilityChecker suitabilityChecker, ConditionalRequestBuilder conditionalRequestBuilder, CacheEntryUpdater entryUpdater, ResponseProtocolCompliance responseCompliance, RequestProtocolCompliance requestCompliance) { CacheConfig config = new CacheConfig(); this.maxObjectSizeBytes = config.getMaxObjectSizeBytes(); this.sharedCache = config.isSharedCache(); this.backend = backend; this.cacheEntryFactory = cacheEntryFactory; this.validityPolicy = validityPolicy; this.responseCachingPolicy = responseCachingPolicy; this.uriExtractor = uriExtractor; this.responseCache = responseCache; this.responseGenerator = responseGenerator; this.cacheInvalidator = cacheInvalidator; this.cacheableRequestPolicy = cacheableRequestPolicy; this.suitabilityChecker = suitabilityChecker; this.conditionalRequestBuilder = conditionalRequestBuilder; this.cacheEntryUpdater = entryUpdater; this.responseCompliance = responseCompliance; this.requestCompliance = requestCompliance; }
#vulnerable code HttpCacheEntry doGetUpdatedParentEntry( final String requestId, final HttpCacheEntry existing, final HttpCacheEntry entry, final String variantURI) throws IOException { if (existing != null) { return cacheEntryFactory.copyVariant(requestId, existing, variantURI); } else { return cacheEntryFactory.copyVariant(requestId, entry, variantURI); } } #location 9 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAbortAfterSocketConnect() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(1); final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( connectLatch, WaitPolicy.AFTER_CONNECT, PlainSocketFactory.getSocketFactory()); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", stallingSocketFactory) .build(); final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(registry); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>(); final Thread abortingThread = new Thread(new Runnable() { public void run() { try { stallingSocketFactory.waitForState(); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); connectLatch.countDown(); } catch (final Throwable e) { throwRef.set(e); } } }); abortingThread.start(); try { mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); Assert.fail("IOException expected"); } catch(final IOException expected) { } abortingThread.join(5000); if(throwRef.get() != null) { throw new RuntimeException(throwRef.get()); } Assert.assertFalse(conn.isOpen()); // Give the server a bit of time to accept the connection, but // ensure that it can accept it. for(int i = 0; i < 10; i++) { if(localServer.getAcceptedConnectionCount() == 1) { break; } Thread.sleep(100); } Assert.assertEquals(1, localServer.getAcceptedConnectionCount()); // the connection is expected to be released back to the manager final HttpClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn2.isOpen()); mgr.releaseConnection(conn2, null, -1, null); mgr.shutdown(); }
#vulnerable code @Test public void testAbortAfterSocketConnect() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(1); final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( connectLatch, WaitPolicy.AFTER_CONNECT, PlainSocketFactory.getSocketFactory()); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", stallingSocketFactory) .build(); final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(registry); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>(); final Thread abortingThread = new Thread(new Runnable() { public void run() { try { stallingSocketFactory.waitForState(); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); connectLatch.countDown(); } catch (final Throwable e) { throwRef.set(e); } } }); abortingThread.start(); try { mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); Assert.fail("IOException expected"); } catch(final IOException expected) { } abortingThread.join(5000); if(throwRef.get() != null) { throw new RuntimeException(throwRef.get()); } Assert.assertFalse(conn.isOpen()); // Give the server a bit of time to accept the connection, but // ensure that it can accept it. for(int i = 0; i < 10; i++) { if(localServer.getAcceptedConnectionCount() == 1) { break; } Thread.sleep(100); } Assert.assertEquals(1, localServer.getAcceptedConnectionCount()); // the connection is expected to be released back to the manager final HttpClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn2.isOpen()); mgr.releaseConnection(conn2, null, -1, null); mgr.shutdown(); } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override InputStream decorate(final InputStream wrapped) throws IOException { return new DeflateInputStream(wrapped); }
#vulnerable code @Override InputStream decorate(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it is just a deflate * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers * implement deflate Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else has already read * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception * handling to do this. If that proves slow, then we could potentially change this to check * the first byte - does it look like a CMF? What about the second byte - does it look like * a FLG, etc. */ /* We read a small buffer to sniff the content. */ final byte[] peeked = new byte[6]; final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); final int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ final byte[] dummy = new byte[1]; final Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* Need dictionary - then it must be zlib stream with DICTID part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. Just need to reset * and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater()); } catch (final DataFormatException e) { /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try * again. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater(true)); } finally { inf.end(); } } #location 36 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Before public void setUp() throws Exception { final ClassLoader classLoader = getClass().getClassLoader(); final InputStream in = classLoader.getResourceAsStream(SOURCE_FILE); Assert.assertNotNull(in); final PublicSuffixList suffixList; try { final org.apache.http.conn.util.PublicSuffixListParser parser = new org.apache.http.conn.util.PublicSuffixListParser(); suffixList = parser.parse(new InputStreamReader(in, Consts.UTF_8)); } finally { in.close(); } final PublicSuffixMatcher matcher = new PublicSuffixMatcher(suffixList.getRules(), suffixList.getExceptions()); this.filter = new PublicSuffixDomainFilter(new RFC2109DomainHandler(), matcher); }
#vulnerable code @Before public void setUp() throws Exception { final Reader r = new InputStreamReader(getClass().getResourceAsStream(LIST_FILE), "UTF-8"); filter = new PublicSuffixFilter(new RFC2109DomainHandler()); final PublicSuffixListParser parser = new PublicSuffixListParser(filter); parser.parse(r); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override InputStream decorate(final InputStream wrapped) throws IOException { return new DeflateInputStream(wrapped); }
#vulnerable code @Override InputStream decorate(final InputStream wrapped) throws IOException { /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it is just a deflate * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers * implement deflate Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else has already read * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception * handling to do this. If that proves slow, then we could potentially change this to check * the first byte - does it look like a CMF? What about the second byte - does it look like * a FLG, etc. */ /* We read a small buffer to sniff the content. */ final byte[] peeked = new byte[6]; final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); final int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ final byte[] dummy = new byte[1]; final Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* Need dictionary - then it must be zlib stream with DICTID part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. Just need to reset * and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater()); } catch (final DataFormatException e) { /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try * again. */ pushback.unread(peeked, 0, headerLength); return new DeflateStream(pushback, new Inflater(true)); } finally { inf.end(); } } #location 73 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Header createDigestHeader( final Credentials credentials, final HttpRequest request) throws AuthenticationException { String uri = getParameter("uri"); String realm = getParameter("realm"); String nonce = getParameter("nonce"); String opaque = getParameter("opaque"); String method = getParameter("methodname"); String algorithm = getParameter("algorithm"); Set<String> qopset = new HashSet<String>(8); int qop = QOP_UNKNOWN; String qoplist = getParameter("qop"); if (qoplist != null) { StringTokenizer tok = new StringTokenizer(qoplist, ","); while (tok.hasMoreTokens()) { String variant = tok.nextToken().trim(); qopset.add(variant.toLowerCase(Locale.US)); } if (request instanceof HttpEntityEnclosingRequest && qopset.contains("auth-int")) { qop = QOP_AUTH_INT; } else if (qopset.contains("auth")) { qop = QOP_AUTH; } } else { qop = QOP_MISSING; } if (qop == QOP_UNKNOWN) { throw new AuthenticationException("None of the qop methods is supported: " + qoplist); } // If an algorithm is not specified, default to MD5. if (algorithm == null) { algorithm = "MD5"; } String charset = getParameter("charset"); if (charset == null) { charset = "ISO-8859-1"; } String digAlg = algorithm; if (digAlg.equalsIgnoreCase("MD5-sess")) { digAlg = "MD5"; } MessageDigest digester; try { digester = createMessageDigest(digAlg); } catch (UnsupportedDigestAlgorithmException ex) { throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg); } String uname = credentials.getUserPrincipal().getName(); String pwd = credentials.getPassword(); if (nonce.equals(this.lastNonce)) { nounceCount++; } else { nounceCount = 1; cnonce = null; lastNonce = nonce; } StringBuilder sb = new StringBuilder(256); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%08x", nounceCount); formatter.close(); String nc = sb.toString(); if (cnonce == null) { cnonce = createCnonce(); } a1 = null; a2 = null; // 3.2.2.2: Calculating digest if (algorithm.equalsIgnoreCase("MD5-sess")) { // H( unq(username-value) ":" unq(realm-value) ":" passwd ) // ":" unq(nonce-value) // ":" unq(cnonce-value) // calculated one per session sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset))); sb.setLength(0); sb.append(checksum).append(':').append(nonce).append(':').append(cnonce); a1 = sb.toString(); } else { // unq(username-value) ":" unq(realm-value) ":" passwd sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); a1 = sb.toString(); } String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset))); if (qop == QOP_AUTH) { // Method ":" digest-uri-value a2 = method + ':' + uri; } else if (qop == QOP_AUTH_INT) { // Method ":" digest-uri-value ":" H(entity-body) HttpEntity entity = null; if (request instanceof HttpEntityEnclosingRequest) { entity = ((HttpEntityEnclosingRequest) request).getEntity(); } if (entity != null && !entity.isRepeatable()) { // If the entity is not repeatable, try falling back onto QOP_AUTH if (qopset.contains("auth")) { qop = QOP_AUTH; a2 = method + ':' + uri; } else { throw new AuthenticationException("Qop auth-int cannot be used with " + "a non-repeatable entity"); } } else { HttpEntityDigester entityDigester = new HttpEntityDigester(digester); try { if (entity != null) { entity.writeTo(entityDigester); } entityDigester.close(); } catch (IOException ex) { throw new AuthenticationException("I/O error reading entity content", ex); } a2 = method + ':' + uri + ':' + encode(entityDigester.getDigest()); } } else { a2 = method + ':' + uri; } String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset))); // 3.2.2.1 String digestValue; if (qop == QOP_MISSING) { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); digestValue = sb.toString(); } else { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':') .append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth") .append(':').append(hasha2); digestValue = sb.toString(); } String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue))); CharArrayBuffer buffer = new CharArrayBuffer(128); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Digest "); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20); params.add(new BasicNameValuePair("username", uname)); params.add(new BasicNameValuePair("realm", realm)); params.add(new BasicNameValuePair("nonce", nonce)); params.add(new BasicNameValuePair("uri", uri)); params.add(new BasicNameValuePair("response", digest)); if (qop != QOP_MISSING) { params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth")); params.add(new BasicNameValuePair("nc", nc)); params.add(new BasicNameValuePair("cnonce", cnonce)); } if (algorithm != null) { params.add(new BasicNameValuePair("algorithm", algorithm)); } if (opaque != null) { params.add(new BasicNameValuePair("opaque", opaque)); } for (int i = 0; i < params.size(); i++) { BasicNameValuePair param = params.get(i); if (i > 0) { buffer.append(", "); } boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName()); BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes); } return new BufferedHeader(buffer); }
#vulnerable code private Header createDigestHeader( final Credentials credentials, final HttpRequest request) throws AuthenticationException { String uri = getParameter("uri"); String realm = getParameter("realm"); String nonce = getParameter("nonce"); String opaque = getParameter("opaque"); String method = getParameter("methodname"); String algorithm = getParameter("algorithm"); Set<String> qopset = new HashSet<String>(8); int qop = QOP_UNKNOWN; String qoplist = getParameter("qop"); if (qoplist != null) { StringTokenizer tok = new StringTokenizer(qoplist, ","); while (tok.hasMoreTokens()) { String variant = tok.nextToken().trim(); qopset.add(variant.toLowerCase(Locale.US)); } if (request instanceof HttpEntityEnclosingRequest && qopset.contains("auth-int")) { qop = QOP_AUTH_INT; } else if (qopset.contains("auth")) { qop = QOP_AUTH; } } else { qop = QOP_MISSING; } if (qop == QOP_UNKNOWN) { throw new AuthenticationException("None of the qop methods is supported: " + qoplist); } // If an algorithm is not specified, default to MD5. if (algorithm == null) { algorithm = "MD5"; } String charset = getParameter("charset"); if (charset == null) { charset = "ISO-8859-1"; } String digAlg = algorithm; if (digAlg.equalsIgnoreCase("MD5-sess")) { digAlg = "MD5"; } MessageDigest digester; try { digester = createMessageDigest(digAlg); } catch (UnsupportedDigestAlgorithmException ex) { throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg); } String uname = credentials.getUserPrincipal().getName(); String pwd = credentials.getPassword(); if (nonce.equals(this.lastNonce)) { nounceCount++; } else { nounceCount = 1; cnonce = null; lastNonce = nonce; } StringBuilder sb = new StringBuilder(256); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%08x", nounceCount); String nc = sb.toString(); if (cnonce == null) { cnonce = createCnonce(); } a1 = null; a2 = null; // 3.2.2.2: Calculating digest if (algorithm.equalsIgnoreCase("MD5-sess")) { // H( unq(username-value) ":" unq(realm-value) ":" passwd ) // ":" unq(nonce-value) // ":" unq(cnonce-value) // calculated one per session sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset))); sb.setLength(0); sb.append(checksum).append(':').append(nonce).append(':').append(cnonce); a1 = sb.toString(); } else { // unq(username-value) ":" unq(realm-value) ":" passwd sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); a1 = sb.toString(); } String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset))); if (qop == QOP_AUTH) { // Method ":" digest-uri-value a2 = method + ':' + uri; } else if (qop == QOP_AUTH_INT) { // Method ":" digest-uri-value ":" H(entity-body) HttpEntity entity = null; if (request instanceof HttpEntityEnclosingRequest) { entity = ((HttpEntityEnclosingRequest) request).getEntity(); } if (entity != null && !entity.isRepeatable()) { // If the entity is not repeatable, try falling back onto QOP_AUTH if (qopset.contains("auth")) { qop = QOP_AUTH; a2 = method + ':' + uri; } else { throw new AuthenticationException("Qop auth-int cannot be used with " + "a non-repeatable entity"); } } else { HttpEntityDigester entityDigester = new HttpEntityDigester(digester); try { if (entity != null) { entity.writeTo(entityDigester); } entityDigester.close(); } catch (IOException ex) { throw new AuthenticationException("I/O error reading entity content", ex); } a2 = method + ':' + uri + ':' + encode(entityDigester.getDigest()); } } else { a2 = method + ':' + uri; } String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset))); // 3.2.2.1 String digestValue; if (qop == QOP_MISSING) { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); digestValue = sb.toString(); } else { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':') .append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth") .append(':').append(hasha2); digestValue = sb.toString(); } String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue))); CharArrayBuffer buffer = new CharArrayBuffer(128); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Digest "); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20); params.add(new BasicNameValuePair("username", uname)); params.add(new BasicNameValuePair("realm", realm)); params.add(new BasicNameValuePair("nonce", nonce)); params.add(new BasicNameValuePair("uri", uri)); params.add(new BasicNameValuePair("response", digest)); if (qop != QOP_MISSING) { params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth")); params.add(new BasicNameValuePair("nc", nc)); params.add(new BasicNameValuePair("cnonce", cnonce)); } if (algorithm != null) { params.add(new BasicNameValuePair("algorithm", algorithm)); } if (opaque != null) { params.add(new BasicNameValuePair("opaque", opaque)); } for (int i = 0; i < params.size(); i++) { BasicNameValuePair param = params.get(i); if (i > 0) { buffer.append(", "); } boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName()); BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes); } return new BufferedHeader(buffer); } #location 66 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAbortDuringConnecting() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(1); final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( connectLatch, WaitPolicy.BEFORE_CONNECT, PlainSocketFactory.getSocketFactory()); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", stallingSocketFactory) .build(); final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(registry); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>(); final Thread abortingThread = new Thread(new Runnable() { public void run() { try { stallingSocketFactory.waitForState(); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); connectLatch.countDown(); } catch (final Throwable e) { throwRef.set(e); } } }); abortingThread.start(); try { mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); Assert.fail("expected SocketException"); } catch(final SocketException expected) {} abortingThread.join(5000); if(throwRef.get() != null) { throw new RuntimeException(throwRef.get()); } Assert.assertFalse(conn.isOpen()); Assert.assertEquals(0, localServer.getAcceptedConnectionCount()); // the connection is expected to be released back to the manager final HttpClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn2.isOpen()); mgr.releaseConnection(conn2, null, -1, null); mgr.shutdown(); }
#vulnerable code @Test public void testAbortDuringConnecting() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(1); final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( connectLatch, WaitPolicy.BEFORE_CONNECT, PlainSocketFactory.getSocketFactory()); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", stallingSocketFactory) .build(); final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(registry); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final HttpContext context = new BasicHttpContext(); final HttpClientConnection conn = getConnection(mgr, route); final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>(); final Thread abortingThread = new Thread(new Runnable() { public void run() { try { stallingSocketFactory.waitForState(); conn.shutdown(); mgr.releaseConnection(conn, null, -1, null); connectLatch.countDown(); } catch (final Throwable e) { throwRef.set(e); } } }); abortingThread.start(); try { mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); Assert.fail("expected SocketException"); } catch(final SocketException expected) {} abortingThread.join(5000); if(throwRef.get() != null) { throw new RuntimeException(throwRef.get()); } Assert.assertFalse(conn.isOpen()); Assert.assertEquals(0, localServer.getAcceptedConnectionCount()); // the connection is expected to be released back to the manager final HttpClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn2.isOpen()); mgr.releaseConnection(conn2, null, -1, null); mgr.shutdown(); } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); }
#vulnerable code public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // default response context setResponseStatus(context, CacheResponseStatus.CACHE_MISS); String via = generateViaHeader(request); if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); return new OptionsHttp11Response(); } HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( request, context); if (fatalErrorResponse != null) return fatalErrorResponse; request = requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { return callBackend(target, request, context); } HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { return handleCacheMiss(target, request, context); } return handleCacheHit(target, request, context, entry); } #location 7 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code CachingHttpClient( HttpClient client, HttpCache cache, CacheConfig config) { super(); if (client == null) { throw new IllegalArgumentException("HttpClient may not be null"); } if (cache == null) { throw new IllegalArgumentException("HttpCache may not be null"); } if (config == null) { throw new IllegalArgumentException("CacheConfig may not be null"); } this.maxObjectSizeBytes = config.getMaxObjectSize(); this.sharedCache = config.isSharedCache(); this.backend = client; this.responseCache = cache; this.validityPolicy = new CacheValidityPolicy(); this.responseCachingPolicy = new ResponseCachingPolicy(maxObjectSizeBytes, sharedCache); this.responseGenerator = new CachedHttpResponseGenerator(this.validityPolicy); this.cacheableRequestPolicy = new CacheableRequestPolicy(); this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, config); this.conditionalRequestBuilder = new ConditionalRequestBuilder(); this.responseCompliance = new ResponseProtocolCompliance(); this.requestCompliance = new RequestProtocolCompliance(); this.asynchRevalidator = makeAsynchronousValidator(config); }
#vulnerable code HttpResponse callBackend(HttpHost target, HttpRequest request, HttpContext context) throws IOException { Date requestDate = getCurrentDate(); log.trace("Calling the backend"); HttpResponse backendResponse = backend.execute(target, request, context); backendResponse.addHeader("Via", generateViaHeader(backendResponse)); return handleBackendResponse(target, request, requestDate, getCurrentDate(), backendResponse); } #location 8 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void enableConnectionGC() throws IllegalStateException { if (refQueue != null) { throw new IllegalStateException("Connection GC already enabled."); } poolLock.lock(); try { if (numConnections > 0) { //@@@ is this check sufficient? throw new IllegalStateException("Pool already in use."); } } finally { poolLock.unlock(); } refQueue = new ReferenceQueue<Object>(); refWorker = new RefQueueWorker(refQueue, this); Thread t = new Thread(refWorker); //@@@ use a thread factory t.setDaemon(true); t.setName("RefQueueWorker@" + this); t.start(); }
#vulnerable code public void enableConnectionGC() throws IllegalStateException { if (refQueue != null) { throw new IllegalStateException("Connection GC already enabled."); } poolLock.lock(); try { if (numConnections > 0) { //@@@ is this check sufficient? throw new IllegalStateException("Pool already in use."); } } finally { poolLock.unlock(); } refQueue = new ReferenceQueue<Object>(); refWorker = new RefQueueWorker(refQueue, this); Thread t = new Thread(refWorker); //@@@ use a thread factory t.setDaemon(true); t.setName("RefQueueWorker@" + this); t.start(); connManager = new ConnMgrRef(connManager.get(), refQueue); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code ManagedClientConnection getConnection(final HttpRoute route, final Object state) { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } synchronized (this) { assertNotShutdown(); if (this.log.isDebugEnabled()) { this.log.debug("Get connection for route " + route); } if (this.conn != null) { throw new IllegalStateException(MISUSE_MESSAGE); } if (this.poolEntry != null && !this.poolEntry.getPlannedRoute().equals(route)) { this.poolEntry.close(); this.poolEntry = null; } if (this.poolEntry == null) { String id = Long.toString(COUNTER.getAndIncrement()); OperatedClientConnection conn = this.connOperator.createConnection(); this.poolEntry = new HttpPoolEntry(this.log, id, route, conn, 0, TimeUnit.MILLISECONDS); } long now = System.currentTimeMillis(); if (this.poolEntry.isExpired(now)) { this.poolEntry.close(); this.poolEntry.getTracker().reset(); } this.conn = new ManagedClientConnectionImpl(this, this.connOperator, this.poolEntry); return this.conn; } }
#vulnerable code ManagedClientConnection getConnection(final HttpRoute route, final Object state) { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } assertNotShutdown(); if (this.log.isDebugEnabled()) { this.log.debug("Get connection for route " + route); } synchronized (this) { if (this.conn != null) { throw new IllegalStateException(MISUSE_MESSAGE); } if (this.poolEntry != null && !this.poolEntry.getPlannedRoute().equals(route)) { this.poolEntry.close(); this.poolEntry = null; } if (this.poolEntry == null) { String id = Long.toString(COUNTER.getAndIncrement()); OperatedClientConnection conn = this.connOperator.createConnection(); this.poolEntry = new HttpPoolEntry(this.log, id, route, conn, 0, TimeUnit.MILLISECONDS); } long now = System.currentTimeMillis(); if (this.poolEntry.isExpired(now)) { this.poolEntry.close(); this.poolEntry.getTracker().reset(); } this.conn = new ManagedClientConnectionImpl(this, this.connOperator, this.poolEntry); return this.conn; } } #location 6 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReleaseConnection() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final int rsplen = 8; final String uri = "/random/" + rsplen; final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); final HttpContext context = new BasicHttpContext(); HttpClientConnection conn = getConnection(mgr, route); mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); final HttpProcessor httpProcessor = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() }); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); HttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); byte[] data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of first response entity", rsplen, data.length); // ignore data, but it must be read // check that there is no auto-release by default try { // this should fail quickly, connection has not been released getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException e) { // expected } conn.close(); mgr.releaseConnection(conn, null, -1, null); conn = getConnection(mgr, route); Assert.assertFalse("connection should have been closed", conn.isOpen()); mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); // repeat the communication, no need to prepare the request again context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in second response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of second response entity", rsplen, data.length); // ignore data, but it must be read // release connection after marking it for re-use // expect the next connection obtained to be open mgr.releaseConnection(conn, null, -1, null); conn = getConnection(mgr, route); Assert.assertTrue("connection should have been open", conn.isOpen()); // repeat the communication, no need to prepare the request again context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in third response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of third response entity", rsplen, data.length); // ignore data, but it must be read mgr.releaseConnection(conn, null, -1, null); mgr.shutdown(); }
#vulnerable code @Test public void testReleaseConnection() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final int rsplen = 8; final String uri = "/random/" + rsplen; final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); final HttpContext context = new BasicHttpContext(); HttpClientConnection conn = getConnection(mgr, route); mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); final HttpProcessor httpProcessor = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() }); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); HttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); byte[] data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of first response entity", rsplen, data.length); // ignore data, but it must be read // check that there is no auto-release by default try { // this should fail quickly, connection has not been released getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException e) { // expected } conn.close(); mgr.releaseConnection(conn, null, -1, null); conn = getConnection(mgr, route); Assert.assertFalse("connection should have been closed", conn.isOpen()); mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); // repeat the communication, no need to prepare the request again context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in second response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of second response entity", rsplen, data.length); // ignore data, but it must be read // release connection after marking it for re-use // expect the next connection obtained to be open mgr.releaseConnection(conn, null, -1, null); conn = getConnection(mgr, route); Assert.assertTrue("connection should have been open", conn.isOpen()); // repeat the communication, no need to prepare the request again context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in third response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of third response entity", rsplen, data.length); // ignore data, but it must be read mgr.releaseConnection(conn, null, -1, null); mgr.shutdown(); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expected = IllegalArgumentException.class) public void testDecorateCORSPropertiesValidRequestNullRequestType() { MockHttpServletRequest request = new MockHttpServletRequest(); CORSFilter.decorateCORSProperties(request, null); }
#vulnerable code @Test(expected = IllegalArgumentException.class) public void testDecorateCORSPropertiesValidRequestNullRequestType() { HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.replay(request); CORSFilter.decorateCORSProperties(request, null); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public InputStream createInputStream(final long offset) throws IOException { // permission check if (!isReadable()) { throw new IOException("No read permission : " + file.getName()); } // move to the appropriate offset and create input stream final RandomAccessFile raf = new RandomAccessFile(file, "r"); try { raf.seek(offset); // The IBM jre needs to have both the stream and the random access file // objects closed to actually close the file return new FileInputStream(raf.getFD()) { public void close() throws IOException { super.close(); raf.close(); } }; } catch (IOException e) { raf.close(); throw e; } }
#vulnerable code public InputStream createInputStream(final long offset) throws IOException { // permission check if (!isReadable()) { throw new IOException("No read permission : " + file.getName()); } // move to the appropriate offset and create input stream final RandomAccessFile raf = new RandomAccessFile(file, "r"); raf.seek(offset); // The IBM jre needs to have both the stream and the random access file // objects closed to actually close the file return new FileInputStream(raf.getFD()) { public void close() throws IOException { super.close(); raf.close(); } }; } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void handleMessage(Buffer buffer) throws Exception { synchronized (lock) { doHandleMessage(buffer); } }
#vulnerable code protected void handleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(); String msg = buffer.getString(); log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg); close(false); break; } case SSH_MSG_UNIMPLEMENTED: { int code = buffer.getInt(); log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code); break; } case SSH_MSG_DEBUG: { boolean display = buffer.getBoolean(); String msg = buffer.getString(); log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg); break; } case SSH_MSG_IGNORE: log.info("Received SSH_MSG_IGNORE"); break; default: switch (state) { case ReceiveKexInit: if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) { log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT); break; } log.info("Received SSH_MSG_KEXINIT"); receiveKexInit(buffer); negociate(); kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]); kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C); setState(State.Kex); break; case Kex: buffer.rpos(buffer.rpos() - 1); if (kex.next(buffer)) { checkHost(); sendNewKeys(); setState(State.ReceiveNewKeys); } break; case ReceiveNewKeys: if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd); return; } log.info("Received SSH_MSG_NEWKEYS"); receiveNewKeys(false); sendAuthRequest(); setState(State.AuthRequestSent); break; case AuthRequestSent: if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd); return; } setState(State.WaitForAuth); break; case WaitForAuth: // We're waiting for the client to send an authentication request // TODO: handle unexpected incoming packets break; case UserAuth: if (userAuth == null) { throw new IllegalStateException("State is userAuth, but no user auth pending!!!"); } buffer.rpos(buffer.rpos() - 1); switch (userAuth.next(buffer)) { case Success: authFuture.setAuthed(true); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } break; case Running: switch (cmd) { case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: channelOpenConfirmation(buffer); break; case SSH_MSG_CHANNEL_OPEN_FAILURE: channelOpenFailure(buffer); break; case SSH_MSG_CHANNEL_REQUEST: channelRequest(buffer); break; case SSH_MSG_CHANNEL_DATA: channelData(buffer); break; case SSH_MSG_CHANNEL_EXTENDED_DATA: channelExtendedData(buffer); break; case SSH_MSG_CHANNEL_FAILURE: channelFailure(buffer); break; case SSH_MSG_CHANNEL_WINDOW_ADJUST: channelWindowAdjust(buffer); break; case SSH_MSG_CHANNEL_EOF: channelEof(buffer); break; case SSH_MSG_CHANNEL_CLOSE: channelClose(buffer); break; // TODO: handle other requests } break; } } } #location 74 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void disconnect(int reason, String msg) throws IOException { Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_DISCONNECT); buffer.putInt(reason); buffer.putString(msg); buffer.putString(""); WriteFuture f = writePacket(buffer); f.addListener(new IoFutureListener() { public void operationComplete(IoFuture future) { close(); } }); }
#vulnerable code public void disconnect(int reason, String msg) throws IOException { Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_DISCONNECT); buffer.putInt(reason); buffer.putString(msg); buffer.putString(""); WriteFuture f = writePacket(buffer); f.join(); close(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void writeFile(String header, File path) throws IOException { if (log.isDebugEnabled()) { log.debug("Writing file {}", path); } if (!header.startsWith("C")) { throw new IOException("Expected a C message but got '" + header + "'"); } String perms = header.substring(1, 5); int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6))); String name = header.substring(header.indexOf(' ', 6) + 1); File file; if (path.exists() && path.isDirectory()) { file = new File(path, name); } else if (path.exists() && path.isFile()) { file = path; } else if (!path.exists() && path.getParentFile().exists() && path.getParentFile().isDirectory()) { file = path; } else { throw new IOException("Can not write to " + path); } OutputStream os = new FileOutputStream(file); try { ack(); byte[] buffer = new byte[8192]; while (length > 0) { int len = Math.min(length, buffer.length); len = in.read(buffer, 0, len); if (len <= 0) { throw new IOException("End of stream reached"); } os.write(buffer, 0, len); length -= len; } } finally { os.close(); } ack(); readAck(); }
#vulnerable code private void writeFile(String header, File path) throws IOException { if (log.isDebugEnabled()) { log.debug("Writing file {}", path); } if (!header.startsWith("C")) { throw new IOException("Expected a C message but got '" + header + "'"); } String perms = header.substring(1, 5); int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6))); String name = header.substring(header.indexOf(' ', 6) + 1); File file; if (path.exists() && path.isDirectory()) { file = new File(path, name); } else if (path.exists() && path.isFile()) { file = path; } else if (!path.exists() && path.getParentFile().exists() && path.getParentFile().isDirectory()) { file = path; } else { throw new IOException("Can not write to " + path); } OutputStream os = new FileOutputStream(file); ack(); byte[] buffer = new byte[8192]; while (length > 0) { int len = Math.min(length, buffer.length); len = in.read(buffer, 0, len); if (len <= 0) { throw new IOException("End of stream reached"); } os.write(buffer, 0, len); length -= len; } os.close(); ack(); readAck(); } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void exceptionCaught(Throwable t) { log.warn("Exception caught", t); try { if (t instanceof SshException) { int code = ((SshException) t).getDisconnectCode(); if (code > 0) { disconnect(code, t.getMessage()); return; } } } catch (Throwable t2) { // Ignore } close(); }
#vulnerable code public void exceptionCaught(Throwable t) { log.warn("Exception caught", t); try { if (t instanceof SshException) { int code = ((SshException) t).getDisconnectCode(); if (code > 0) { disconnect(code, t.getMessage()); } } } catch (Throwable t2) { // Ignore } close(); } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void handleMessage(Buffer buffer) throws Exception { synchronized (lock) { doHandleMessage(buffer); } }
#vulnerable code protected void handleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(); String msg = buffer.getString(); log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg); close(false); break; } case SSH_MSG_UNIMPLEMENTED: { int code = buffer.getInt(); log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code); break; } case SSH_MSG_DEBUG: { boolean display = buffer.getBoolean(); String msg = buffer.getString(); log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg); break; } case SSH_MSG_IGNORE: log.info("Received SSH_MSG_IGNORE"); break; default: switch (state) { case ReceiveKexInit: if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) { log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT); break; } log.info("Received SSH_MSG_KEXINIT"); receiveKexInit(buffer); negociate(); kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]); kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C); setState(State.Kex); break; case Kex: buffer.rpos(buffer.rpos() - 1); if (kex.next(buffer)) { checkHost(); sendNewKeys(); setState(State.ReceiveNewKeys); } break; case ReceiveNewKeys: if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd); return; } log.info("Received SSH_MSG_NEWKEYS"); receiveNewKeys(false); sendAuthRequest(); setState(State.AuthRequestSent); break; case AuthRequestSent: if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd); return; } setState(State.WaitForAuth); break; case WaitForAuth: // We're waiting for the client to send an authentication request // TODO: handle unexpected incoming packets break; case UserAuth: if (userAuth == null) { throw new IllegalStateException("State is userAuth, but no user auth pending!!!"); } buffer.rpos(buffer.rpos() - 1); switch (userAuth.next(buffer)) { case Success: authFuture.setAuthed(true); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } break; case Running: switch (cmd) { case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: channelOpenConfirmation(buffer); break; case SSH_MSG_CHANNEL_OPEN_FAILURE: channelOpenFailure(buffer); break; case SSH_MSG_CHANNEL_REQUEST: channelRequest(buffer); break; case SSH_MSG_CHANNEL_DATA: channelData(buffer); break; case SSH_MSG_CHANNEL_EXTENDED_DATA: channelExtendedData(buffer); break; case SSH_MSG_CHANNEL_FAILURE: channelFailure(buffer); break; case SSH_MSG_CHANNEL_WINDOW_ADJUST: channelWindowAdjust(buffer); break; case SSH_MSG_CHANNEL_EOF: channelEof(buffer); break; case SSH_MSG_CHANNEL_CLOSE: channelClose(buffer); break; // TODO: handle other requests } break; } } } #location 44 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleOpenFailure(Buffer buffer) { int reason = buffer.getInt(); String msg = buffer.getString(); this.openFailureReason = reason; this.openFailureMsg = msg; this.openFuture.setException(new SshException(msg)); this.closeFuture.setClosed(); this.doClose(); notifyStateChanged(); }
#vulnerable code public void handleOpenFailure(Buffer buffer) { int reason = buffer.getInt(); String msg = buffer.getString(); synchronized (lock) { this.openFailureReason = reason; this.openFailureMsg = msg; this.openFuture.setException(new SshException(msg)); this.closeFuture.setClosed(); this.doClose(); lock.notifyAll(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleOpenFailure(Buffer buffer) { int reason = buffer.getInt(); String msg = buffer.getString(); this.openFailureReason = reason; this.openFailureMsg = msg; this.openFuture.setException(new SshException(msg)); this.closeFuture.setClosed(); this.doClose(); notifyStateChanged(); }
#vulnerable code public void handleOpenFailure(Buffer buffer) { int reason = buffer.getInt(); String msg = buffer.getString(); synchronized (lock) { this.openFailureReason = reason; this.openFailureMsg = msg; this.openFuture.setException(new SshException(msg)); this.closeFuture.setClosed(); this.doClose(); lock.notifyAll(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean handleShell(Buffer buffer) throws IOException { boolean wantReply = buffer.getBoolean(); if (((ServerSession) session).getServerFactoryManager().getShellFactory() == null) { return false; } addEnvVariable("USER", ((ServerSession) session).getUsername()); shell = ((ServerSession) session).getServerFactoryManager().getShellFactory().createShell(); out = new ChannelOutputStream(this, remoteWindow, log, SshConstants.Message.SSH_MSG_CHANNEL_DATA); err = new ChannelOutputStream(this, remoteWindow, log, SshConstants.Message.SSH_MSG_CHANNEL_EXTENDED_DATA); // Wrap in logging filters out = new LoggingFilterOutputStream(out, "OUT:", log); err = new LoggingFilterOutputStream(err, "ERR:", log); if (getPtyModeValue(PtyMode.ONLCR) != 0) { out = new LfToCrLfFilterOutputStream(out); err = new LfToCrLfFilterOutputStream(err); } in = new ChannelPipedInputStream(localWindow); shellIn = new ChannelPipedOutputStream((ChannelPipedInputStream) in); shell.setInputStream(in); shell.setOutputStream(out); shell.setErrorStream(err); shell.setExitCallback(new ShellFactory.ExitCallback() { public void onExit(int exitValue) { try { closeShell(exitValue); } catch (IOException e) { log.info("Error closing shell", e); } } }); if (wantReply) { buffer = session.createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_SUCCESS); buffer.putInt(recipient); session.writePacket(buffer); } shell.start(getEnvironment()); shellIn = new LoggingFilterOutputStream(shellIn, "IN: ", log); return true; }
#vulnerable code protected boolean handleShell(Buffer buffer) throws IOException { boolean wantReply = buffer.getBoolean(); if (((ServerSession) session).getServerFactoryManager().getShellFactory() == null) { return false; } addEnvVariable("USER", ((ServerSession) session).getUsername()); shell = ((ServerSession) session).getServerFactoryManager().getShellFactory().createShell(); out = new ChannelOutputStream(this, remoteWindow, log, SshConstants.Message.SSH_MSG_CHANNEL_DATA); err = new ChannelOutputStream(this, remoteWindow, log, SshConstants.Message.SSH_MSG_CHANNEL_EXTENDED_DATA); // Wrap in logging filters out = new LoggingFilterOutputStream(out, "OUT:", log); err = new LoggingFilterOutputStream(err, "ERR:", log); if (getPtyModeValue(PtyMode.ONLCR) != 0) { out = new LfToCrLfFilterOutputStream(out); err = new LfToCrLfFilterOutputStream(err); } in = new ChannelPipedInputStream(localWindow); shellIn = new ChannelPipedOutputStream((ChannelPipedInputStream) in); shell.setInputStream(in); shell.setOutputStream(out); shell.setErrorStream(err); shell.setExitCallback(new ShellFactory.ExitCallback() { public void onExit(int exitValue) { try { closeShell(exitValue); } catch (IOException e) { log.info("Error closing shell", e); } } }); if (wantReply) { buffer = session.createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_SUCCESS); buffer.putInt(recipient); session.writePacket(buffer); } shell.start(env); shellIn = new LoggingFilterOutputStream(shellIn, "IN: ", log); return true; } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void handleMessage(Buffer buffer) throws Exception { synchronized (lock) { doHandleMessage(buffer); } }
#vulnerable code protected void handleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(); String msg = buffer.getString(); log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg); close(false); break; } case SSH_MSG_UNIMPLEMENTED: { int code = buffer.getInt(); log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code); break; } case SSH_MSG_DEBUG: { boolean display = buffer.getBoolean(); String msg = buffer.getString(); log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg); break; } case SSH_MSG_IGNORE: log.info("Received SSH_MSG_IGNORE"); break; default: switch (state) { case ReceiveKexInit: if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) { log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT); break; } log.info("Received SSH_MSG_KEXINIT"); receiveKexInit(buffer); negociate(); kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]); kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C); setState(State.Kex); break; case Kex: buffer.rpos(buffer.rpos() - 1); if (kex.next(buffer)) { checkHost(); sendNewKeys(); setState(State.ReceiveNewKeys); } break; case ReceiveNewKeys: if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd); return; } log.info("Received SSH_MSG_NEWKEYS"); receiveNewKeys(false); sendAuthRequest(); setState(State.AuthRequestSent); break; case AuthRequestSent: if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd); return; } setState(State.WaitForAuth); break; case WaitForAuth: // We're waiting for the client to send an authentication request // TODO: handle unexpected incoming packets break; case UserAuth: if (userAuth == null) { throw new IllegalStateException("State is userAuth, but no user auth pending!!!"); } buffer.rpos(buffer.rpos() - 1); switch (userAuth.next(buffer)) { case Success: authFuture.setAuthed(true); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } break; case Running: switch (cmd) { case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: channelOpenConfirmation(buffer); break; case SSH_MSG_CHANNEL_OPEN_FAILURE: channelOpenFailure(buffer); break; case SSH_MSG_CHANNEL_REQUEST: channelRequest(buffer); break; case SSH_MSG_CHANNEL_DATA: channelData(buffer); break; case SSH_MSG_CHANNEL_EXTENDED_DATA: channelExtendedData(buffer); break; case SSH_MSG_CHANNEL_FAILURE: channelFailure(buffer); break; case SSH_MSG_CHANNEL_WINDOW_ADJUST: channelWindowAdjust(buffer); break; case SSH_MSG_CHANNEL_EOF: channelEof(buffer); break; case SSH_MSG_CHANNEL_CLOSE: channelClose(buffer); break; // TODO: handle other requests } break; } } } #location 37 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setupSensibleDefaultPty() { try { if (OsUtils.isUNIX()) { ptyModes = SttySupport.getUnixPtyModes(); ptyColumns = SttySupport.getTerminalWidth(); ptyLines = SttySupport.getTerminalHeight(); } else { ptyType = "windows"; } } catch (Throwable t) { // Ignore exceptions } }
#vulnerable code public void setupSensibleDefaultPty() { try { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("windows") < 0) { ptyModes = SttySupport.getUnixPtyModes(); ptyColumns = SttySupport.getTerminalWidth(); ptyLines = SttySupport.getTerminalHeight(); } else { ptyType = "windows"; } } catch (Throwable t) { // Ignore exceptions } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleRequest(Buffer buffer) throws IOException { log.info("Received SSH_MSG_CHANNEL_REQUEST on channel {}", id); String req = buffer.getString(); if ("exit-status".equals(req)) { buffer.getBoolean(); exitStatus = buffer.getInt(); notifyStateChanged(); } else if ("exit-signal".equals(req)) { buffer.getBoolean(); exitSignal = buffer.getString(); notifyStateChanged(); } // TODO: handle other channel requests }
#vulnerable code public void handleRequest(Buffer buffer) throws IOException { log.info("Received SSH_MSG_CHANNEL_REQUEST on channel {}", id); String req = buffer.getString(); if ("exit-status".equals(req)) { buffer.getBoolean(); synchronized (lock) { exitStatus = buffer.getInt(); lock.notifyAll(); } } else if ("exit-signal".equals(req)) { buffer.getBoolean(); synchronized (lock) { exitSignal = buffer.getString(); lock.notifyAll(); } } // TODO: handle other channel requests } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void handleMessage(Buffer buffer) throws Exception { synchronized (lock) { doHandleMessage(buffer); } }
#vulnerable code protected void handleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(); String msg = buffer.getString(); log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg); close(false); break; } case SSH_MSG_UNIMPLEMENTED: { int code = buffer.getInt(); log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code); break; } case SSH_MSG_DEBUG: { boolean display = buffer.getBoolean(); String msg = buffer.getString(); log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg); break; } case SSH_MSG_IGNORE: log.info("Received SSH_MSG_IGNORE"); break; default: switch (state) { case ReceiveKexInit: if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) { log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT); break; } log.info("Received SSH_MSG_KEXINIT"); receiveKexInit(buffer); negociate(); kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]); kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C); setState(State.Kex); break; case Kex: buffer.rpos(buffer.rpos() - 1); if (kex.next(buffer)) { checkHost(); sendNewKeys(); setState(State.ReceiveNewKeys); } break; case ReceiveNewKeys: if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd); return; } log.info("Received SSH_MSG_NEWKEYS"); receiveNewKeys(false); sendAuthRequest(); setState(State.AuthRequestSent); break; case AuthRequestSent: if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd); return; } setState(State.WaitForAuth); break; case WaitForAuth: // We're waiting for the client to send an authentication request // TODO: handle unexpected incoming packets break; case UserAuth: if (userAuth == null) { throw new IllegalStateException("State is userAuth, but no user auth pending!!!"); } buffer.rpos(buffer.rpos() - 1); switch (userAuth.next(buffer)) { case Success: authFuture.setAuthed(true); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } break; case Running: switch (cmd) { case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: channelOpenConfirmation(buffer); break; case SSH_MSG_CHANNEL_OPEN_FAILURE: channelOpenFailure(buffer); break; case SSH_MSG_CHANNEL_REQUEST: channelRequest(buffer); break; case SSH_MSG_CHANNEL_DATA: channelData(buffer); break; case SSH_MSG_CHANNEL_EXTENDED_DATA: channelExtendedData(buffer); break; case SSH_MSG_CHANNEL_FAILURE: channelFailure(buffer); break; case SSH_MSG_CHANNEL_WINDOW_ADJUST: channelWindowAdjust(buffer); break; case SSH_MSG_CHANNEL_EOF: channelEof(buffer); break; case SSH_MSG_CHANNEL_CLOSE: channelClose(buffer); break; // TODO: handle other requests } break; } } } #location 81 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.