instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
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 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 @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 @Test public void testReleaseConnectionWithTimeLimits() 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, 100, TimeUnit.MILLISECONDS); conn = getConnection(mgr, route); Assert.assertFalse("connection should have been closed", conn.isOpen()); // repeat the communication, no need to prepare the request again mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); 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 mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS); 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, 100, TimeUnit.MILLISECONDS); Thread.sleep(150); conn = getConnection(mgr, route); Assert.assertTrue("connection should have been closed", !conn.isOpen()); // repeat the communication, no need to prepare the request again mgr.connect(conn, route, 0, context); mgr.routeComplete(conn, route, context); 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 fourth response entity", rsplen, data.length); // ignore data, but it must be read mgr.shutdown(); }
#vulnerable code @Test public void testReleaseConnectionWithTimeLimits() 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, 100, TimeUnit.MILLISECONDS); conn = getConnection(mgr, route); Assert.assertFalse("connection should have been closed", conn.isOpen()); // repeat the communication, no need to prepare the request again mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); 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 mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS); 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, 100, TimeUnit.MILLISECONDS); Thread.sleep(150); conn = getConnection(mgr, route); Assert.assertTrue("connection should have been closed", !conn.isOpen()); // repeat the communication, no need to prepare the request again mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context); 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 fourth response entity", rsplen, data.length); // ignore data, but it must be read mgr.shutdown(); } #location 16 #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 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 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 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(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 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 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 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.
#fixed code public int getSize() { synchronized (lock) { return size; } }
#vulnerable code public int getSize() { return 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 init(int size, int packetSize) { synchronized (lock) { this.size = size; this.maxSize = size; this.packetSize = packetSize; lock.notifyAll(); } }
#vulnerable code public void init(int size, int packetSize) { this.size = size; this.maxSize = size; this.packetSize = packetSize; } #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 setAttributes(Map<Attribute, Object> attributes) throws IOException { if (!attributes.isEmpty()) { throw new UnsupportedOperationException(); } }
#vulnerable code public void setAttributes(Map<Attribute, Object> attributes) throws IOException { for (Attribute attribute : attributes.keySet()) { String name = null; Object value = attributes.get(attribute); switch (attribute) { case Uid: name = "unix:uid"; break; case Owner: name = "unix:owner"; value = toUser((String) value); break; case Gid: name = "unix:gid"; break; case Group: name = "unix:group"; value = toGroup((String) value); break; case CreationTime: name = "unix:creationTime"; value = FileTime.fromMillis((Long) value); break; case LastModifiedTime: name = "unix:lastModifiedTime"; value = FileTime.fromMillis((Long) value); break; case LastAccessTime: name = "unix:lastAccessTime"; value = FileTime.fromMillis((Long) value); break; case Permissions: name = "unix:permissions"; value = toPerms((EnumSet<Permission>) value); break; } if (name != null && value != null) { Files.setAttribute(file.toPath(), name, value, LinkOption.NOFOLLOW_LINKS); } } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setAttributes(Map<Attribute, Object> attributes) throws IOException { if (!attributes.isEmpty()) { throw new UnsupportedOperationException(); } }
#vulnerable code public void setAttributes(Map<Attribute, Object> attributes) throws IOException { for (Attribute attribute : attributes.keySet()) { String name = null; Object value = attributes.get(attribute); switch (attribute) { case Uid: name = "unix:uid"; break; case Owner: name = "unix:owner"; value = toUser((String) value); break; case Gid: name = "unix:gid"; break; case Group: name = "unix:group"; value = toGroup((String) value); break; case CreationTime: name = "unix:creationTime"; value = FileTime.fromMillis((Long) value); break; case LastModifiedTime: name = "unix:lastModifiedTime"; value = FileTime.fromMillis((Long) value); break; case LastAccessTime: name = "unix:lastAccessTime"; value = FileTime.fromMillis((Long) value); break; case Permissions: name = "unix:permissions"; value = toPerms((EnumSet<Permission>) value); break; } if (name != null && value != null) { Files.setAttribute(file.toPath(), name, value, LinkOption.NOFOLLOW_LINKS); } } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void doHandleMessage(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 (getState()) { 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; } authFuture.setAuthed(false); 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!!!"); } if (cmd == SshConstants.Message.SSH_MSG_USERAUTH_BANNER) { String welcome = buffer.getString(); String lang = buffer.getString(); log.debug("Welcome banner: " + welcome); UserInteraction ui = getClientFactoryManager().getUserInteraction(); if (ui != null) { ui.welcome(welcome); } } else { buffer.rpos(buffer.rpos() - 1); processUserAuth(buffer); } break; case Running: switch (cmd) { case SSH_MSG_REQUEST_SUCCESS: requestSuccess(buffer); break; case SSH_MSG_REQUEST_FAILURE: requestFailure(buffer); break; case SSH_MSG_CHANNEL_OPEN: channelOpen(buffer); break; 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; default: throw new IllegalStateException("Unsupported command: " + cmd); } break; default: throw new IllegalStateException("Unsupported state: " + getState()); } } }
#vulnerable code protected void doHandleMessage(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 (getState()) { 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!!!"); } if (cmd == SshConstants.Message.SSH_MSG_USERAUTH_BANNER) { String welcome = buffer.getString(); String lang = buffer.getString(); log.debug("Welcome banner: " + welcome); UserInteraction ui = getClientFactoryManager().getUserInteraction(); if (ui != null) { ui.welcome(welcome); } } else { buffer.rpos(buffer.rpos() - 1); switch (userAuth.next(buffer)) { case Success: authFuture.setAuthed(true); username = userAuth.getUsername(); authed = true; setState(State.Running); startHeartBeat(); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } } break; case Running: switch (cmd) { case SSH_MSG_REQUEST_SUCCESS: requestSuccess(buffer); break; case SSH_MSG_REQUEST_FAILURE: requestFailure(buffer); break; case SSH_MSG_CHANNEL_OPEN: channelOpen(buffer); break; 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; default: throw new IllegalStateException("Unsupported command: " + cmd); } break; default: throw new IllegalStateException("Unsupported state: " + getState()); } } } #location 93 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void truncate() throws IOException{ RandomAccessFile tempFile = new RandomAccessFile(file, "rw"); tempFile.setLength(0); tempFile.close(); }
#vulnerable code public void truncate() throws IOException{ new RandomAccessFile(file, "rw").setLength(0); } #location 2 #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 Exception { int port = 8000; boolean error = false; for (int i = 0; i < args.length; i++) { if ("-p".equals(args[i])) { if (i + 1 >= args.length) { System.err.println("option requires an argument: " + args[i]); break; } port = Integer.parseInt(args[++i]); } else if (args[i].startsWith("-")) { System.err.println("illegal option: " + args[i]); error = true; break; } else { System.err.println("extra argument: " + args[i]); error = true; break; } } if (error) { System.err.println("usage: sshd [-p port]"); System.exit(-1); } System.err.println("Starting SSHD on port " + port); SshServer sshd = SshServer.setUpDefaultServer(); sshd.setPort(port); if (SecurityUtils.isBouncyCastleRegistered()) { sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider("key.pem")); } else { sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("key.ser")); } if (OsUtils.isUNIX()) { sshd.setShellFactory(new ProcessShellFactory(new String[] { "/bin/sh", "-i", "-l" }, EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr))); } else { sshd.setShellFactory(new ProcessShellFactory(new String[] { "cmd.exe "}, EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr))); } sshd.setPasswordAuthenticator(new PasswordAuthenticator() { public boolean authenticate(String username, String password, ServerSession session) { return username != null && username.equals(password); } }); sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() { public boolean authenticate(String username, PublicKey key, ServerSession session) { //File f = new File("/Users/" + username + "/.ssh/authorized_keys"); return true; } }); sshd.setForwardingFilter(new ForwardingFilter() { public boolean canForwardAgent(ServerSession session) { return true; } public boolean canForwardX11(ServerSession session) { return true; } public boolean canListen(InetSocketAddress address, ServerSession session) { return true; } public boolean canConnect(InetSocketAddress address, ServerSession session) { return true; } }); sshd.start(); }
#vulnerable code public static void main(String[] args) throws Exception { int port = 8000; boolean error = false; for (int i = 0; i < args.length; i++) { if ("-p".equals(args[i])) { if (i + 1 >= args.length) { System.err.println("option requires an argument: " + args[i]); break; } port = Integer.parseInt(args[++i]); } else if (args[i].startsWith("-")) { System.err.println("illegal option: " + args[i]); error = true; break; } else { System.err.println("extra argument: " + args[i]); error = true; break; } } if (error) { System.err.println("usage: sshd [-p port]"); System.exit(-1); } System.err.println("Starting SSHD on port " + port); SshServer sshd = SshServer.setUpDefaultServer(); sshd.setPort(port); if (SecurityUtils.isBouncyCastleRegistered()) { sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider("key.pem")); } else { sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("key.ser")); } if (System.getProperty("os.name").toLowerCase().indexOf("windows") < 0) { sshd.setShellFactory(new ProcessShellFactory(new String[] { "/bin/sh", "-i", "-l" }, EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr))); } else { sshd.setShellFactory(new ProcessShellFactory(new String[] { "cmd.exe "}, EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr))); } sshd.setPasswordAuthenticator(new PasswordAuthenticator() { public boolean authenticate(String username, String password, ServerSession session) { return username != null && username.equals(password); } }); sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() { public boolean authenticate(String username, PublicKey key, ServerSession session) { //File f = new File("/Users/" + username + "/.ssh/authorized_keys"); return true; } }); sshd.setForwardingFilter(new ForwardingFilter() { public boolean canForwardAgent(ServerSession session) { return true; } public boolean canForwardX11(ServerSession session) { return true; } public boolean canListen(InetSocketAddress address, ServerSession session) { return true; } public boolean canConnect(InetSocketAddress address, ServerSession session) { return true; } }); sshd.start(); } #location 36 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void check(int maxFree) throws IOException { synchronized (lock) { if ((size < maxFree) && (maxFree - size > packetSize * 3 || size < maxFree / 2)) { if (log.isDebugEnabled()) { log.debug("Increase " + name + " by " + (maxFree - size) + " up to " + maxFree); } channel.sendWindowAdjust(maxFree - size); size = maxFree; } } }
#vulnerable code public void check(int maxFree) throws IOException { int threshold = Math.min(packetSize * 8, maxSize / 4); synchronized (lock) { if ((maxFree - size) > packetSize && (maxFree - size > threshold || size < threshold)) { if (log.isDebugEnabled()) { log.debug("Increase " + name + " by " + (maxFree - size) + " up to " + maxFree); } channel.sendWindowAdjust(maxFree - size); size = maxFree; } } } #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 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 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void doHandleMessage(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 (getState()) { 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; } authFuture.setAuthed(false); 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!!!"); } if (cmd == SshConstants.Message.SSH_MSG_USERAUTH_BANNER) { String welcome = buffer.getString(); String lang = buffer.getString(); log.debug("Welcome banner: " + welcome); UserInteraction ui = getClientFactoryManager().getUserInteraction(); if (ui != null) { ui.welcome(welcome); } } else { buffer.rpos(buffer.rpos() - 1); processUserAuth(buffer); } break; case Running: switch (cmd) { case SSH_MSG_REQUEST_SUCCESS: requestSuccess(buffer); break; case SSH_MSG_REQUEST_FAILURE: requestFailure(buffer); break; case SSH_MSG_CHANNEL_OPEN: channelOpen(buffer); break; 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; default: throw new IllegalStateException("Unsupported command: " + cmd); } break; default: throw new IllegalStateException("Unsupported state: " + getState()); } } }
#vulnerable code protected void doHandleMessage(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 (getState()) { 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!!!"); } if (cmd == SshConstants.Message.SSH_MSG_USERAUTH_BANNER) { String welcome = buffer.getString(); String lang = buffer.getString(); log.debug("Welcome banner: " + welcome); UserInteraction ui = getClientFactoryManager().getUserInteraction(); if (ui != null) { ui.welcome(welcome); } } else { buffer.rpos(buffer.rpos() - 1); switch (userAuth.next(buffer)) { case Success: authFuture.setAuthed(true); username = userAuth.getUsername(); authed = true; setState(State.Running); startHeartBeat(); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } } break; case Running: switch (cmd) { case SSH_MSG_REQUEST_SUCCESS: requestSuccess(buffer); break; case SSH_MSG_REQUEST_FAILURE: requestFailure(buffer); break; case SSH_MSG_CHANNEL_OPEN: channelOpen(buffer); break; 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; default: throw new IllegalStateException("Unsupported command: " + cmd); } break; default: throw new IllegalStateException("Unsupported state: " + getState()); } } } #location 87 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleClose() throws IOException { log.debug("Received SSH_MSG_CHANNEL_CLOSE on channel {}", id); closedByOtherSide = !closing.get(); if (closedByOtherSide) { close(false); } else { close(false).setClosed(); notifyStateChanged(); } }
#vulnerable code public void handleClose() throws IOException { log.debug("Received SSH_MSG_CHANNEL_CLOSE on channel {}", id); synchronized (lock) { closedByOtherSide = !closing; if (closedByOtherSide) { close(false); } else { close(false).setClosed(); 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 public static void readBySax(File file, int sheetIndex, RowHandler rowHandler) { if (ExcelFileUtil.isXlsx(file)) { read07BySax(file, sheetIndex, rowHandler); } else { read03BySax(file, sheetIndex, rowHandler); } }
#vulnerable code public static void readBySax(File file, int sheetIndex, RowHandler rowHandler) { BufferedInputStream in = null; try { in = FileUtil.getInputStream(file); readBySax(in, sheetIndex, rowHandler); } finally { IoUtil.close(in); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void rythmEngineTest() { // 字符串模板 TemplateEngine engine = TemplateUtil.createEngine( new TemplateConfig("templates").setCustomEngine(RythmEngine.class)); Template template = engine.getTemplate("hello,@name"); String result = template.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result); // classpath中获取模板 Template template2 = engine.getTemplate("rythm_test.tmpl"); String result2 = template2.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result2); }
#vulnerable code @Test public void rythmEngineTest() { // 字符串模板 TemplateEngine engine = new RythmEngine(new TemplateConfig("templates")); Template template = engine.getTemplate("hello,@name"); String result = template.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result); // classpath中获取模板 Template template2 = engine.getTemplate("rythm_test.tmpl"); String result2 = template2.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result2); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public byte[] encrypt(byte[] data, KeyType keyType) throws CryptoException { if (KeyType.PublicKey != keyType) { throw new IllegalArgumentException("Encrypt is only support by public key"); } checkKey(keyType); lock.lock(); final SM2Engine engine = getEngine(); try { engine.init(true, new ParametersWithRandom(getCipherParameters(keyType))); return engine.processBlock(data, 0, data.length); } finally { lock.unlock(); } }
#vulnerable code @Override public byte[] encrypt(byte[] data, KeyType keyType) throws CryptoException { if (KeyType.PublicKey != keyType) { throw new IllegalArgumentException("Encrypt is only support by public key"); } ckeckKey(keyType); lock.lock(); final SM2Engine engine = getEngine(); try { engine.init(true, new ParametersWithRandom(getCipherParameters(keyType))); return engine.processBlock(data, 0, data.length); } finally { lock.unlock(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void toJsonStrTest2() { Map<String, Object> model = new HashMap<>(); model.put("mobile", "17610836523"); model.put("type", 1); Map<String, Object> data = new HashMap<>(); data.put("model", model); data.put("model2", model); JSONObject jsonObject = JSONUtil.parseObj(data); Assert.assertTrue(jsonObject.containsKey("model")); Assert.assertEquals(1, jsonObject.getJSONObject("model").getInt("type").intValue()); Assert.assertEquals("17610836523", jsonObject.getJSONObject("model").getStr("mobile")); // Assert.assertEquals("{\"model\":{\"type\":1,\"mobile\":\"17610836523\"}}", jsonObject.toString()); }
#vulnerable code @Test public void toJsonStrTest2() { Map<String, Object> model = new HashMap<String, Object>(); model.put("mobile", "17610836523"); model.put("type", 1); Map<String, Object> data = new HashMap<String, Object>(); data.put("model", model); data.put("model2", model); JSONObject jsonObject = JSONUtil.parseObj(data); Assert.assertTrue(jsonObject.containsKey("model")); Assert.assertEquals(1, jsonObject.getJSONObject("model").getInt("type").intValue()); Assert.assertEquals("17610836523", jsonObject.getJSONObject("model").getStr("mobile")); // Assert.assertEquals("{\"model\":{\"type\":1,\"mobile\":\"17610836523\"}}", jsonObject.toString()); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public byte[] decrypt(byte[] data, KeyType keyType) throws CryptoException { if (KeyType.PrivateKey != keyType) { throw new IllegalArgumentException("Decrypt is only support by private key"); } checkKey(keyType); lock.lock(); final SM2Engine engine = getEngine(); try { engine.init(false, getCipherParameters(keyType)); return engine.processBlock(data, 0, data.length); } finally { lock.unlock(); } }
#vulnerable code @Override public byte[] decrypt(byte[] data, KeyType keyType) throws CryptoException { if (KeyType.PrivateKey != keyType) { throw new IllegalArgumentException("Decrypt is only support by private key"); } ckeckKey(keyType); lock.lock(); final SM2Engine engine = getEngine(); try { engine.init(false, getCipherParameters(keyType)); return engine.processBlock(data, 0, data.length); } finally { lock.unlock(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public byte[] encrypt(byte[] data, KeyType keyType) { final Key key = getKeyByType(keyType); lock.lock(); try { cipher.init(Cipher.ENCRYPT_MODE, key); if(this.encryptBlockSize < 0){ // 在引入BC库情况下,自动获取块大小 final int blockSize = this.cipher.getBlockSize(); if(blockSize > 0){ this.encryptBlockSize = blockSize; } } return doFinal(data, this.encryptBlockSize < 0 ? data.length : this.encryptBlockSize); } catch (Exception e) { throw new CryptoException(e); } finally { lock.unlock(); } }
#vulnerable code @Override public byte[] encrypt(byte[] data, KeyType keyType) { final Key key = getKeyByType(keyType); final int maxBlockSize = this.encryptBlockSize < 0 ? data.length : this.encryptBlockSize; lock.lock(); try { cipher.init(Cipher.ENCRYPT_MODE, key); return doFinal(data, maxBlockSize); } catch (Exception e) { throw new CryptoException(e); } finally { lock.unlock(); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ClassLoader compile() { // 获得classPath final List<File> classPath = getClassPath(); final URL[] urLs = URLUtil.getURLs(classPath.toArray(new File[0])); final URLClassLoader ucl = URLClassLoader.newInstance(urLs, this.parentClassLoader); if (sourceCodeMap.isEmpty() && sourceFileList.isEmpty()) { // 没有需要编译的源码 return ucl; } // 没有需要编译的源码文件返回加载zip或jar包的类加载器 // 创建编译器 final JavaFileManager javaFileManager = new JavaClassFileManager(ucl, CompilerUtil.getFileManager()); // classpath final List<String> options = new ArrayList<>(); if (false == classPath.isEmpty()) { final List<String> cp = classPath.stream().map(File::getAbsolutePath).collect(Collectors.toList()); options.add("-cp"); options.addAll(cp); } // 编译文件 final DiagnosticCollector<? super JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); final List<JavaFileObject> javaFileObjectList = getJavaFileObject(); final CompilationTask task = CompilerUtil.getTask(javaFileManager, diagnosticCollector, options, javaFileObjectList); try{ if (task.call()) { // 加载编译后的类 return javaFileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); } } finally { IoUtil.close(javaFileManager); } //编译失败,收集错误信息 throw new CompilerException(DiagnosticUtil.getMessages(diagnosticCollector)); }
#vulnerable code public ClassLoader compile() { // 获得classPath final List<File> classPath = getClassPath(); final URL[] urLs = URLUtil.getURLs(classPath.toArray(new File[0])); final URLClassLoader ucl = URLClassLoader.newInstance(urLs, this.parentClassLoader); if (sourceCodeMap.isEmpty() && sourceFileList.isEmpty()) { // 没有需要编译的源码 return ucl; } // 没有需要编译的源码文件返回加载zip或jar包的类加载器 // 创建编译器 final JavaFileManager javaFileManager = new JavaClassFileManager(ucl, CompilerUtil.getFileManager()); // classpath final List<String> options = new ArrayList<>(); if (false == classPath.isEmpty()) { final List<String> cp = classPath.stream().map(File::getAbsolutePath).collect(Collectors.toList()); options.add("-cp"); options.addAll(cp); } // 编译文件 final DiagnosticCollector<? super JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); final List<JavaFileObject> javaFileObjectList = getJavaFileObject(); final CompilationTask task = CompilerUtil.getTask(javaFileManager, diagnosticCollector, options, javaFileObjectList); if (task.call()) { // 加载编译后的类 return javaFileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); } else { // 编译失败,收集错误信息 throw new CompilerException(DiagnosticUtil.getMessages(diagnosticCollector)); } } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static DataSize parse(CharSequence text, DataUnit defaultUnit) { Assert.notNull(text, "Text must not be null"); try { final Matcher matcher = PATTERN.matcher(text); Assert.state(matcher.matches(), "Does not match data size pattern"); final DataUnit unit = determineDataUnit(matcher.group(3), defaultUnit); return DataSize.of(new BigDecimal(matcher.group(1)), unit); } catch (Exception ex) { throw new IllegalArgumentException("'" + text + "' is not a valid data size", ex); } }
#vulnerable code public static DataSize parse(CharSequence text, DataUnit defaultUnit) { Assert.notNull(text, "Text must not be null"); try { Matcher matcher = PATTERN.matcher(text); Assert.state(matcher.matches(), "Does not match data size pattern"); DataUnit unit = determineDataUnit(matcher.group(3), defaultUnit); String value = matcher.group(1); if (value.indexOf(".") > -1) { return DataSize.of(new BigDecimal(value), unit); } else { long amount = Long.parseLong(matcher.group(1)); return DataSize.of(amount, unit); } } catch (Exception ex) { throw new IllegalArgumentException("'" + text + "' is not a valid data size", ex); } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void enjoyEngineTest() { // 字符串模板 TemplateEngine engine = TemplateUtil.createEngine( new TemplateConfig("templates").setCustomEngine(EnjoyEngine.class)); Template template = engine.getTemplate("#(x + 123)"); String result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); //ClassPath模板 engine = new EnjoyEngine( new TemplateConfig("templates", ResourceMode.CLASSPATH).setCustomEngine(EnjoyEngine.class)); template = engine.getTemplate("enjoy_test.etl"); result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); }
#vulnerable code @Test public void enjoyEngineTest() { // 字符串模板 TemplateEngine engine = new EnjoyEngine(new TemplateConfig("templates")); Template template = engine.getTemplate("#(x + 123)"); String result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); //ClassPath模板 engine = new EnjoyEngine(new TemplateConfig("templates", ResourceMode.CLASSPATH)); template = engine.getTemplate("enjoy_test.etl"); result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void copyPropertiesBeanToMapTest() { // 测试BeanToMap SubPerson p1 = new SubPerson(); p1.setSlow(true); p1.setName("测试"); p1.setSubName("sub测试"); Map<String, Object> map = MapUtil.newHashMap(); BeanUtil.copyProperties(p1, map); Assert.assertTrue((Boolean) map.get("slow")); Assert.assertEquals("测试", map.get("name")); Assert.assertEquals("sub测试", map.get("subName")); }
#vulnerable code @Test public void copyPropertiesBeanToMapTest() { // 测试BeanToMap SubPerson p1 = new SubPerson(); p1.setSlow(true); p1.setName("测试"); p1.setSubName("sub测试"); Map<String, Object> map = MapUtil.newHashMap(); BeanUtil.copyProperties(p1, map); Assert.assertTrue((Boolean) map.get("isSlow")); Assert.assertEquals("测试", map.get("name")); Assert.assertEquals("sub测试", map.get("subName")); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] readBytes(InputStream in, boolean isCloseStream) throws IORuntimeException { final InputStream availableStream = toAvailableStream(in); try{ final int available = availableStream.available(); if(available > 0){ byte[] result = new byte[available]; //noinspection ResultOfMethodCallIgnored availableStream.read(result); return result; } } catch (IOException e){ throw new IORuntimeException(e); } return new byte[0]; }
#vulnerable code public static byte[] readBytes(InputStream in, boolean isCloseStream) throws IORuntimeException { final FastByteArrayOutputStream out = new FastByteArrayOutputStream(); copy(in, out); if (isCloseStream) { close(in); } return out.toByteArray(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void enjoyEngineTest() { // 字符串模板 TemplateEngine engine = TemplateUtil.createEngine( new TemplateConfig("templates").setCustomEngine(EnjoyEngine.class)); Template template = engine.getTemplate("#(x + 123)"); String result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); //ClassPath模板 engine = new EnjoyEngine( new TemplateConfig("templates", ResourceMode.CLASSPATH).setCustomEngine(EnjoyEngine.class)); template = engine.getTemplate("enjoy_test.etl"); result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); }
#vulnerable code @Test public void enjoyEngineTest() { // 字符串模板 TemplateEngine engine = new EnjoyEngine(new TemplateConfig("templates")); Template template = engine.getTemplate("#(x + 123)"); String result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); //ClassPath模板 engine = new EnjoyEngine(new TemplateConfig("templates", ResourceMode.CLASSPATH)); template = engine.getTemplate("enjoy_test.etl"); result = template.render(Dict.create().set("x", 1)); Assert.assertEquals("124", result); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static PemObject readPemObject(InputStream keyStream) { return readPemObject(IoUtil.getUtf8Reader(keyStream)); }
#vulnerable code public static PemObject readPemObject(InputStream keyStream) { PemReader pemReader = null; try { pemReader = new PemReader(IoUtil.getReader(keyStream, CharsetUtil.CHARSET_UTF_8)); return pemReader.readPemObject(); } catch (IOException e) { throw new IORuntimeException(e); } finally { IoUtil.close(pemReader); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void copyPropertiesHasBooleanTest() { SubPerson p1 = new SubPerson(); p1.setSlow(true); // 测试boolean参数值isXXX形式 SubPerson p2 = new SubPerson(); BeanUtil.copyProperties(p1, p2); Assert.assertTrue(p2.getSlow()); // 测试boolean参数值非isXXX形式 SubPerson2 p3 = new SubPerson2(); BeanUtil.copyProperties(p1, p3); Assert.assertTrue(p3.getSlow()); }
#vulnerable code @Test public void copyPropertiesHasBooleanTest() { SubPerson p1 = new SubPerson(); p1.setSlow(true); // 测试boolean参数值isXXX形式 SubPerson p2 = new SubPerson(); BeanUtil.copyProperties(p1, p2); Assert.assertTrue(p2.isSlow()); // 测试boolean参数值非isXXX形式 SubPerson2 p3 = new SubPerson2(); BeanUtil.copyProperties(p1, p3); Assert.assertTrue(p3.isSlow()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void freemarkerEngineTest() { // 字符串模板 TemplateEngine engine = TemplateUtil.createEngine( new TemplateConfig("templates", ResourceMode.STRING).setCustomEngine(FreemarkerEngine.class)); Template template = engine.getTemplate("hello,${name}"); String result = template.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result); //ClassPath模板 engine = TemplateUtil.createEngine( new TemplateConfig("templates", ResourceMode.CLASSPATH).setCustomEngine(FreemarkerEngine.class)); template = engine.getTemplate("freemarker_test.ftl"); result = template.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result); }
#vulnerable code @Test public void freemarkerEngineTest() { // 字符串模板 TemplateEngine engine = new FreemarkerEngine(new TemplateConfig("templates", ResourceMode.STRING)); Template template = engine.getTemplate("hello,${name}"); String result = template.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result); //ClassPath模板 engine = new FreemarkerEngine(new TemplateConfig("templates", ResourceMode.CLASSPATH)); template = engine.getTemplate("freemarker_test.ftl"); result = template.render(Dict.create().set("name", "hutool")); Assert.assertEquals("hello,hutool", result); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void thymeleafEngineTest() { // 字符串模板 TemplateEngine engine = TemplateUtil.createEngine( new TemplateConfig("templates").setCustomEngine(ThymeleafEngine.class)); Template template = engine.getTemplate("<h3 th:text=\"${message}\"></h3>"); String result = template.render(Dict.create().set("message", "Hutool")); Assert.assertEquals("<h3>Hutool</h3>", result); //ClassPath模板 engine = TemplateUtil.createEngine( new TemplateConfig("templates", ResourceMode.CLASSPATH).setCustomEngine(ThymeleafEngine.class)); template = engine.getTemplate("thymeleaf_test.ttl"); result = template.render(Dict.create().set("message", "Hutool")); Assert.assertEquals("<h3>Hutool</h3>", result); }
#vulnerable code @Test public void thymeleafEngineTest() { // 字符串模板 TemplateEngine engine = new ThymeleafEngine(new TemplateConfig("templates")); Template template = engine.getTemplate("<h3 th:text=\"${message}\"></h3>"); String result = template.render(Dict.create().set("message", "Hutool")); Assert.assertEquals("<h3>Hutool</h3>", result); //ClassPath模板 engine = new ThymeleafEngine(new TemplateConfig("templates", ResourceMode.CLASSPATH)); template = engine.getTemplate("thymeleaf_test.ttl"); result = template.render(Dict.create().set("message", "Hutool")); Assert.assertEquals("<h3>Hutool</h3>", result); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public CellStyle getOrCreateCellStyle(int x, int y) { final CellStyle cellStyle = getOrCreateCell(x, y).getCellStyle(); return StyleUtil.isNullOrDefaultStyle(this.workbook, cellStyle) ? createCellStyle(x, y) : cellStyle; }
#vulnerable code public CellStyle getOrCreateCellStyle(int x, int y) { final Cell cell = getOrCreateCell(x, y); CellStyle cellStyle = cell.getCellStyle(); if (null == cellStyle) { cellStyle = this.workbook.createCellStyle(); cell.setCellStyle(cellStyle); } return cellStyle; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes mapperScanAttrs = AnnotationAttributes .fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName())); if (mapperScanAttrs != null) { registerBeanDefinitions(mapperScanAttrs, registry); } }
#vulnerable code @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName())); ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); // this check is needed in Spring 3.1 if (resourceLoader != null) { scanner.setResourceLoader(resourceLoader); } Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass"); if (!Annotation.class.equals(annotationClass)) { scanner.setAnnotationClass(annotationClass); } Class<?> markerInterface = annoAttrs.getClass("markerInterface"); if (!Class.class.equals(markerInterface)) { scanner.setMarkerInterface(markerInterface); } Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator"); if (!BeanNameGenerator.class.equals(generatorClass)) { scanner.setBeanNameGenerator(BeanUtils.instantiateClass(generatorClass)); } Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean"); if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) { scanner.setMapperFactoryBean(BeanUtils.instantiateClass(mapperFactoryBeanClass)); } scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef")); scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef")); List<String> basePackages = new ArrayList<>(); basePackages.addAll( Arrays.stream(annoAttrs.getStringArray("value")) .filter(StringUtils::hasText) .collect(Collectors.toList())); basePackages.addAll( Arrays.stream(annoAttrs.getStringArray("basePackages")) .filter(StringUtils::hasText) .collect(Collectors.toList())); basePackages.addAll( Arrays.stream(annoAttrs.getClassArray("basePackageClasses")) .map(ClassUtils::getPackageName) .collect(Collectors.toList())); scanner.registerFilters(); scanner.doScan(StringUtils.toStringArray(basePackages)); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code DccManager(PircBotX bot) { _bot = bot; }
#vulnerable code boolean processRequest(String nick, String login, String hostname, String request) { StringTokenizer tokenizer = new StringTokenizer(request); tokenizer.nextToken(); String type = tokenizer.nextToken(); String filename = tokenizer.nextToken(); if (type.equals("SEND")) { long address = Long.parseLong(tokenizer.nextToken()); int port = Integer.parseInt(tokenizer.nextToken()); long size = -1; try { size = Long.parseLong(tokenizer.nextToken()); } catch (Exception e) { // Stick with the old value. } DccFileTransfer transfer = new DccFileTransfer(_bot, this, nick, login, hostname, type, filename, address, port, size); _bot.onIncomingFileTransfer(transfer); } else if (type.equals("RESUME")) { int port = Integer.parseInt(tokenizer.nextToken()); long progress = Long.parseLong(tokenizer.nextToken()); DccFileTransfer transfer = null; synchronized (_awaitingResume) { for (int i = 0; i < _awaitingResume.size(); i++) { transfer = (DccFileTransfer) _awaitingResume.elementAt(i); if (transfer.getNick().equals(nick) && transfer.getPort() == port) { _awaitingResume.removeElementAt(i); break; } } } if (transfer != null) { transfer.setProgress(progress); _bot.sendCTCPCommand(nick, "DCC ACCEPT file.ext " + port + " " + progress); } } else if (type.equals("ACCEPT")) { int port = Integer.parseInt(tokenizer.nextToken()); long progress = Long.parseLong(tokenizer.nextToken()); DccFileTransfer transfer = null; synchronized (_awaitingResume) { for (int i = 0; i < _awaitingResume.size(); i++) { transfer = (DccFileTransfer) _awaitingResume.elementAt(i); if (transfer.getNick().equals(nick) && transfer.getPort() == port) { _awaitingResume.removeElementAt(i); break; } } } if (transfer != null) transfer.doReceive(transfer.getFile(), true); } else if (type.equals("CHAT")) { long address = Long.parseLong(tokenizer.nextToken()); int port = Integer.parseInt(tokenizer.nextToken()); final DccChat chat = new DccChat(_bot, nick, login, hostname, address, port); new Thread() { public void run() { _bot.onIncomingChatRequest(chat); } }.start(); } else return false; return true; } #location 36 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void handleLine(String line) throws Throwable { try { log(line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. onServerPing(line.substring(5)); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. onUnknown(line); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request onVersion(sourceNick, sourceLogin, sourceHostname, target); else if (request.startsWith("ACTION ")) // ACTION request onAction(sourceNick, sourceLogin, sourceHostname, target, request.substring(7)); else if (request.startsWith("PING ")) // PING request onPing(sourceNick, sourceLogin, sourceHostname, target, request.substring(5)); else if (request.equals("TIME")) // TIME request onTime(sourceNick, sourceLogin, sourceHostname, target); else if (request.equals("FINGER")) // FINGER request onFinger(sourceNick, sourceLogin, sourceHostname, target); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(sourceNick, sourceLogin, sourceHostname, request); if (!success) // The DccManager didn't know what to do with the line. onUnknown(line); } else // An unknown CTCP message - ignore it. onUnknown(line); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. onMessage(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("PRIVMSG")) // This is a private message to us. onPrivateMessage(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("JOIN")) { // Someone is joining a channel. String channel = target; Channel chan = getChannel(channel); if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup sendRawLine("WHO " + channel); sendRawLine("MODE " + channel); } User usr = getUser(sourceNick); //Only setup if nessesary if (usr.getHostmask() == null) { usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); } chan.addUser(usr); onJoin(channel, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("PART")) { // Someone is parting from a channel. if (sourceNick.equals(getNick())) removeChannel(target); else //Just remove the user from memory getChannel(target).removeUser(sourceNick); onPart(target, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; renameUser(sourceNick, newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); onNickChange(sourceNick, sourceLogin, sourceHostname, newNick); } else if (command.equals("NOTICE")) // Someone is sending a notice. onNotice(sourceNick, sourceLogin, sourceHostname, target, line.substring(line.indexOf(" :") + 2)); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) removeAllChannels(); else removeUser(sourceNick); onQuit(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); if (recipient.equals(getNick())) removeChannel(target); removeUser(recipient); onKick(target, sourceNick, sourceLogin, sourceHostname, recipient, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); Channel chan = getChannel(target); chan.setTopic(topic); chan.setTopicSetter(sourceNick); chan.setTopicTimestamp(currentTime); onTopic(target, topic, sourceNick, currentTime, true); } else if (command.equals("INVITE")) // Somebody is inviting somebody else into a channel. onInvite(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. onUnknown(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); synchronized (this) { log("### Your implementation of PircBotXis faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotXto continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); for (String curLine : sw.toString().split("\r\n")) log("### " + curLine); } } }
#vulnerable code protected void handleLine(String line) throws Throwable { try { log(line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. onServerPing(line.substring(5)); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. onUnknown(line); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request onVersion(sourceNick, sourceLogin, sourceHostname, target); else if (request.startsWith("ACTION ")) // ACTION request onAction(sourceNick, sourceLogin, sourceHostname, target, request.substring(7)); else if (request.startsWith("PING ")) // PING request onPing(sourceNick, sourceLogin, sourceHostname, target, request.substring(5)); else if (request.equals("TIME")) // TIME request onTime(sourceNick, sourceLogin, sourceHostname, target); else if (request.equals("FINGER")) // FINGER request onFinger(sourceNick, sourceLogin, sourceHostname, target); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(sourceNick, sourceLogin, sourceHostname, request); if (!success) // The DccManager didn't know what to do with the line. onUnknown(line); } else // An unknown CTCP message - ignore it. onUnknown(line); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. onMessage(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("PRIVMSG")) // This is a private message to us. onPrivateMessage(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("JOIN")) { // Someone is joining a channel. String channel = target; if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup _channels.put(channel, new Channel(channel)); sendRawLine("WHO " + channel); sendRawLine("MODE " + channel); } User usr = _channels.get(channel).getUser(sourceNick); usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); onJoin(channel, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("PART")) { // Someone is parting from a channel. removeUser(target, sourceNick); if (sourceNick.equals(getNick())) removeChannel(target); onPart(target, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; renameUser(sourceNick, newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); onNickChange(sourceNick, sourceLogin, sourceHostname, newNick); } else if (command.equals("NOTICE")) // Someone is sending a notice. onNotice(sourceNick, sourceLogin, sourceHostname, target, line.substring(line.indexOf(" :") + 2)); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) removeAllChannels(); else removeUser(sourceNick); onQuit(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); if (recipient.equals(getNick())) removeChannel(target); removeUser(target, recipient); onKick(target, sourceNick, sourceLogin, sourceHostname, recipient, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) // Someone is changing the topic. onTopic(target, line.substring(line.indexOf(" :") + 2), sourceNick, System.currentTimeMillis(), true); else if (command.equals("INVITE")) // Somebody is inviting somebody else into a channel. onInvite(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. onUnknown(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); synchronized (this) { log("### Your implementation of PircBotXis faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotXto continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); for (String curLine : sw.toString().split("\r\n")) log("### " + curLine); } } } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void processServerResponseTest() { String aString = "I'm some super long string that has multiple words"; //Simulate /LIST response bot.processServerResponse(321, "Channel :Users Name"); bot.processServerResponse(322, "PircBotXUser #PircBotXChannel 99 :" + aString); bot.processServerResponse(322, "PircBotXUser #PircBotXChannel1 100 :" + aString + aString); bot.processServerResponse(322, "PircBotXUser #PircBotXChannel2 101 :" + aString + aString + aString); bot.processServerResponse(323, ":End of /LIST"); Set<ChannelListEntry> channels = ((ChannelInfo.Event) signal.event).getList(); assertEquals(channels.size(), 3); boolean channelParsed = false; for (ChannelListEntry entry : channels) if (entry.getName().equals("#PircBotXChannel1")) { assertEquals(entry.getName(), "#PircBotXChannel1"); assertEquals(entry.getTopic(), aString + aString); assertEquals(entry.getUsers(), 100); channelParsed = true; } assertEquals(channelParsed, true, "Channel #PircBotXChannel1 not found in /LIST results!"); //From a /TOPIC or /JOIN Channel aChannel = bot.getChannel("#aChannel"); bot.processServerResponse(332, "PircBotXUser #aChannel :" + aString + aString); assertEquals(aChannel.getTopic(), aString + aString); bot.processServerResponse(333, "PircBotXUser #aChannel ISetTopic 1564842512"); assertEquals(aChannel.getTopicSetter(), "ISetTopic"); assertEquals(aChannel.getTopicTimestamp(), (long) 1564842512 * 1000); }
#vulnerable code @Test public void processServerResponseTest() { PircBotXVisible bot = new PircBotXVisible() { }; final Signal signal = new Signal(); bot.getListeners().addListener(new MetaListener() { @Override public void onChannelInfo(Event event) { signal.event = event; } @Override public void onMotd(Motd.Event event) { signal.event = event; } @Override public void onTopic(Topic.Event event) { signal.event = event; } @Override public void onUserList(UserList.Event event) { signal.event = event; } }); String aString = "I'm some super long string that has multiple words"; //Simulate /LIST response bot.processServerResponse(321, "Channel :Users Name"); bot.processServerResponse(322, "PircBotXUser #PircBotXChannel 99 :" + aString); bot.processServerResponse(322, "PircBotXUser #PircBotXChannel1 100 :" + aString + aString); bot.processServerResponse(322, "PircBotXUser #PircBotXChannel2 101 :" + aString + aString + aString); bot.processServerResponse(323, ":End of /LIST"); Set<ChannelListEntry> channels = ((ChannelInfo.Event) signal.event).getList(); assertEquals(channels.size(), 3); boolean channelParsed = false; for (ChannelListEntry entry : channels) if (entry.getName().equals("#PircBotXChannel1")) { assertEquals(entry.getName(), "#PircBotXChannel1"); assertEquals(entry.getTopic(), aString + aString); assertEquals(entry.getUsers(), 100); channelParsed = true; } assertEquals(channelParsed, true, "Channel #PircBotXChannel1 not found in /LIST results!"); //From a /TOPIC or /JOIN Channel aChannel = bot.getChannel("#aChannel"); bot.processServerResponse(332, "PircBotXUser #aChannel :" + aString + aString); assertEquals(aChannel.getTopic(), aString + aString); bot.processServerResponse(333, "PircBotXUser #aChannel ISetTopic 1564842512"); assertEquals(aChannel.getTopicSetter(), "ISetTopic"); assertEquals(aChannel.getTopicTimestamp(), (long)1564842512*1000); } #location 36 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void handleLine(String line) throws Throwable { try { log(line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. onServerPing(line.substring(5)); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. onUnknown(line); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request onVersion(sourceNick, sourceLogin, sourceHostname, target); else if (request.startsWith("ACTION ")) // ACTION request onAction(sourceNick, sourceLogin, sourceHostname, target, request.substring(7)); else if (request.startsWith("PING ")) // PING request onPing(sourceNick, sourceLogin, sourceHostname, target, request.substring(5)); else if (request.equals("TIME")) // TIME request onTime(sourceNick, sourceLogin, sourceHostname, target); else if (request.equals("FINGER")) // FINGER request onFinger(sourceNick, sourceLogin, sourceHostname, target); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(sourceNick, sourceLogin, sourceHostname, request); if (!success) // The DccManager didn't know what to do with the line. onUnknown(line); } else // An unknown CTCP message - ignore it. onUnknown(line); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. onMessage(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("PRIVMSG")) // This is a private message to us. onPrivateMessage(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("JOIN")) { // Someone is joining a channel. String channel = target; Channel chan = getChannel(channel); if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup sendRawLine("WHO " + channel); sendRawLine("MODE " + channel); } User usr = getUser(sourceNick); //Only setup if nessesary if (usr.getHostmask() == null) { usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); } chan.addUser(usr); onJoin(channel, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("PART")) { // Someone is parting from a channel. if (sourceNick.equals(getNick())) removeChannel(target); else //Just remove the user from memory getChannel(target).removeUser(sourceNick); onPart(target, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; renameUser(sourceNick, newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); onNickChange(sourceNick, sourceLogin, sourceHostname, newNick); } else if (command.equals("NOTICE")) // Someone is sending a notice. onNotice(sourceNick, sourceLogin, sourceHostname, target, line.substring(line.indexOf(" :") + 2)); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) removeAllChannels(); else removeUser(sourceNick); onQuit(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); if (recipient.equals(getNick())) removeChannel(target); removeUser(recipient); onKick(target, sourceNick, sourceLogin, sourceHostname, recipient, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); Channel chan = getChannel(target); chan.setTopic(topic); chan.setTopicSetter(sourceNick); chan.setTopicTimestamp(currentTime); onTopic(target, topic, sourceNick, currentTime, true); } else if (command.equals("INVITE")) // Somebody is inviting somebody else into a channel. onInvite(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. onUnknown(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); synchronized (this) { log("### Your implementation of PircBotXis faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotXto continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); for (String curLine : sw.toString().split("\r\n")) log("### " + curLine); } } }
#vulnerable code protected void handleLine(String line) throws Throwable { try { log(line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. onServerPing(line.substring(5)); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. onUnknown(line); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request onVersion(sourceNick, sourceLogin, sourceHostname, target); else if (request.startsWith("ACTION ")) // ACTION request onAction(sourceNick, sourceLogin, sourceHostname, target, request.substring(7)); else if (request.startsWith("PING ")) // PING request onPing(sourceNick, sourceLogin, sourceHostname, target, request.substring(5)); else if (request.equals("TIME")) // TIME request onTime(sourceNick, sourceLogin, sourceHostname, target); else if (request.equals("FINGER")) // FINGER request onFinger(sourceNick, sourceLogin, sourceHostname, target); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(sourceNick, sourceLogin, sourceHostname, request); if (!success) // The DccManager didn't know what to do with the line. onUnknown(line); } else // An unknown CTCP message - ignore it. onUnknown(line); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. onMessage(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("PRIVMSG")) // This is a private message to us. onPrivateMessage(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("JOIN")) { // Someone is joining a channel. String channel = target; if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup _channels.put(channel, new Channel(channel)); sendRawLine("WHO " + channel); sendRawLine("MODE " + channel); } User usr = _channels.get(channel).getUser(sourceNick); usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); onJoin(channel, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("PART")) { // Someone is parting from a channel. removeUser(target, sourceNick); if (sourceNick.equals(getNick())) removeChannel(target); onPart(target, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; renameUser(sourceNick, newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); onNickChange(sourceNick, sourceLogin, sourceHostname, newNick); } else if (command.equals("NOTICE")) // Someone is sending a notice. onNotice(sourceNick, sourceLogin, sourceHostname, target, line.substring(line.indexOf(" :") + 2)); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) removeAllChannels(); else removeUser(sourceNick); onQuit(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); if (recipient.equals(getNick())) removeChannel(target); removeUser(target, recipient); onKick(target, sourceNick, sourceLogin, sourceHostname, recipient, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) // Someone is changing the topic. onTopic(target, line.substring(line.indexOf(" :") + 2), sourceNick, System.currentTimeMillis(), true); else if (command.equals("INVITE")) // Somebody is inviting somebody else into a channel. onInvite(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. onUnknown(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); synchronized (this) { log("### Your implementation of PircBotXis faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotXto continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); for (String curLine : sw.toString().split("\r\n")) log("### " + curLine); } } } #location 149 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void logGuildLeave(GuildMemberRemoveEvent event) { TextChannel tc = vortex.getDatabase().settings.getSettings(event.getGuild()).getServerLogChannel(event.getGuild()); if(tc==null) return; OffsetDateTime now = OffsetDateTime.now(); String msg = FormatUtil.formatFullUser(event.getUser())+" left or was kicked from the server."; Member member = event.getMember(); if(member != null) { long seconds = member.getTimeJoined().until(now, ChronoUnit.SECONDS); StringBuilder rlist; if(member.getRoles().isEmpty()) rlist = new StringBuilder(); else { rlist= new StringBuilder("\nRoles: `"+member.getRoles().get(0).getName()); for(int i=1; i<member.getRoles().size(); i++) rlist.append("`, `").append(member.getRoles().get(i).getName()); rlist.append("`"); } msg += "\nJoined: " + member.getTimeJoined().format(DateTimeFormatter.RFC_1123_DATE_TIME) + " (" + FormatUtil.secondsToTimeCompact(seconds) + " ago)" + rlist.toString(); } log(now, tc, LEAVE, msg, null); }
#vulnerable code public void logGuildLeave(GuildMemberRemoveEvent event) { TextChannel tc = vortex.getDatabase().settings.getSettings(event.getGuild()).getServerLogChannel(event.getGuild()); if(tc==null) return; OffsetDateTime now = OffsetDateTime.now(); long seconds = event.getMember().getTimeJoined().until(now, ChronoUnit.SECONDS); StringBuilder rlist; if(event.getMember().getRoles().isEmpty()) rlist = new StringBuilder(); else { rlist= new StringBuilder("\nRoles: `"+event.getMember().getRoles().get(0).getName()); for(int i=1; i<event.getMember().getRoles().size(); i++) rlist.append("`, `").append(event.getMember().getRoles().get(i).getName()); rlist.append("`"); } log(now, tc, LEAVE, FormatUtil.formatFullUser(event.getUser())+" left or was kicked from the server. " +"\nJoined: "+event.getMember().getTimeJoined().format(DateTimeFormatter.RFC_1123_DATE_TIME)+" ("+FormatUtil.secondsToTimeCompact(seconds)+" ago)" +rlist.toString(), null); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { // Get the transform names from the suffix final List<NamedImageTransformer> selectedNamedImageTransformers = getNamedImageTransformers(request); // Collect and combine the image transformers and their params final ValueMap imageTransformersWithParams = getImageTransformersWithParams(selectedNamedImageTransformers); final Image image = this.resolveImage(request); final String mimeType = this.getMimeType(request, image); Layer layer = this.getLayer(image); if (layer == null) { response.setStatus(SlingHttpServletResponse.SC_NOT_FOUND); return; } // Transform the image layer = this.transform(layer, imageTransformersWithParams); // Get the quality final double quality = this.getQuality(mimeType, imageTransformersWithParams.get(TYPE_QUALITY, EMPTY_PARAMS)); response.setContentType(mimeType); layer.write(mimeType, quality, response.getOutputStream()); response.flushBuffer(); }
#vulnerable code @Override protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { // Get the transform names from the suffix final List<NamedImageTransformer> selectedNamedImageTransformers = getNamedImageTransformers(request); // Collect and combine the image transformers and their params final ValueMap imageTransformersWithParams = getImageTransformersWithParams(selectedNamedImageTransformers); final Image image = this.resolveImage(request); final String mimeType = this.getMimeType(request, image); Layer layer = this.getLayer(image); // Transform the image layer = this.transform(layer, imageTransformersWithParams); // Get the quality final double quality = this.getQuality(mimeType, imageTransformersWithParams.get(TYPE_QUALITY, EMPTY_PARAMS)); response.setContentType(mimeType); layer.write(mimeType, quality, response.getOutputStream()); response.flushBuffer(); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final void addThumbnail(final JcrPackage jcrPackage, Resource thumbnailResource) { ResourceResolver resourceResolver = null; if (jcrPackage == null) { log.error("JCR Package is null; no package thumbnail needed for null packages!"); return; } boolean useDefault = thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE); try { if (useDefault) { log.debug("Using default ACS AEM Commons packager package icon."); resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null); thumbnailResource = resourceResolver.getResource(DEFAULT_PACKAGE_THUMBNAIL_RESOURCE_PATH); } if (thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE)) { log.warn("Cannot find a specific OR a default package icon; no package icon will be used."); } else { final Node srcNode = thumbnailResource.adaptTo(Node.class); final Node dstParentNode = jcrPackage.getDefinition().getNode(); JcrUtil.copy(srcNode, dstParentNode, NN_THUMBNAIL); dstParentNode.getSession().save(); } } catch (RepositoryException e) { log.error("Could not add package thumbnail: {}", e.getMessage()); } catch (LoginException e) { log.error("Could not add a default package thumbnail: {}", e.getMessage()); } finally { if (resourceResolver != null) { resourceResolver.close(); } } }
#vulnerable code public final void addThumbnail(final JcrPackage jcrPackage, Resource thumbnailResource) { ResourceResolver resourceResolver = null; if (jcrPackage == null) { log.error("JCR Package is null; no package thumbnail needed for null packages!"); return; } boolean useDefault = thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE); try { if (useDefault) { log.debug("Using default ACS AEM Commons packager package icon."); resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null); thumbnailResource = resourceResolver.getResource(DEFAULT_PACKAGE_THUMBNAIL_RESOURCE_PATH); if (thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE)) { log.warn("Cannot find a specific OR a default package icon; no package icon will be used."); } } final Node srcNode = thumbnailResource.adaptTo(Node.class); final Node dstParentNode = jcrPackage.getDefinition().getNode(); JcrUtil.copy(srcNode, dstParentNode, NN_THUMBNAIL); dstParentNode.getSession().save(); } catch (RepositoryException e) { log.error("Could not add package thumbnail: {}", e.getMessage()); } catch (LoginException e) { log.error("Could not add a default package thumbnail: {}", e.getMessage()); } finally { if (resourceResolver != null) { resourceResolver.close(); } } } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public final void clearCache() { this.cache.clear(); }
#vulnerable code @Override public final void clearCache() { synchronized (this.cache) { this.cache.clear(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected int resize(int newSize) { if (newSize != timestamps.length) { LOG.debug("Resizing throttling queue from {} to {}", timestamps.length, newSize); Instant[] newQueue = new Instant[newSize]; int result = 0; if (timestamps.length - newSize > 0) { // queue got smaller result = reduceSize(newQueue); } else { // queue got larger, just resize the timestamps array and ignore the purge till // next cycle result = increaseSize(newQueue); } timestamps = newQueue; return result; } else { // Do not resize LOG.debug("No resizing required"); } return 0; }
#vulnerable code protected int resize(int newSize) { if (newSize != timestamps.length) { LOG.debug("Resizing throttling queue from {} to {}", timestamps.length, newSize); Instant[] newQueue = new Instant[newSize]; int result = 0; if (timestamps.length - newSize > 0) { // queue got smaller result = reduceSize(newQueue); } else { // queue got larger, just resize the timestamps array and ignore the purge till // next cycle result = increaseSize(newQueue); } timestamps = newQueue; return result; } else { // Do not resize LOG.debug("No resizing required"); } return 0; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected String getRawFormData(final String formName, final SlingHttpServletRequest request, final SlingHttpServletResponse response) { final String cookieName = getGetLookupKey(formName); final Cookie cookie = CookieUtil.getCookie(request, cookieName); String data = ""; if (response != null && cookie != null) { CookieUtil.dropCookies(request, response, ROOT_COOKIE_PATH, cookieName); // Get the QP lookup for this form data = this.decode(cookie.getValue()); } else { log.warn("SlingHttpServletResponse required for removing cookie. Please use formHelper.getForm({}, slingRequest, slingResponse);", formName); } return data; }
#vulnerable code @Override protected String getRawFormData(final String formName, final SlingHttpServletRequest request, final SlingHttpServletResponse response) { final String cookieName = getGetLookupKey(formName); final Cookie cookie = CookieUtil.getCookie(request, cookieName); if (response != null && cookie != null) { CookieUtil.dropCookies(request, response, ROOT_COOKIE_PATH, cookieName); } else { log.warn("SlingHttpServletResponse required for removing cookie. Please use formHelper.getForm({}, slingRequest, slingResponse);", formName); } // Get the QP lookup for this form return this.decode(cookie.getValue()); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object getValue(Object adaptable, String name, Type declaredType, AnnotatedElement element, DisposalCallbackRegistry callbackRegistry) { // sanity check if (!(adaptable instanceof Resource || adaptable instanceof SlingHttpServletRequest)) { return null; } ObjectType nameEnum = ObjectType.fromString(name); if (nameEnum == null) { return null; } switch (nameEnum) { case RESOURCE: return getResource(adaptable); case RESOURCE_RESOLVER: return getResourceResolver(adaptable); case COMPONENT_CONTEXT: return getComponentContext(adaptable); case PAGE_MANAGER: return getPageManager(adaptable); case CURRENT_PAGE: return getCurrentPage(adaptable); case RESOURCE_PAGE: return getResourcePage(adaptable); case DESIGNER: return getDesigner(adaptable); case CURRENT_DESIGN: return getCurrentDesign(adaptable); case RESOURCE_DESIGN: return getResourceDesign(adaptable); case CURRENT_STYLE: return getCurrentStyle(adaptable); case SESSION: return getSession(adaptable); case XSS_API: return getXssApi(adaptable); default: return null; } }
#vulnerable code @Override public Object getValue(Object adaptable, String name, Type declaredType, AnnotatedElement element, DisposalCallbackRegistry callbackRegistry) { // sanity check if (!(adaptable instanceof Resource || adaptable instanceof SlingHttpServletRequest)) { return null; } ObjectType nameEnum = ObjectType.fromString(name); switch (nameEnum) { case RESOURCE: return getResource(adaptable); case RESOURCE_RESOLVER: return getResourceResolver(adaptable); case COMPONENT_CONTEXT: return getComponentContext(adaptable); case PAGE_MANAGER: return getPageManager(adaptable); case CURRENT_PAGE: return getCurrentPage(adaptable); case RESOURCE_PAGE: return getResourcePage(adaptable); case DESIGNER: return getDesigner(adaptable); case CURRENT_DESIGN: return getCurrentDesign(adaptable); case RESOURCE_DESIGN: return getResourceDesign(adaptable); case CURRENT_STYLE: return getCurrentStyle(adaptable); case SESSION: return getSession(adaptable); case XSS_API: return getXssApi(adaptable); default: return null; } } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String evaluate(Map<String, String> configIn, String key, String value) { checkConfig(configIn); try { HTable table = getHTable(configIn.get(TABLE_NAME_TAG), configIn.get(ZOOKEEPER_QUORUM_TAG)); Put thePut = new Put(key.getBytes()); thePut.add(configIn.get(FAMILY_TAG).getBytes(), configIn.get(QUALIFIER_TAG).getBytes(), value.getBytes()); table.put(thePut); return "Put " + key + ":" + value; } catch(Exception exc) { LOG.error("Error while doing HBase Puts"); throw new RuntimeException(exc); } }
#vulnerable code public String evaluate(Map<String, String> configIn, String key, String value) { if (!configIn.containsKey(FAMILY_TAG) || !configIn.containsKey(QUALIFIER_TAG) || !configIn.containsKey(TABLE_NAME_TAG) || !configIn.containsKey(ZOOKEEPER_QUORUM_TAG)) { String errorMsg = "Error while doing HBase Puts. Config is missing for: " + FAMILY_TAG + " or " + QUALIFIER_TAG + " or " + TABLE_NAME_TAG + " or " + ZOOKEEPER_QUORUM_TAG; LOG.error(errorMsg); throw new RuntimeException(errorMsg); } try { HTable table = getHTable(configIn.get(TABLE_NAME_TAG), configIn.get(ZOOKEEPER_QUORUM_TAG)); Put thePut = new Put(key.getBytes()); thePut.add(configIn.get(FAMILY_TAG).getBytes(), configIn.get(QUALIFIER_TAG).getBytes(), value.getBytes()); table.put(thePut); return "Put " + key + ":" + value; } catch(Exception exc) { LOG.error("Error while doing HBase Puts"); throw new RuntimeException(exc); } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void render(PebbleTemplateImpl self, Writer writer, EvaluationContext context) throws PebbleException, IOException { Object iterableEvaluation = iterableExpression.evaluate(self, context); Iterable<?> iterable = null; if (iterableEvaluation == null) { return; } iterable = toIterable(iterableEvaluation); if (iterable == null) { throw new PebbleException(null, "Not an iterable object. Value = [" + iterableEvaluation.toString() + "]", getLineNumber(), self.getName()); } Iterator<?> iterator = iterable.iterator(); boolean newScope = false; if (iterator.hasNext()) { ScopeChain scopeChain = context.getScopeChain(); /* * Only if there is a variable name conflict between one of the * variables added by the for loop construct and an existing * variable do we push another scope, otherwise we reuse the current * scope for performance purposes. */ if (scopeChain.currentScopeContainsVariable("loop") || scopeChain .currentScopeContainsVariable(variableName)) { scopeChain.pushScope(); newScope = true; } int length = getIteratorSize(iterableEvaluation); int index = 0; Map<String, Object> loop = null; boolean usingExecutorService = context.getExecutorService() != null; while (iterator.hasNext()) { /* * If the user is using an executor service (i.e. parallel node), we * must create a new map with every iteration instead of * re-using the same one; it's imperative that each thread would * get it's own distinct copy of the context. */ if (index == 0 || usingExecutorService) { loop = new HashMap<>(); loop.put("first", index == 0); loop.put("last", index == length - 1); loop.put("length", length); }else{ // second iteration if(index == 1){ loop.put("first", false); } // last iteration if(index == length - 1){ loop.put("last", true); } } loop.put("revindex", length - index - 1); loop.put("index", index++); scopeChain.put("loop", loop); scopeChain.put(variableName, iterator.next()); body.render(self, writer, context); } if (newScope) { scopeChain.popScope(); } } else if (elseBody != null) { elseBody.render(self, writer, context); } }
#vulnerable code @Override public void render(PebbleTemplateImpl self, Writer writer, EvaluationContext context) throws PebbleException, IOException { Object iterableEvaluation = iterableExpression.evaluate(self, context); Iterable<?> iterable = null; if (iterableEvaluation == null) { return; } iterable = toIterable(iterableEvaluation); Iterator<?> iterator = iterable.iterator(); boolean newScope = false; if (iterator.hasNext()) { ScopeChain scopeChain = context.getScopeChain(); /* * Only if there is a variable name conflict between one of the * variables added by the for loop construct and an existing * variable do we push another scope, otherwise we reuse the current * scope for performance purposes. */ if (scopeChain.currentScopeContainsVariable("loop") || scopeChain .currentScopeContainsVariable(variableName)) { scopeChain.pushScope(); newScope = true; } int length = getIteratorSize(iterableEvaluation); int index = 0; Map<String, Object> loop = null; boolean usingExecutorService = context.getExecutorService() != null; while (iterator.hasNext()) { /* * If the user is using an executor service (i.e. parallel node), we * must create a new map with every iteration instead of * re-using the same one; it's imperative that each thread would * get it's own distinct copy of the context. */ if (index == 0 || usingExecutorService) { loop = new HashMap<>(); loop.put("first", index == 0); loop.put("last", index == length - 1); loop.put("length", length); }else{ // second iteration if(index == 1){ loop.put("first", false); } // last iteration if(index == length - 1){ loop.put("last", true); } } loop.put("revindex", length - index - 1); loop.put("index", index++); scopeChain.put("loop", loop); scopeChain.put(variableName, iterator.next()); body.render(self, writer, context); } if (newScope) { scopeChain.popScope(); } } else if (elseBody != null) { elseBody.render(self, writer, context); } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object evaluate(PebbleTemplateImpl self, EvaluationContext context) throws PebbleException { Object object = node.evaluate(self, context); Object result = null; Object[] argumentValues = null; Member member = object == null ? null : memberCache.get(object.getClass()); if (object != null && member == null) { /* * If, and only if, no arguments were provided does it make sense to * check maps/arrays/lists */ if (args == null) { // first we check maps if (object instanceof Map && ((Map<?, ?>) object).containsKey(attributeName)) { return ((Map<?, ?>) object).get(attributeName); } try { // then we check arrays if (object instanceof Object[]) { Integer key = Integer.valueOf(attributeName); Object[] arr = ((Object[]) object); return arr[key]; } // then lists if (object instanceof List) { Integer key = Integer.valueOf(attributeName); @SuppressWarnings("unchecked") List<Object> list = (List<Object>) object; return list.get(key); } } catch (NumberFormatException ex) { // do nothing } } /* * Only one thread at a time should */ synchronized (memberLock) { if (member == null) { /* * turn args into an array of types and an array of values * in order to use them for our reflection calls */ argumentValues = getArgumentValues(self, context); Class<?>[] argumentTypes = new Class<?>[argumentValues.length]; for (int i = 0; i < argumentValues.length; i++) { argumentTypes[i] = argumentValues[i].getClass(); } member = reflect(object, attributeName, argumentTypes); memberCache.put(object.getClass(), member); } } } if (object != null && member != null) { if (argumentValues == null) { argumentValues = getArgumentValues(self, context); } result = invokeMember(object, member, argumentValues); } else if (context.isStrictVariables()) { throw new AttributeNotFoundException( null, String.format( "Attribute [%s] of [%s] does not exist or can not be accessed and strict variables is set to true.", attributeName, object.getClass().getName())); } return result; }
#vulnerable code @Override public Object evaluate(PebbleTemplateImpl self, EvaluationContext context) throws PebbleException { Object object = node.evaluate(self, context); Object result = null; Object[] argumentValues = null; if (object != null && member == null) { /* * If, and only if, no arguments were provided does it make sense to * check maps/arrays/lists */ if (args == null) { // first we check maps if (object instanceof Map && ((Map<?, ?>) object).containsKey(attributeName)) { return ((Map<?, ?>) object).get(attributeName); } try { // then we check arrays if (object instanceof Object[]) { Integer key = Integer.valueOf(attributeName); Object[] arr = ((Object[]) object); return arr[key]; } // then lists if (object instanceof List) { Integer key = Integer.valueOf(attributeName); @SuppressWarnings("unchecked") List<Object> list = (List<Object>) object; return list.get(key); } } catch (NumberFormatException ex) { // do nothing } } /* * Only one thread at a time should */ synchronized (memberLock) { if (member == null) { /* * turn args into an array of types and an array of values * in order to use them for our reflection calls */ argumentValues = getArgumentValues(self, context); Class<?>[] argumentTypes = new Class<?>[argumentValues.length]; for (int i = 0; i < argumentValues.length; i++) { argumentTypes[i] = argumentValues[i].getClass(); } member = reflect(object, attributeName, argumentTypes); } } } if (object != null && member != null) { if (argumentValues == null) { argumentValues = getArgumentValues(self, context); } result = invokeMember(object, member, argumentValues); } else if (context.isStrictVariables()) { throw new AttributeNotFoundException( null, String.format( "Attribute [%s] of [%s] does not exist or can not be accessed and strict variables is set to true.", attributeName, object.getClass().getName())); } return result; } #location 77 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evaluateBlock(String blockName, Writer writer, Map<String, Object> map, Locale locale) throws PebbleException, IOException { EvaluationContext context = this.initContext(locale); context.getScopeChain().pushScope(map); this.evaluate(new NoopWriter(), context); this.block(writer, context, blockName, false); writer.flush(); }
#vulnerable code public void evaluateBlock(String blockName, Writer writer, Map<String, Object> map, Locale locale) throws PebbleException, IOException { EvaluationContext context = this.initContext(locale); context.getScopeChain().pushScope(map); final Writer nowhere = new Writer() { public void write(char[] cbuf, int off, int len) throws IOException {} public void flush() throws IOException {} public void close() throws IOException {} }; this.evaluate(nowhere, context); this.block(writer, context, blockName, false); writer.flush(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object evaluate(PebbleTemplateImpl self, EvaluationContext context) throws PebbleException { Object object = node.evaluate(self, context); Object result = null; Object[] argumentValues = null; Member member = object == null ? null : memberCache.get(object.getClass()); if (object != null && member == null) { /* * If, and only if, no arguments were provided does it make sense to * check maps/arrays/lists */ if (args == null) { // first we check maps if (object instanceof Map && ((Map<?, ?>) object).containsKey(attributeName)) { return ((Map<?, ?>) object).get(attributeName); } try { // then we check arrays if (object instanceof Object[]) { Integer key = Integer.valueOf(attributeName); Object[] arr = ((Object[]) object); return arr[key]; } // then lists if (object instanceof List) { Integer key = Integer.valueOf(attributeName); @SuppressWarnings("unchecked") List<Object> list = (List<Object>) object; return list.get(key); } } catch (NumberFormatException ex) { // do nothing } } /* * turn args into an array of types and an array of values in order * to use them for our reflection calls */ argumentValues = getArgumentValues(self, context); Class<?>[] argumentTypes = new Class<?>[argumentValues.length]; for (int i = 0; i < argumentValues.length; i++) { argumentTypes[i] = argumentValues[i].getClass(); } member = reflect(object, attributeName, argumentTypes); if (member != null) { memberCache.put(object.getClass(), member); } } if (object != null && member != null) { if (argumentValues == null) { argumentValues = getArgumentValues(self, context); } result = invokeMember(object, member, argumentValues); } else if (context.isStrictVariables()) { if (object == null) { final String rootPropertyName = ((ContextVariableExpression)node).getName(); throw new RootAttributeNotFoundException( null, String.format( "Root attribute [%s] does not exist or can not be accessed and strict variables is set to true.", rootPropertyName)); } else { throw new AttributeNotFoundException( null, String.format( "Attribute [%s] of [%s] does not exist or can not be accessed and strict variables is set to true.", attributeName, object.getClass().getName())); } } return result; }
#vulnerable code @Override public Object evaluate(PebbleTemplateImpl self, EvaluationContext context) throws PebbleException { Object object = node.evaluate(self, context); Object result = null; Object[] argumentValues = null; Member member = object == null ? null : memberCache.get(object.getClass()); if (object != null && member == null) { /* * If, and only if, no arguments were provided does it make sense to * check maps/arrays/lists */ if (args == null) { // first we check maps if (object instanceof Map && ((Map<?, ?>) object).containsKey(attributeName)) { return ((Map<?, ?>) object).get(attributeName); } try { // then we check arrays if (object instanceof Object[]) { Integer key = Integer.valueOf(attributeName); Object[] arr = ((Object[]) object); return arr[key]; } // then lists if (object instanceof List) { Integer key = Integer.valueOf(attributeName); @SuppressWarnings("unchecked") List<Object> list = (List<Object>) object; return list.get(key); } } catch (NumberFormatException ex) { // do nothing } } /* * turn args into an array of types and an array of values in order * to use them for our reflection calls */ argumentValues = getArgumentValues(self, context); Class<?>[] argumentTypes = new Class<?>[argumentValues.length]; for (int i = 0; i < argumentValues.length; i++) { argumentTypes[i] = argumentValues[i].getClass(); } member = reflect(object, attributeName, argumentTypes); if (member != null) { memberCache.put(object.getClass(), member); } } if (object != null && member != null) { if (argumentValues == null) { argumentValues = getArgumentValues(self, context); } result = invokeMember(object, member, argumentValues); } else if (context.isStrictVariables()) { throw new AttributeNotFoundException( null, String.format( "Attribute [%s] of [%s] does not exist or can not be accessed and strict variables is set to true.", attributeName, object.getClass().getName())); } return result; } #location 74 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected MetricData getRollupByGranularity( String tenantId, String metricName, long from, long to, Granularity g) { final Timer.Context ctx = metricsFetchTimer.time(); final Locator locator = Locator.createLocatorFromPathComponents(tenantId, metricName); final MetricData metricData = AstyanaxReader.getInstance().getDatapointsForRange( locator, new Range(g.snapMillis(from), to), g); boolean isRollable = metricData.getType().equals(MetricData.Type.NUMBER.toString()) || metricData.getType().equals(MetricData.Type.HISTOGRAM.toString()); // if Granularity is FULL, we are missing raw data - can't generate that if (ROLLUP_REPAIR && isRollable && g != Granularity.FULL && metricData != null) { final Timer.Context rollupsCalcCtx = rollupsCalcOnReadTimer.time(); if (metricData.getData().isEmpty()) { // data completely missing for range. complete repair. rollupsRepairEntireRange.mark(); List<Points.Point> repairedPoints = repairRollupsOnRead(locator, g, from, to); for (Points.Point repairedPoint : repairedPoints) { metricData.getData().add(repairedPoint); } if (repairedPoints.isEmpty()) { rollupsRepairEntireRangeEmpty.mark(); } } else { long actualStart = minTime(metricData.getData()); long actualEnd = maxTime(metricData.getData()); // If the returned start is greater than 'from', we are missing a portion of data. if (actualStart > from) { rollupsRepairedLeft.mark(); List<Points.Point> repairedLeft = repairRollupsOnRead(locator, g, from, actualStart); for (Points.Point repairedPoint : repairedLeft) { metricData.getData().add(repairedPoint); } if (repairedLeft.isEmpty()) { rollupsRepairedLeftEmpty.mark(); } } // If the returned end timestamp is less than 'to', we are missing a portion of data. if (actualEnd + g.milliseconds() <= to) { rollupsRepairedRight.mark(); List<Points.Point> repairedRight = repairRollupsOnRead(locator, g, actualEnd + g.milliseconds(), to); for (Points.Point repairedPoint : repairedRight) { metricData.getData().add(repairedPoint); } if (repairedRight.isEmpty()) { rollupsRepairedRightEmpty.mark(); } } } rollupsCalcCtx.stop(); } ctx.stop(); if (g == Granularity.FULL) { numFullPointsReturned.update(metricData.getData().getPoints().size()); } else { numRollupPointsReturned.update(metricData.getData().getPoints().size()); } return metricData; }
#vulnerable code protected MetricData getRollupByGranularity( String tenantId, String metricName, long from, long to, Granularity g) { final Timer.Context ctx = metricsFetchTimer.time(); final Locator locator = Locator.createLocatorFromPathComponents(tenantId, metricName); final MetricData metricData = AstyanaxReader.getInstance().getDatapointsForRange( locator, new Range(g.snapMillis(from), to), g); // if Granularity is FULL, we are missing raw data - can't generate that if (ROLLUP_REPAIR && g != Granularity.FULL && metricData != null) { final Timer.Context rollupsCalcCtx = rollupsCalcOnReadTimer.time(); if (metricData.getData().isEmpty()) { // data completely missing for range. complete repair. rollupsRepairEntireRange.mark(); List<Points.Point> repairedPoints = repairRollupsOnRead(locator, g, from, to); for (Points.Point repairedPoint : repairedPoints) { metricData.getData().add(repairedPoint); } if (repairedPoints.isEmpty()) { rollupsRepairEntireRangeEmpty.mark(); } } else { long actualStart = minTime(metricData.getData()); long actualEnd = maxTime(metricData.getData()); // If the returned start is greater than 'from', we are missing a portion of data. if (actualStart > from) { rollupsRepairedLeft.mark(); List<Points.Point> repairedLeft = repairRollupsOnRead(locator, g, from, actualStart); for (Points.Point repairedPoint : repairedLeft) { metricData.getData().add(repairedPoint); } if (repairedLeft.isEmpty()) { rollupsRepairedLeftEmpty.mark(); } } // If the returned end timestamp is less than 'to', we are missing a portion of data. if (actualEnd + g.milliseconds() <= to) { rollupsRepairedRight.mark(); List<Points.Point> repairedRight = repairRollupsOnRead(locator, g, actualEnd + g.milliseconds(), to); for (Points.Point repairedPoint : repairedRight) { metricData.getData().add(repairedPoint); } if (repairedRight.isEmpty()) { rollupsRepairedRightEmpty.mark(); } } } rollupsCalcCtx.stop(); } ctx.stop(); if (g == Granularity.FULL) { numFullPointsReturned.update(metricData.getData().getPoints().size()); } else { numRollupPointsReturned.update(metricData.getData().getPoints().size()); } return metricData; } #location 66 #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) { if (args.length != 5){ System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE"); System.exit(1); } String testClassName = args[0]; String testMethodName = args[1]; String testInputFile = args[2]; String a2jPipe = args[3]; String j2aPipe = args[4]; try { // Load the guidance Guidance guidance = new AFLPerformanceGuidance(testInputFile, a2jPipe, j2aPipe); // Run the Junit test GuidedFuzzing.run(testClassName, testMethodName, guidance, System.out); } catch (ClassNotFoundException e) { System.err.println(String.format("Cannot load class %s", testClassName)); e.printStackTrace(); System.exit(2); } catch (IOException e) { e.printStackTrace(); System.exit(3); } }
#vulnerable code public static void main(String[] args) { if (args.length != 5){ System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE"); System.exit(1); } String testClassName = args[0]; String testMethodName = args[1]; String testInputFile = args[2]; String a2jPipe = args[3]; String j2aPipe = args[4]; try { // Load the guidance Guidance guidance = new AFLRedundancyGuidance(testInputFile, a2jPipe, j2aPipe); // Run the Junit test GuidedFuzzing.run(testClassName, testMethodName, guidance, System.out); } catch (ClassNotFoundException e) { System.err.println(String.format("Cannot load class %s", testClassName)); e.printStackTrace(); System.exit(2); } catch (IOException e) { e.printStackTrace(); System.exit(3); } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { ClassLoader loader; ZestGuidance guidance; Log log = getLog(); PrintStream out = System.out; // TODO: Re-route to logger from super.getLog() Result result; // Configure classes to instrument if (excludes != null) { System.setProperty("janala.excludes", excludes); } if (includes != null) { System.setProperty("janala.includes", includes); } // Configure Zest Guidance if (saveAll) { System.setProperty("jqf.ei.SAVE_ALL_INPUTS", "true"); } if (libFuzzerCompatOutput != null) { System.setProperty("jqf.ei.LIBFUZZER_COMPAT_OUTPUT", libFuzzerCompatOutput); } if (quiet) { System.setProperty("jqf.ei.QUIET_MODE", "true"); } if (exitOnCrash != null) { System.setProperty("jqf.ei.EXIT_ON_CRASH", exitOnCrash); } if (runTimeout > 0) { System.setProperty("jqf.ei.TIMEOUT", String.valueOf(runTimeout)); } Duration duration = null; if (time != null && !time.isEmpty()) { try { duration = Duration.parse("PT"+time); } catch (DateTimeParseException e) { throw new MojoExecutionException("Invalid time duration: " + time); } } if (outputDirectory == null || outputDirectory.isEmpty()) { outputDirectory = "fuzz-results" + File.separator + testClassName + File.separator + testMethod; } try { List<String> classpathElements = project.getTestClasspathElements(); if (disableCoverage) { loader = new URLClassLoader( stringsToUrls(classpathElements.toArray(new String[0])), getClass().getClassLoader()); } else { loader = new InstrumentingClassLoader( classpathElements.toArray(new String[0]), getClass().getClassLoader()); } } catch (DependencyResolutionRequiredException|MalformedURLException e) { throw new MojoExecutionException("Could not get project classpath", e); } try { File resultsDir = new File(target, outputDirectory); String targetName = testClassName + "#" + testMethod; File seedsDir = inputDirectory == null ? null : new File(inputDirectory); switch (engine) { case "zest": guidance = new ZestGuidance(targetName, duration, resultsDir, seedsDir); break; case "zeal": System.setProperty("jqf.traceGenerators", "true"); guidance = new ExecutionIndexingGuidance(targetName, duration, resultsDir, seedsDir); break; default: throw new MojoExecutionException("Unknown fuzzing engine: " + engine); } guidance.setBlind(blind); } catch (IOException e) { throw new MojoExecutionException("Could not create output directory", e); } try { result = GuidedFuzzing.run(testClassName, testMethod, loader, guidance, out); } catch (ClassNotFoundException e) { throw new MojoExecutionException("Could not load test class", e); } catch (IllegalArgumentException e) { throw new MojoExecutionException("Bad request", e); } catch (RuntimeException e) { throw new MojoExecutionException("Internal error", e); } if (!result.wasSuccessful()) { throw new MojoFailureException("Fuzzing revealed errors. " + "Use mvn jqf:repro to reproduce failing test case."); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { ClassLoader loader; ZestGuidance guidance; Log log = getLog(); PrintStream out = System.out; // TODO: Re-route to logger from super.getLog() Result result; // Configure classes to instrument if (excludes != null) { System.setProperty("janala.excludes", excludes); } if (includes != null) { System.setProperty("janala.includes", includes); } // Configure Zest Guidance if (saveAll) { System.setProperty("jqf.ei.SAVE_ALL_INPUTS", "true"); } if (libFuzzerCompatOutput != null) { System.setProperty("jqf.ei.LIBFUZZER_COMPAT_OUTPUT", libFuzzerCompatOutput); } if (quiet) { System.setProperty("jqf.ei.QUIET_MODE", "true"); } if (exitOnCrash != null) { System.setProperty("jqf.ei.EXIT_ON_CRASH", exitOnCrash); } if (runTimeout > 0) { System.setProperty("jqf.ei.TIMEOUT", String.valueOf(runTimeout)); } Duration duration = null; if (time != null && !time.isEmpty()) { try { duration = Duration.parse("PT"+time); } catch (DateTimeParseException e) { throw new MojoExecutionException("Invalid time duration: " + time); } } if (outputDirectory == null || outputDirectory.isEmpty()) { outputDirectory = "fuzz-results" + File.separator + testClassName + File.separator + testMethod; } try { List<String> classpathElements = project.getTestClasspathElements(); if (disableCoverage) { loader = new URLClassLoader( stringsToUrls(classpathElements.toArray(new String[0])), getClass().getClassLoader()); } else { loader = new InstrumentingClassLoader( classpathElements.toArray(new String[0]), getClass().getClassLoader()); } } catch (DependencyResolutionRequiredException|MalformedURLException e) { throw new MojoExecutionException("Could not get project classpath", e); } try { File resultsDir = new File(target, outputDirectory); String targetName = testClassName + "#" + testMethod; if (inputDirectory != null) { File seedsDir = new File(inputDirectory); guidance = new ZestGuidance(targetName, duration, resultsDir, seedsDir); } else { guidance = new ZestGuidance(targetName, duration, resultsDir); } guidance.setBlind(blind); } catch (IOException e) { throw new MojoExecutionException("Could not create output directory", e); } try { result = GuidedFuzzing.run(testClassName, testMethod, loader, guidance, out); } catch (ClassNotFoundException e) { throw new MojoExecutionException("Could not load test class", e); } catch (IllegalArgumentException e) { throw new MojoExecutionException("Bad request", e); } catch (RuntimeException e) { throw new MojoExecutionException("Internal error", e); } if (!result.wasSuccessful()) { throw new MojoFailureException("Fuzzing revealed errors. " + "Use mvn jqf:repro to reproduce failing test case."); } } #location 74 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void prepareOutputDirectory() throws IOException { // Create the output directory if it does not exist if (!outputDirectory.exists()) { if (!outputDirectory.mkdirs()) { throw new IOException("Could not create output directory" + outputDirectory.getAbsolutePath()); } } // Make sure we can write to output directory if (!outputDirectory.isDirectory() || !outputDirectory.canWrite()) { throw new IOException("Output directory is not a writable directory: " + outputDirectory.getAbsolutePath()); } // Name files and directories after AFL this.savedCorpusDirectory = new File(outputDirectory, "corpus"); this.savedCorpusDirectory.mkdirs(); this.savedFailuresDirectory = new File(outputDirectory, "failures"); this.savedFailuresDirectory.mkdirs(); this.statsFile = new File(outputDirectory, "plot_data"); this.logFile = new File(outputDirectory, "fuzz.log"); this.currentInputFile = new File(outputDirectory, ".cur_input"); // Delete everything that we may have created in a previous run. // Trying to stay away from recursive delete of parent output directory in case there was a // typo and that was not a directory we wanted to nuke. // We also do not check if the deletes are actually successful. statsFile.delete(); logFile.delete(); for (File file : savedCorpusDirectory.listFiles()) { file.delete(); } for (File file : savedFailuresDirectory.listFiles()) { file.delete(); } appendLineToFile(statsFile,"# unix_time, cycles_done, cur_path, paths_total, pending_total, " + "pending_favs, map_size, unique_crashes, unique_hangs, max_depth, execs_per_sec, valid_inputs, invalid_inputs, valid_cov"); }
#vulnerable code private void prepareOutputDirectory() throws IOException { // Create the output directory if it does not exist if (!outputDirectory.exists()) { if (!outputDirectory.mkdirs()) { throw new IOException("Could not create output directory" + outputDirectory.getAbsolutePath()); } } // Make sure we can write to output directory if (!outputDirectory.isDirectory() || !outputDirectory.canWrite()) { throw new IOException("Output directory is not a writable directory: " + outputDirectory.getAbsolutePath()); } // Name files and directories after AFL this.savedInputsDirectory = new File(outputDirectory, "corpus"); this.savedInputsDirectory.mkdirs(); this.savedFailuresDirectory = new File(outputDirectory, "failures"); this.savedFailuresDirectory.mkdirs(); this.statsFile = new File(outputDirectory, "plot_data"); this.logFile = new File(outputDirectory, "fuzz.log"); this.currentInputFile = new File(outputDirectory, ".cur_input"); // Delete everything that we may have created in a previous run. // Trying to stay away from recursive delete of parent output directory in case there was a // typo and that was not a directory we wanted to nuke. // We also do not check if the deletes are actually successful. statsFile.delete(); logFile.delete(); for (File file : savedInputsDirectory.listFiles()) { file.delete(); } for (File file : savedFailuresDirectory.listFiles()) { file.delete(); } appendLineToFile(statsFile,"# unix_time, cycles_done, cur_path, paths_total, pending_total, " + "pending_favs, map_size, unique_crashes, unique_hangs, max_depth, execs_per_sec, valid_inputs, invalid_inputs, valid_cov"); } #location 33 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private File[] readSeedFiles() { if (this.inputDirectory == null) { return new File[0]; } ArrayList<File> seedFilesArray = new ArrayList<>(); File[] allFiles = this.inputDirectory.listFiles(); if (allFiles == null) { // this means the directory doesn't exist return new File[0]; } for (int i = 0; i < allFiles.length; i++) { if (allFiles[i].isFile()) { seedFilesArray.add(allFiles[i]); } } File[] seedFiles = seedFilesArray.toArray(new File[seedFilesArray.size()]); return seedFiles; }
#vulnerable code private File[] readSeedFiles() { if (this.inputDirectory == null) { return new File[0]; } ArrayList<File> seedFilesArray = new ArrayList<>(); File[] allFiles = this.inputDirectory.listFiles(); for (int i = 0; i < allFiles.length; i++) { if (allFiles[i].isFile()) { seedFilesArray.add(allFiles[i]); } } File[] seedFiles = seedFilesArray.toArray(new File[seedFilesArray.size()]); return seedFiles; } #location 8 #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) { if (args.length != 5){ System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE"); System.exit(1); } String testClassName = args[0]; String testMethodName = args[1]; String testInputFile = args[2]; String a2jPipe = args[3]; String j2aPipe = args[4]; try { // Load the guidance Guidance guidance = new AFLPerformanceGuidance(testInputFile, a2jPipe, j2aPipe); // Run the Junit test GuidedFuzzing.run(testClassName, testMethodName, guidance, System.out); } catch (Exception e) { e.printStackTrace(); System.exit(2); } }
#vulnerable code public static void main(String[] args) { if (args.length != 5){ System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE"); System.exit(1); } String testClassName = args[0]; String testMethodName = args[1]; String testInputFile = args[2]; String a2jPipe = args[3]; String j2aPipe = args[4]; try { // Load the guidance Guidance guidance = new AFLPerformanceGuidance(testInputFile, a2jPipe, j2aPipe); // Run the Junit test GuidedFuzzing.run(testClassName, testMethodName, guidance, System.out); } catch (ClassNotFoundException e) { System.err.println(String.format("Cannot load class %s", testClassName)); e.printStackTrace(); System.exit(2); } catch (IOException e) { e.printStackTrace(); System.exit(3); } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void prepareOutputDirectory() throws IOException { // Create the output directory if it does not exist if (!outputDirectory.exists()) { if (!outputDirectory.mkdirs()) { throw new IOException("Could not create output directory" + outputDirectory.getAbsolutePath()); } } // Make sure we can write to output directory if (!outputDirectory.isDirectory() || !outputDirectory.canWrite()) { throw new IOException("Output directory is not a writable directory: " + outputDirectory.getAbsolutePath()); } // Name files and directories after AFL this.savedInputsDirectory = new File(outputDirectory, "queue"); this.savedInputsDirectory.mkdirs(); this.savedFailuresDirectory = new File(outputDirectory, "crashes"); this.savedFailuresDirectory.mkdirs(); this.statsFile = new File(outputDirectory, "plot_data"); this.logFile = new File(outputDirectory, "ei.log"); // Delete everything that we may have created in a previous run. // Trying to stay away from recursive delete of parent output directory in case there was a // typo and that was not a directory we wanted to nuke. // We also do not check if the deletes are actually successful. statsFile.delete(); logFile.delete(); for (File file : savedInputsDirectory.listFiles()) { file.delete(); } for (File file : savedFailuresDirectory.listFiles()) { file.delete(); } appendLineToFile(statsFile,"# unix_time, cycles_done, cur_path, paths_total, pending_total, " + "pending_favs, map_size, unique_crashes, unique_hangs, max_depth, execs_per_sec"); }
#vulnerable code private void prepareOutputDirectory() throws IOException { // Create the output directory if it does not exist if (!outputDirectory.exists()) { if (!outputDirectory.mkdirs()) { throw new IOException("Could not create output directory" + outputDirectory.getAbsolutePath()); } } // Make sure we can write to output directory if (!outputDirectory.isDirectory() || !outputDirectory.canWrite()) { throw new IOException("Output directory is not a writable directory: " + outputDirectory.getAbsolutePath()); } // Delete everything in the output directory (for cases where we re-use an existing dir) for (File file : outputDirectory.listFiles()) { file.delete(); // We do not check if this was successful } this.statsFile = new File(outputDirectory, "plot_data"); this.logFile = new File(outputDirectory, "ei.log"); appendLineToFile(statsFile,"# unix_time, cycles_done, cur_path, paths_total, pending_total, " + "pending_favs, map_size, unique_crashes, unique_hangs, max_depth, execs_per_sec"); } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) { return execute(jerseyRequest).whenCompleteAsync((r, th) -> { if (th == null) jerseyCallback.response(r); else jerseyCallback.failure(th); }, executorService); }
#vulnerable code @Override public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) { final CompletableFuture<Object> settableFuture = new CompletableFuture<>(); final URI requestUri = jerseyRequest.getUri(); String host = requestUri.getHost(); int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80; try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // Enable HTTPS if necessary. if ("https".equals(requestUri.getScheme())) { // making client authentication optional for now; it could be extracted to configurable property JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE); p.addLast(jdkSslContext.newHandler(ch.alloc())); } // http proxy Configuration config = jerseyRequest.getConfiguration(); final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI); if (proxyUri != null) { final URI u = getProxyUri(proxyUri); final String userName = ClientProperties.getValue( config.getProperties(), ClientProperties.PROXY_USERNAME, String.class); final String password = ClientProperties.getValue( config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class); p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password)); } p.addLast(new HttpClientCodec()); p.addLast(new ChunkedWriteHandler()); p.addLast(new HttpContentDecompressor()); p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture)); } }); // connect timeout Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0); if (connectTimeout > 0) { b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); } // Make the connection attempt. final Channel ch = b.connect(host, port).sync().channel(); // guard against prematurely closed channel final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() { @Override public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception { if (!settableFuture.isDone()) { settableFuture.completeExceptionally(new IOException("Channel closed.")); } } }; ch.closeFuture().addListener(closeListener); HttpRequest nettyRequest; String pathWithQuery = buildPathWithQueryParameters(requestUri); if (jerseyRequest.hasEntity()) { nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), pathWithQuery); } else { nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), pathWithQuery); } // headers for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) { nettyRequest.headers().add(e.getKey(), e.getValue()); } // host header - http 1.1 nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost()); if (jerseyRequest.hasEntity()) { if (jerseyRequest.getLengthLong() == -1) { HttpUtil.setTransferEncodingChunked(nettyRequest, true); } else { nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong()); } } if (jerseyRequest.hasEntity()) { // Send the HTTP request. ch.writeAndFlush(nettyRequest); final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch); jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(int contentLength) throws IOException { return jerseyChunkedInput; } }); if (HttpUtil.isTransferEncodingChunked(nettyRequest)) { ch.write(new HttpChunkedInput(jerseyChunkedInput)); } else { ch.write(jerseyChunkedInput); } executorService.execute(new Runnable() { @Override public void run() { // close listener is not needed any more. ch.closeFuture().removeListener(closeListener); try { jerseyRequest.writeEntity(); } catch (IOException e) { jerseyCallback.failure(e); settableFuture.completeExceptionally(e); } } }); ch.flush(); } else { // close listener is not needed any more. ch.closeFuture().removeListener(closeListener); // Send the HTTP request. ch.writeAndFlush(nettyRequest); } } catch (InterruptedException e) { settableFuture.completeExceptionally(e); return settableFuture; } return settableFuture; } #location 86 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void writeTo(final Object object, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { final Output output = new Output(entityStream); kryoPool.ifPresent(a -> a.run(new KryoCallback() { public Object execute(Kryo kryo) { kryo.writeObject(output, object); return null; } })); output.flush(); }
#vulnerable code @Override public void writeTo(final Object object, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { final Output output = new Output(entityStream); kryoPool.run(new KryoCallback() { public Object execute(Kryo kryo) { kryo.writeObject(output, object); return null; } }); output.flush(); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { final EntityInputStream entityInputStream = new EntityInputStream(entityStream); entityStream = entityInputStream; if (entityInputStream.isEmpty()) { throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM()); } Jsonb jsonb = getJsonb(type); try { return jsonb.fromJson(entityStream, genericType); } catch (JsonbException e) { throw new ProcessingException(LocalizationMessages.ERROR_JSONB_DESERIALIZATION(), e); } }
#vulnerable code @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { if (entityStream.markSupported()) { entityStream.mark(1); if (entityStream.read() == -1) { throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM()); } entityStream.reset(); } else { final PushbackInputStream buffer = new PushbackInputStream(entityStream); final int firstByte = buffer.read(); if (firstByte == -1) { throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM()); } buffer.unread(firstByte); entityStream = buffer; } Jsonb jsonb = getJsonb(type); try { return jsonb.fromJson(entityStream, genericType); } catch (JsonbException e) { throw new ProcessingException(LocalizationMessages.ERROR_JSONB_DESERIALIZATION(), e); } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object readFrom(final Class<Object> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException { final Input input = new Input(entityStream); return kryoPool.map(pool -> pool.run(new KryoCallback() { public Object execute(Kryo kryo) { return kryo.readObject(input, type); } })).orElse(null); }
#vulnerable code @Override public Object readFrom(final Class<Object> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException { final Input input = new Input(entityStream); return kryoPool.run(new KryoCallback() { public Object execute(Kryo kryo) { return kryo.readObject(input, type); } }); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { final EntityInputStream entityInputStream = new EntityInputStream(entityStream); entityStream = entityInputStream; if (entityInputStream.isEmpty()) { throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM()); } Jsonb jsonb = getJsonb(type); try { return jsonb.fromJson(entityStream, genericType); } catch (JsonbException e) { throw new ProcessingException(LocalizationMessages.ERROR_JSONB_DESERIALIZATION(), e); } }
#vulnerable code @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { if (entityStream.markSupported()) { entityStream.mark(1); if (entityStream.read() == -1) { throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM()); } entityStream.reset(); } else { final PushbackInputStream buffer = new PushbackInputStream(entityStream); final int firstByte = buffer.read(); if (firstByte == -1) { throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM()); } buffer.unread(firstByte); entityStream = buffer; } Jsonb jsonb = getJsonb(type); try { return jsonb.fromJson(entityStream, genericType); } catch (JsonbException e) { throw new ProcessingException(LocalizationMessages.ERROR_JSONB_DESERIALIZATION(), e); } } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object intercept(Invocation invocation) throws Throwable { try { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; Executor executor = (Executor) invocation.getTarget(); CacheKey cacheKey; BoundSql boundSql; //由于逻辑关系,只会进入一次 if (args.length == 4) { //4 个参数时 boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { //6 个参数时 cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } checkDialectExists(); List resultList; //调用方法判断是否需要进行分页,如果不需要,直接返回结果 if (!dialect.skip(ms, parameter, rowBounds)) { //判断是否需要进行 count 查询 if (dialect.beforeCount(ms, parameter, rowBounds)) { //查询总数 Long count = count(executor, ms, parameter, rowBounds, resultHandler, boundSql); //处理查询总数,返回 true 时继续分页查询,false 时直接返回 if (!dialect.afterCount(count, parameter, rowBounds)) { //当查询总数为 0 时,直接返回空的结果 return dialect.afterPage(new ArrayList(), parameter, rowBounds); } } resultList = ExecutorUtil.pageQuery(dialect, executor, ms, parameter, rowBounds, resultHandler, boundSql, cacheKey); } else { //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } return dialect.afterPage(resultList, parameter, rowBounds); } finally { dialect.afterAll(); } }
#vulnerable code @Override public Object intercept(Invocation invocation) throws Throwable { try { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; Executor executor = (Executor) invocation.getTarget(); CacheKey cacheKey; BoundSql boundSql; //由于逻辑关系,只会进入一次 if(args.length == 4){ //4 个参数时 boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { //6 个参数时 cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } // Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化 // 因此这里会出现 null 的情况 fixed #26 if(dialect == null){ synchronized (default_dialect_class){ if(dialect == null){ setProperties(new Properties()); } } } List resultList; //调用方法判断是否需要进行分页,如果不需要,直接返回结果 if (!dialect.skip(ms, parameter, rowBounds)) { //反射获取动态参数 String msId = ms.getId(); Configuration configuration = ms.getConfiguration(); Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql); //判断是否需要进行 count 查询 if (dialect.beforeCount(ms, parameter, rowBounds)) { String countMsId = msId + countSuffix; Long count; //先判断是否存在手写的 count 查询 MappedStatement countMs = getExistedMappedStatement(configuration, countMsId); if(countMs != null){ count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler); } else { countMs = msCountMap.get(countMsId); //自动创建 if (countMs == null) { //根据当前的 ms 创建一个返回值为 Long 类型的 ms countMs = MSUtils.newCountMappedStatement(ms, countMsId); msCountMap.put(countMsId, countMs); } count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler); } //处理查询总数 //返回 true 时继续分页查询,false 时直接返回 if (!dialect.afterCount(count, parameter, rowBounds)) { //当查询总数为 0 时,直接返回空的结果 return dialect.afterPage(new ArrayList(), parameter, rowBounds); } } //判断是否需要进行分页查询 if (dialect.beforePage(ms, parameter, rowBounds)) { //生成分页的缓存 key CacheKey pageKey = cacheKey; //处理参数对象 parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); //调用方言获取分页 sql String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter); //设置动态参数 for (String key : additionalParameters.keySet()) { pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); } //执行分页查询 resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); } else { //不执行分页的情况下,也不执行内存分页 resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); } } else { //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } return dialect.afterPage(resultList, parameter, rowBounds); } finally { dialect.afterAll(); } } #location 38 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object intercept(Invocation invocation) throws Throwable { try { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; Executor executor = (Executor) invocation.getTarget(); CacheKey cacheKey; BoundSql boundSql; //由于逻辑关系,只会进入一次 if (args.length == 4) { //4 个参数时 boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { //6 个参数时 cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } checkDialectExists(); List resultList; //调用方法判断是否需要进行分页,如果不需要,直接返回结果 if (!dialect.skip(ms, parameter, rowBounds)) { //判断是否需要进行 count 查询 if (dialect.beforeCount(ms, parameter, rowBounds)) { //查询总数 Long count = count(executor, ms, parameter, rowBounds, resultHandler, boundSql); //处理查询总数,返回 true 时继续分页查询,false 时直接返回 if (!dialect.afterCount(count, parameter, rowBounds)) { //当查询总数为 0 时,直接返回空的结果 return dialect.afterPage(new ArrayList(), parameter, rowBounds); } } resultList = ExecutorUtil.pageQuery(dialect, executor, ms, parameter, rowBounds, resultHandler, boundSql, cacheKey); } else { //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } return dialect.afterPage(resultList, parameter, rowBounds); } finally { dialect.afterAll(); } }
#vulnerable code @Override public Object intercept(Invocation invocation) throws Throwable { try { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; Executor executor = (Executor) invocation.getTarget(); CacheKey cacheKey; BoundSql boundSql; //由于逻辑关系,只会进入一次 if(args.length == 4){ //4 个参数时 boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { //6 个参数时 cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } // Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化 // 因此这里会出现 null 的情况 fixed #26 if(dialect == null){ synchronized (default_dialect_class){ if(dialect == null){ setProperties(new Properties()); } } } List resultList; //调用方法判断是否需要进行分页,如果不需要,直接返回结果 if (!dialect.skip(ms, parameter, rowBounds)) { //反射获取动态参数 String msId = ms.getId(); Configuration configuration = ms.getConfiguration(); Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql); //判断是否需要进行 count 查询 if (dialect.beforeCount(ms, parameter, rowBounds)) { String countMsId = msId + countSuffix; Long count; //先判断是否存在手写的 count 查询 MappedStatement countMs = getExistedMappedStatement(configuration, countMsId); if(countMs != null){ count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler); } else { countMs = msCountMap.get(countMsId); //自动创建 if (countMs == null) { //根据当前的 ms 创建一个返回值为 Long 类型的 ms countMs = MSUtils.newCountMappedStatement(ms, countMsId); msCountMap.put(countMsId, countMs); } count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler); } //处理查询总数 //返回 true 时继续分页查询,false 时直接返回 if (!dialect.afterCount(count, parameter, rowBounds)) { //当查询总数为 0 时,直接返回空的结果 return dialect.afterPage(new ArrayList(), parameter, rowBounds); } } //判断是否需要进行分页查询 if (dialect.beforePage(ms, parameter, rowBounds)) { //生成分页的缓存 key CacheKey pageKey = cacheKey; //处理参数对象 parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); //调用方言获取分页 sql String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter); //设置动态参数 for (String key : additionalParameters.keySet()) { pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); } //执行分页查询 resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); } else { //不执行分页的情况下,也不执行内存分页 resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); } } else { //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } return dialect.afterPage(resultList, parameter, rowBounds); } finally { dialect.afterAll(); } } #location 53 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object intercept(Invocation invocation) throws Throwable { if (autoRuntimeDialect) { SqlUtil sqlUtil = getSqlUtil(invocation); return sqlUtil.processPage(invocation); } else { if (autoDialect) { initSqlUtil(invocation); } return sqlUtil.processPage(invocation); } }
#vulnerable code public Object intercept(Invocation invocation) throws Throwable { SqlUtil sqlUtil; if (autoRuntimeDialect) { sqlUtil = getSqlUtil(invocation); } else { if (autoDialect) { initSqlUtil(invocation); } sqlUtil = this.sqlUtil; } return sqlUtil.processPage(invocation); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void setProperties(Properties properties) { //缓存 count ms msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties); String dialectClass = properties.getProperty("dialect"); if (StringUtil.isEmpty(dialectClass)) { dialectClass = default_dialect_class; } try { Class<?> aClass = Class.forName(dialectClass); dialect = (Dialect) aClass.newInstance(); } catch (Exception e) { throw new PageException(e); } dialect.setProperties(properties); String countSuffix = properties.getProperty("countSuffix"); if (StringUtil.isNotEmpty(countSuffix)) { this.countSuffix = countSuffix; } }
#vulnerable code @Override public void setProperties(Properties properties) { //缓存 count ms msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties); String dialectClass = properties.getProperty("dialect"); if (StringUtil.isEmpty(dialectClass)) { dialectClass = default_dialect_class; } try { Class<?> aClass = Class.forName(dialectClass); dialect = (Dialect) aClass.newInstance(); } catch (Exception e) { throw new PageException(e); } dialect.setProperties(properties); String countSuffix = properties.getProperty("countSuffix"); if (StringUtil.isNotEmpty(countSuffix)) { this.countSuffix = countSuffix; } try { //反射获取 BoundSql 中的 additionalParameters 属性 additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters"); additionalParametersField.setAccessible(true); } catch (NoSuchFieldException e) { throw new PageException(e); } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getUrl(DataSource dataSource){ Connection conn = null; try { conn = dataSource.getConnection(); return conn.getMetaData().getURL(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if(conn != null){ try { if(closeConn){ conn.close(); } } catch (SQLException e) { //ignore } } } }
#vulnerable code public String getUrl(DataSource dataSource){ Connection conn = null; try { conn = dataSource.getConnection(); return conn.getMetaData().getURL(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if(conn != null){ try { if(sqlUtil.isCloseConn()){ conn.close(); } } catch (SQLException e) { //ignore } } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void verifyArchivedNotContainingItself(WorkflowRun run) throws IOException { assertTrue("Build should have artifacts", run.getHasArtifacts()); Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0); VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath); try (ZipInputStream zip = new ZipInputStream(file.open())) { for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { assertNotEquals("The zip output file shouldn't contain itself", entry.getName(), artifact.getFileName()); } } }
#vulnerable code private void verifyArchivedNotContainingItself(WorkflowRun run) throws IOException { assertTrue("Build should have artifacts", run.getHasArtifacts()); Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0); VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath); ZipInputStream zip = new ZipInputStream(file.open()); for(ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { assertNotEquals("The zip output file shouldn't contain itself", entry.getName(), artifact.getFileName()); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canArchiveFileWithSameName() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " dir ('src') {\n" + " writeFile file: 'hello.txt', text: 'Hello world'\n" + " writeFile file: 'output.zip', text: 'not really a zip'\n" + " }\n" + " dir ('out') {\n" + " zip zipFile: 'output.zip', dir: '../src', glob: '', archive: true\n" + " }\n" + "}\n", true)); WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); run = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); j.assertLogContains("Writing zip file", run); assertTrue("Build should have artifacts", run.getHasArtifacts()); Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0); assertEquals("output.zip", artifact.getFileName()); VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath); try (ZipInputStream zip = new ZipInputStream(file.open())) { ZipEntry entry = zip.getNextEntry(); while (entry != null && !entry.getName().equals("output.zip")) { System.out.println("zip entry name is: " + entry.getName()); entry = zip.getNextEntry(); } assertNotNull("output.zip should be included in the zip", entry); // we should have the the zip - but double check assertEquals("output.zip", entry.getName()); Scanner scanner = new Scanner(zip); assertTrue(scanner.hasNextLine()); // the file that was not a zip should be included. assertEquals("not really a zip", scanner.nextLine()); } }
#vulnerable code @Test public void canArchiveFileWithSameName() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " dir ('src') {\n" + " writeFile file: 'hello.txt', text: 'Hello world'\n" + " writeFile file: 'output.zip', text: 'not really a zip'\n" + " }\n" + " dir ('out') {\n" + " zip zipFile: 'output.zip', dir: '../src', glob: '', archive: true\n" + " }\n" + "}\n", true)); WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); run = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); j.assertLogContains("Writing zip file", run); assertTrue("Build should have artifacts", run.getHasArtifacts()); Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0); assertEquals("output.zip", artifact.getFileName()); VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath); ZipInputStream zip = new ZipInputStream(file.open()); ZipEntry entry = zip.getNextEntry(); while (entry != null && !entry.getName().equals("output.zip")) { System.out.println("zip entry name is: " + entry.getName()); entry = zip.getNextEntry(); } assertNotNull("output.zip should be included in the zip", entry); // we should have the the zip - but double check assertEquals("output.zip", entry.getName()); Scanner scanner = new Scanner(zip); assertTrue(scanner.hasNextLine()); // the file that was not a zip should be included. assertEquals("not really a zip", scanner.nextLine()); zip.close(); } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void verifyArchivedHello(WorkflowRun run, String basePath) throws IOException { assertTrue("Build should have artifacts", run.getHasArtifacts()); Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0); assertEquals("hello.zip", artifact.getFileName()); VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath); try (ZipInputStream zip = new ZipInputStream(file.open())) { ZipEntry entry = zip.getNextEntry(); while (entry.isDirectory()) { entry = zip.getNextEntry(); } assertNotNull(entry); assertEquals(basePath + "hello.txt", entry.getName()); try (Scanner scanner = new Scanner(zip)) { assertTrue(scanner.hasNextLine()); assertEquals("Hello World!", scanner.nextLine()); assertNull("There should be no more entries", zip.getNextEntry()); } } }
#vulnerable code private void verifyArchivedHello(WorkflowRun run, String basePath) throws IOException { assertTrue("Build should have artifacts", run.getHasArtifacts()); Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0); assertEquals("hello.zip", artifact.getFileName()); VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath); ZipInputStream zip = new ZipInputStream(file.open()); ZipEntry entry = zip.getNextEntry(); while (entry.isDirectory()) { entry = zip.getNextEntry(); } assertNotNull(entry); assertEquals(basePath + "hello.txt", entry.getName()); try(Scanner scanner = new Scanner(zip)){ assertTrue(scanner.hasNextLine()); assertEquals("Hello World!", scanner.nextLine()); assertNull("There should be no more entries", zip.getNextEntry()); zip.close(); } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String slurp(String fileName) throws IOException { URL fileUrl = this.getClass().getResource(fileName); File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8")); BufferedReader in = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); return sb.toString(); }
#vulnerable code private String slurp(String fileName) throws IOException { URL fileUrl = this.getClass().getResource(fileName); File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8")); FileReader in = new FileReader(file); StringBuffer sb = new StringBuffer(); int ch; while ((ch = in.read()) != -1) { sb.append((char) ch); } return sb.toString(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String slurp(String fileName) throws IOException { URL fileUrl = this.getClass().getResource(fileName); File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8")); BufferedReader in = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); return sb.toString(); }
#vulnerable code private String slurp(String fileName) throws IOException { URL fileUrl = this.getClass().getResource(fileName); File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8")); FileReader in = new FileReader(file); StringBuffer sb = new StringBuffer(); int ch; while ((ch = in.read()) != -1) { sb.append((char) ch); } return sb.toString(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code LatticeNode getOOVNode(String text, OOV oov, int length) { LatticeNode node = createNode(); node.setParameter(oov.leftId, oov.rightId, oov.cost); WordInfo info = new WordInfo(text, (short) length, oov.posId, text, text, ""); node.setWordInfo(info); return node; }
#vulnerable code void readCharacterProperty(String charDef) throws IOException { try (InputStream input = (charDef == null) ? openFromJar("char.def") : new FileInputStream(charDef); InputStreamReader isReader = new InputStreamReader(input, StandardCharsets.UTF_8); LineNumberReader reader = new LineNumberReader(isReader)) { while (true) { String line = reader.readLine(); if (line == null) { break; } if (line.matches("\\s*") || line.startsWith("#")) { continue; } String[] cols = line.split("\\s+"); if (cols.length < 2) { throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber()); } if (cols[0].startsWith("0x")) { continue; } CategoryType type = CategoryType.valueOf(cols[0]); if (type == null) { throw new IllegalArgumentException(cols[0] + " is invalid type at line " + reader.getLineNumber()); } if (categories.containsKey(type)) { throw new IllegalArgumentException( cols[0] + " is already defined at line " + reader.getLineNumber()); } CategoryInfo info = new CategoryInfo(); info.type = type; info.isInvoke = (!cols[1].equals("0")); info.isGroup = (!cols[2].equals("0")); info.length = Integer.parseInt(cols[3]); categories.put(type, info); } } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code DictionaryBuilder() { buffer = ByteBuffer.allocate(BUFFER_SIZE); buffer.order(ByteOrder.LITTLE_ENDIAN); }
#vulnerable code void buildLexicon(String filename, FileInputStream lexiconInput) throws IOException { int lineno = -1; try (InputStreamReader isr = new InputStreamReader(lexiconInput); LineNumberReader reader = new LineNumberReader(isr)) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { lineno = reader.getLineNumber(); WordEntry entry = parseLine(line); if (entry.headword != null) { addToTrie(entry.headword, wordInfos.size()); } params.add(entry.parameters); wordInfos.add(entry.wordInfo); } } catch (Exception e) { if (lineno > 0) { System.err.println("Error: " + e.getMessage() + " at line " + lineno + " in " + filename); } throw e; } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code LatticeNode getOOVNode(String text, OOV oov, int length) { LatticeNode node = createNode(); node.setParameter(oov.leftId, oov.rightId, oov.cost); WordInfo info = new WordInfo(text, (short) length, oov.posId, text, text, ""); node.setWordInfo(info); return node; }
#vulnerable code void readOOV(String unkDef, Grammar grammar) throws IOException { try (InputStream input = (unkDef == null) ? openFromJar("unk.def") : new FileInputStream(unkDef); InputStreamReader isReader = new InputStreamReader(input, StandardCharsets.UTF_8); LineNumberReader reader = new LineNumberReader(isReader)) { while (true) { String line = reader.readLine(); if (line == null) { break; } String[] cols = line.split(","); if (cols.length < 10) { throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber()); } CategoryType type = CategoryType.valueOf(cols[0]); if (type == null) { throw new IllegalArgumentException(cols[0] + " is invalid type at line " + reader.getLineNumber()); } if (!categories.containsKey(type)) { throw new IllegalArgumentException(cols[0] + " is undefined at line " + reader.getLineNumber()); } OOV oov = new OOV(); oov.leftId = Short.parseShort(cols[1]); oov.rightId = Short.parseShort(cols[2]); oov.cost = Short.parseShort(cols[3]); List<String> pos = Arrays.asList(cols[4], cols[5], cols[6], cols[7], cols[8], cols[9]); oov.posId = grammar.getPartOfSpeechId(pos); if (!oovList.containsKey(type)) { oovList.put(type, new ArrayList<OOV>()); } oovList.get(type).add(oov); } } } #location 9 #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 IOException { try (FileInputStream lexiconInput = new FileInputStream(args[0]); FileInputStream matrixInput = new FileInputStream(args[1]); FileOutputStream output = new FileOutputStream(args[2])) { DictionaryBuilder builder = new DictionaryBuilder(); builder.build(lexiconInput, matrixInput, output); } }
#vulnerable code public static void main(String[] args) throws IOException { FileInputStream lexiconInput = new FileInputStream(args[0]); FileInputStream matrixInput = new FileInputStream(args[1]); FileOutputStream output = new FileOutputStream(args[2]); DictionaryBuilder builder = new DictionaryBuilder(); builder.build(lexiconInput, matrixInput, output); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void handleRead() throws IOException { if( !socketBuffer.hasRemaining() ) { socketBuffer.rewind(); socketBuffer.limit( socketBuffer.capacity() ); if( sockchannel.read( socketBuffer ) == -1 ) { if( draft == null ) { closeConnection( CloseFrame.ABNROMAL_CLOSE, true ); } else if( draft.getCloseHandshakeType() == CloseHandshakeType.NONE ) { closeConnection( CloseFrame.NORMAL, true ); } else if( draft.getCloseHandshakeType() == CloseHandshakeType.ONEWAY ) { if( role == Role.SERVER ) closeConnection( CloseFrame.ABNROMAL_CLOSE, true ); else closeConnection( CloseFrame.NORMAL, true ); } else { closeConnection( CloseFrame.ABNROMAL_CLOSE, true ); } } socketBuffer.flip(); } if( socketBuffer.hasRemaining() ) { if( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" ); if( !handshakeComplete ) { if( draft == null ) { HandshakeState isflashedgecase = isFlashEdgeCase( socketBuffer ); if( isflashedgecase == HandshakeState.MATCHED ) { channelWriteDirect( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( wsl.getFlashPolicy( this ) ) ) ); closeDirect( CloseFrame.FLASHPOLICY, "" ); return; } else if( isflashedgecase == HandshakeState.MATCHING ) { return; } } HandshakeState handshakestate = null; socketBuffer.mark(); try { if( role == Role.SERVER ) { if( draft == null ) { for( Draft d : known_drafts ) { try { d.setParseMode( role ); socketBuffer.reset(); Handshakedata tmphandshake = d.translateHandshake( socketBuffer ); if( tmphandshake instanceof ClientHandshake == false ) { closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return; } ClientHandshake handshake = (ClientHandshake) tmphandshake; handshakestate = d.acceptHandshakeAsServer( handshake ); if( handshakestate == HandshakeState.MATCHED ) { ServerHandshakeBuilder response; try { response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake ); } catch ( InvalidDataException e ) { closeConnection( e.getCloseCode(), e.getMessage(), false ); return; } writeDirect( d.createHandshake( d.postProcessHandshakeResponseAsServer( handshake, response ), role ) ); draft = d; open( handshake ); handleRead(); return; } else if( handshakestate == HandshakeState.MATCHING ) { if( draft != null ) { throw new InvalidHandshakeException( "multible drafts matching" ); } draft = d; } } catch ( InvalidHandshakeException e ) { // go on with an other draft } catch ( IncompleteHandshakeException e ) { if( socketBuffer.limit() == socketBuffer.capacity() ) { close( CloseFrame.TOOBIG, "handshake is to big" ); } // read more bytes for the handshake socketBuffer.position( socketBuffer.limit() ); socketBuffer.limit( socketBuffer.capacity() ); return; } } if( draft == null ) { close( CloseFrame.PROTOCOL_ERROR, "no draft matches" ); } return; } else { // special case for multiple step handshakes Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( tmphandshake instanceof ClientHandshake == false ) { closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return; } ClientHandshake handshake = (ClientHandshake) tmphandshake; handshakestate = draft.acceptHandshakeAsServer( handshake ); if( handshakestate == HandshakeState.MATCHED ) { open( handshake ); handleRead(); } else if( handshakestate != HandshakeState.MATCHING ) { close( CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match" ); } return; } } else if( role == Role.CLIENT ) { draft.setParseMode( role ); Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( tmphandshake instanceof ServerHandshake == false ) { closeConnection( CloseFrame.PROTOCOL_ERROR, "Wwrong http function", false ); return; } ServerHandshake handshake = (ServerHandshake) tmphandshake; handshakestate = draft.acceptHandshakeAsClient( handshakerequest, handshake ); if( handshakestate == HandshakeState.MATCHED ) { try { wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake ); } catch ( InvalidDataException e ) { closeConnection( e.getCloseCode(), e.getMessage(), false ); return; } open( handshake ); handleRead(); } else if( handshakestate == HandshakeState.MATCHING ) { return; } else { close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" ); } } } catch ( InvalidHandshakeException e ) { close( e ); } } else { // Receiving frames List<Framedata> frames; try { frames = draft.translateFrame( socketBuffer ); for( Framedata f : frames ) { if( DEBUG ) System.out.println( "matched frame: " + f ); Opcode curop = f.getOpcode(); if( curop == Opcode.CLOSING ) { int code = CloseFrame.NOCODE; String reason = ""; if( f instanceof CloseFrame ) { CloseFrame cf = (CloseFrame) f; code = cf.getCloseCode(); reason = cf.getMessage(); } if( closeHandshakeSent ) { // complete the close handshake by disconnecting closeConnection( code, reason, true ); } else { // echo close handshake if( draft.getCloseHandshakeType() == CloseHandshakeType.TWOWAY ) close( code, reason ); closeConnection( code, reason, false ); } continue; } else if( curop == Opcode.PING ) { wsl.onWebsocketPing( this, f ); continue; } else if( curop == Opcode.PONG ) { wsl.onWebsocketPong( this, f ); continue; } else { // process non control frames if( currentframe == null ) { if( f.getOpcode() == Opcode.CONTINIOUS ) { throw new InvalidFrameException( "unexpected continious frame" ); } else if( f.isFin() ) { // receive normal onframe message deliverMessage( f ); } else { // remember the frame whose payload is about to be continued currentframe = f; } } else if( f.getOpcode() == Opcode.CONTINIOUS ) { currentframe.append( f ); if( f.isFin() ) { deliverMessage( currentframe ); currentframe = null; } } else { throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "non control or continious frame expected" ); } } } } catch ( InvalidDataException e1 ) { wsl.onWebsocketError( this, e1 ); close( e1 ); return; } } } }
#vulnerable code long bufferedDataAmount() { return bufferQueueTotalAmount; } #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 stop() throws IOException { for( WebSocket ws : connections ) { ws.close( CloseFrame.NORMAL ); } thread.interrupt(); this.server.close(); }
#vulnerable code public void stop() throws IOException { synchronized ( connections ) { for( WebSocket ws : connections ) { ws.close( CloseFrame.NORMAL ); } } thread.interrupt(); this.server.close(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } catch ( Throwable e ) { System.out.println( e ); e.printStackTrace(); } } } #location 52 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close() { if( thread != null ) { conn.close( CloseFrame.NORMAL ); /*closelock.lock(); try { if( selector != null ) selector.wakeup(); } finally { closelock.unlock(); }*/ } }
#vulnerable code public void close() { if( thread != null ) { thread.interrupt(); closelock.lock(); try { if( selector != null ) selector.wakeup(); } finally { closelock.unlock(); } } } #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 run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; thread = null; }
#vulnerable code public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); thread = null; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel selector.wakeup(); try { if( removeConnection( conn ) ) { onClose( conn, code, reason, remote ); } } finally { try { releaseBuffers( conn ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } }
#vulnerable code @Override public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel selector.wakeup(); try { synchronized ( connections ) { if( this.connections.remove( conn ) ) { onClose( conn, code, reason, remote ); } } } finally { try { releaseBuffers( conn ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } catch ( Throwable e ) { System.out.println( e ); e.printStackTrace(); } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close() { if( thread != null ) { conn.close( CloseFrame.NORMAL ); /*closelock.lock(); try { if( selector != null ) selector.wakeup(); } finally { closelock.unlock(); }*/ } }
#vulnerable code public void close() { if( thread != null ) { thread.interrupt(); closelock.lock(); try { if( selector != null ) selector.wakeup(); } finally { closelock.unlock(); } } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION