output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#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;
}
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);
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());
}
}
} | #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 (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);
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: " + state);
}
}
}
#location 134
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String createLocalSocketAddress() throws IOException {
String name;
if (OsUtils.isUNIX()) {
File socket = File.createTempFile("mina", "apr");
socket.delete();
name = socket.getAbsolutePath();
} else {
File socket = File.createTempFile("mina", "apr");
socket.delete();
name = "\\\\.\\pipe\\" + socket.getName();
}
return name;
} | #vulnerable code
static String createLocalSocketAddress() throws IOException {
String name;
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("windows") < 0) {
File socket = File.createTempFile("mina", "apr");
socket.delete();
name = socket.getAbsolutePath();
} else {
File socket = File.createTempFile("mina", "apr");
socket.delete();
name = "\\\\.\\pipe\\" + socket.getName();
}
return name;
}
#location 3
#vulnerability type NULL_DEREFERENCE | 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
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 82
#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
static void secureLocalSocket(String authSocket, long handle) throws IOException {
if (OsUtils.isUNIX()) {
File file = new File(authSocket);
if (!file.setReadable(false, false) || !file.setReadable(true, true)
|| !file.setExecutable(false, false) || !file.setExecutable(true, true)) {
throw new IOException("Unable to secure local socket");
}
} else {
// should be ok on windows
}
} | #vulnerable code
static void secureLocalSocket(String authSocket, long handle) throws IOException {
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("windows") < 0) {
File file = new File(authSocket);
if (!file.setReadable(false, false) || !file.setReadable(true, true)
|| !file.setExecutable(false, false) || !file.setExecutable(true, true)) {
throw new IOException("Unable to secure local socket");
}
} else {
// should be ok on windows
}
}
#location 2
#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 27
#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 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 handleEof() throws IOException {
log.debug("Received SSH_MSG_CHANNEL_EOF on channel {}", id);
eof = true;
notifyStateChanged();
} | #vulnerable code
public void handleEof() throws IOException {
log.debug("Received SSH_MSG_CHANNEL_EOF on channel {}", id);
synchronized (lock) {
eof = true;
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
private void readFile(File path) throws IOException {
if (log.isDebugEnabled()) {
log.debug("Reading file {}", path);
}
StringBuffer buf = new StringBuffer();
buf.append("C");
buf.append("0644"); // what about perms
buf.append(" ");
buf.append(path.length()); // length
buf.append(" ");
buf.append(path.getName());
buf.append("\n");
out.write(buf.toString().getBytes());
out.flush();
readAck();
InputStream is = new FileInputStream(path);
try {
byte[] buffer = new byte[8192];
for (;;) {
int len = is.read(buffer, 0, buffer.length);
if (len == -1) {
break;
}
out.write(buffer, 0, len);
}
} finally {
is.close();
}
ack();
readAck();
} | #vulnerable code
private void readFile(File path) throws IOException {
if (log.isDebugEnabled()) {
log.debug("Reading file {}", path);
}
StringBuffer buf = new StringBuffer();
buf.append("C");
buf.append("0644"); // what about perms
buf.append(" ");
buf.append(path.length()); // length
buf.append(" ");
buf.append(path.getName());
buf.append("\n");
out.write(buf.toString().getBytes());
out.flush();
readAck();
InputStream is = new FileInputStream(path);
byte[] buffer = new byte[8192];
for (;;) {
int len = is.read(buffer, 0, buffer.length);
if (len == -1) {
break;
}
out.write(buffer, 0, len);
}
is.close();
ack();
readAck();
}
#location 4
#vulnerability type RESOURCE_LEAK | 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
protected void doWriteKeyPair(KeyPair kp, OutputStream os) throws Exception {
PEMWriter w = new PEMWriter(new OutputStreamWriter(os));
try {
w.writeObject(kp);
} finally {
w.close();
}
} | #vulnerable code
protected void doWriteKeyPair(KeyPair kp, OutputStream os) throws Exception {
PEMWriter w = new PEMWriter(new OutputStreamWriter(os));
w.writeObject(kp);
}
#location 3
#vulnerability type RESOURCE_LEAK | 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 close() {
if (!closed) {
synchronized (lock) {
if (!closed && !closing) {
try {
closing = true;
log.info("Closing session");
Channel[] channelToClose = channels.values().toArray(new Channel[0]);
for (Channel channel : channelToClose) {
log.debug("Closing channel {}", channel.getId());
IoUtils.closeQuietly(channel);
}
log.debug("Closing IoSession");
CloseFuture future = ioSession.close(true);
future.addListener(new IoFutureListener() {
public void operationComplete(IoFuture future) {
synchronized (lock) {
log.debug("IoSession closed");
closed = true;
lock.notifyAll();
}
}
});
} catch (Throwable t) {
log.warn("Error closing session", t);
}
}
}
}
} | #vulnerable code
public void close() {
if (!closed) {
synchronized (lock) {
if (!closed) {
try {
log.info("Closing session");
Channel[] channelToClose = channels.values().toArray(new Channel[0]);
for (Channel channel : channelToClose) {
log.debug("Closing channel {}", channel.getId());
IoUtils.closeQuietly(channel);
}
log.debug("Closing IoSession");
CloseFuture future = ioSession.close();
log.debug("Waiting for IoSession to be closed");
future.join();
log.debug("IoSession closed");
} catch (Throwable t) {
log.warn("Error closing session", t);
}
closed = true;
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
@Test
public void testAgentForwarding() throws Exception {
int port1 = getFreePort();
int port2 = getFreePort();
TestEchoShellFactory shellFactory = new TestEchoShellFactory();
ProxyAgentFactory agentFactory = new ProxyAgentFactory();
LocalAgentFactory localAgentFactory = new LocalAgentFactory();
KeyPair pair = createTestKeyPairProvider("dsaprivkey.pem").loadKey(KeyPairProvider.SSH_DSS);
localAgentFactory.getAgent().addIdentity(pair, "smx");
SshServer sshd1 = SshServer.setUpDefaultServer();
sshd1.setPort(port1);
sshd1.setKeyPairProvider(Utils.createTestHostKeyProvider());
sshd1.setShellFactory(shellFactory);
sshd1.setPasswordAuthenticator(new BogusPasswordAuthenticator());
sshd1.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
sshd1.setAgentFactory(agentFactory);
sshd1.start();
SshServer sshd2 = SshServer.setUpDefaultServer();
sshd2.setPort(port2);
sshd2.setKeyPairProvider(Utils.createTestHostKeyProvider());
sshd2.setShellFactory(new TestEchoShellFactory());
sshd2.setPasswordAuthenticator(new BogusPasswordAuthenticator());
sshd2.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
sshd2.setAgentFactory(new ProxyAgentFactory());
sshd2.start();
SshClient client1 = SshClient.setUpDefaultClient();
client1.setAgentFactory(localAgentFactory);
client1.start();
ClientSession session1 = client1.connect("localhost", port1).await().getSession();
assertTrue(session1.authAgent("smx").await().isSuccess());
ChannelShell channel1 = session1.createShellChannel();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
channel1.setOut(out);
channel1.setErr(err);
channel1.setAgentForwarding(true);
channel1.open().await();
OutputStream pipedIn = channel1.getInvertedIn();
synchronized (shellFactory.shell) {
System.out.println("Possibly waiting for remote shell to start");
if (!shellFactory.shell.started) {
shellFactory.shell.wait();
}
}
SshClient client2 = SshClient.setUpDefaultClient();
client2.setAgentFactory(agentFactory);
client2.getProperties().putAll(shellFactory.shell.getEnvironment().getEnv());
client2.start();
ClientSession session2 = client2.connect("localhost", port2).await().getSession();
assertTrue(session2.authAgent("smx").await().isSuccess());
ChannelShell channel2 = session2.createShellChannel();
channel2.setIn(shellFactory.shell.getIn());
channel2.setOut(shellFactory.shell.getOut());
channel2.setErr(shellFactory.shell.getErr());
channel2.setAgentForwarding(true);
channel2.open().await();
pipedIn.write("foo\n".getBytes());
pipedIn.flush();
Thread.sleep(1000);
System.out.println(out.toString());
System.err.println(err.toString());
} | #vulnerable code
@Test
public void testAgentForwarding() throws Exception {
int port1 = getFreePort();
int port2 = getFreePort();
TestEchoShellFactory shellFactory = new TestEchoShellFactory();
ProxyAgentFactory agentFactory = new ProxyAgentFactory();
LocalAgentFactory localAgentFactory = new LocalAgentFactory();
KeyPair pair = createTestKeyPairProvider("dsaprivkey.pem").loadKey(KeyPairProvider.SSH_DSS);
localAgentFactory.getAgent().addIdentity(pair, "smx");
SshServer sshd1 = SshServer.setUpDefaultServer();
sshd1.setPort(port1);
sshd1.setKeyPairProvider(Utils.createTestHostKeyProvider());
sshd1.setShellFactory(shellFactory);
sshd1.setPasswordAuthenticator(new BogusPasswordAuthenticator());
sshd1.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
sshd1.setAgentFactory(agentFactory);
sshd1.start();
SshServer sshd2 = SshServer.setUpDefaultServer();
sshd2.setPort(port2);
sshd2.setKeyPairProvider(Utils.createTestHostKeyProvider());
sshd2.setShellFactory(new TestEchoShellFactory());
sshd2.setPasswordAuthenticator(new BogusPasswordAuthenticator());
sshd2.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
sshd2.setAgentFactory(new ProxyAgentFactory());
sshd2.start();
SshClient client1 = SshClient.setUpDefaultClient();
client1.setAgentFactory(localAgentFactory);
client1.start();
ClientSession session1 = client1.connect("localhost", port1).await().getSession();
assertTrue(session1.authAgent("smx").await().isSuccess());
ChannelShell channel1 = session1.createShellChannel();
ByteArrayOutputStream sent = new ByteArrayOutputStream();
PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
channel1.setIn(new PipedInputStream(pipedIn));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
channel1.setOut(out);
channel1.setErr(err);
channel1.setAgentForwarding(true);
channel1.open().await();
synchronized (shellFactory.shell) {
System.out.println("Possibly waiting for remote shell to start");
if (!shellFactory.shell.started) {
shellFactory.shell.wait();
}
}
SshClient client2 = SshClient.setUpDefaultClient();
client2.setAgentFactory(agentFactory);
client2.getProperties().putAll(shellFactory.shell.getEnvironment().getEnv());
client2.start();
ClientSession session2 = client2.connect("localhost", port2).await().getSession();
assertTrue(session2.authAgent("smx").await().isSuccess());
ChannelShell channel2 = session2.createShellChannel();
channel2.setIn(shellFactory.shell.getIn());
channel2.setOut(shellFactory.shell.getOut());
channel2.setErr(shellFactory.shell.getErr());
channel2.setAgentForwarding(true);
channel2.open().await();
pipedIn.write("foo\n".getBytes());
pipedIn.flush();
Thread.sleep(1000);
System.out.println(out.toString());
System.err.println(err.toString());
}
#location 40
#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
@SuppressWarnings("unchecked")
public <T> T convert(Type type, Object value, T defaultValue, boolean isCustomFirst) throws ConvertException {
if (TypeUtil.isUnknow(type) && null == defaultValue) {
// 对于用户不指定目标类型的情况,返回原值
return (T) value;
}
if (ObjectUtil.isNull(value)) {
return defaultValue;
}
if (TypeUtil.isUnknow(type)) {
type = defaultValue.getClass();
}
if(type instanceof TypeReference) {
type = ((TypeReference<?>)type).getType();
}
// 标准转换器
final Converter<T> converter = getConverter(type, isCustomFirst);
if (null != converter) {
return converter.convert(value, defaultValue);
}
Class<T> rowType = (Class<T>) TypeUtil.getClass(type);
if (null == rowType) {
if (null != defaultValue) {
rowType = (Class<T>) defaultValue.getClass();
} else {
// 无法识别的泛型类型,按照Object处理
return (T) value;
}
}
// 特殊类型转换,包括Collection、Map、强转、Array等
final T result = convertSpecial(type, rowType, value, defaultValue);
if (null != result) {
return result;
}
// 尝试转Bean
if (BeanUtil.isBean(rowType)) {
return new BeanConverter<T>(type).convert(value, defaultValue);
}
// 无法转换
throw new ConvertException("No Converter for type [{}]", rowType.getName());
} | #vulnerable code
@SuppressWarnings("unchecked")
public <T> T convert(Type type, Object value, T defaultValue, boolean isCustomFirst) throws ConvertException {
if (TypeUtil.isUnknow(type) && null == defaultValue) {
// 对于用户不指定目标类型的情况,返回原值
return (T) value;
}
if (ObjectUtil.isNull(value)) {
return defaultValue;
}
if (TypeUtil.isUnknow(type)) {
type = defaultValue.getClass();
}
// 标准转换器
final Converter<T> converter = getConverter(type, isCustomFirst);
if (null != converter) {
return converter.convert(value, defaultValue);
}
Class<T> rowType = (Class<T>) TypeUtil.getClass(type);
if (null == rowType) {
if (null != defaultValue) {
rowType = (Class<T>) defaultValue.getClass();
} else {
// 无法识别的泛型类型,按照Object处理
return (T) value;
}
}
// 特殊类型转换,包括Collection、Map、强转、Array等
final T result = convertSpecial(type, rowType, value, defaultValue);
if (null != result) {
return result;
}
// 尝试转Bean
if (BeanUtil.isBean(rowType)) {
return new BeanConverter<T>(type).convert(value, defaultValue);
}
// 无法转换
throw new ConvertException("No Converter for type [{}]", rowType.getName());
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public byte[] decrypt(byte[] data, KeyType keyType) {
final Key key = getKeyByType(keyType);
lock.lock();
try {
cipher.init(Cipher.DECRYPT_MODE, key);
if(this.decryptBlockSize < 0){
// 在引入BC库情况下,自动获取块大小
final int blockSize = this.cipher.getBlockSize();
if(blockSize > 0){
this.decryptBlockSize = blockSize;
}
}
return doFinal(data, this.decryptBlockSize < 0 ? data.length : this.decryptBlockSize);
} catch (Exception e) {
throw new CryptoException(e);
} finally {
lock.unlock();
}
} | #vulnerable code
@Override
public byte[] decrypt(byte[] data, KeyType keyType) {
final Key key = getKeyByType(keyType);
final int maxBlockSize = this.decryptBlockSize < 0 ? data.length : this.decryptBlockSize;
lock.lock();
try {
cipher.init(Cipher.DECRYPT_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
@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
@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 6
#vulnerability type NULL_DEREFERENCE | 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 11
#vulnerability type NULL_DEREFERENCE | 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 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
public static void readBySax(String path, int sheetIndex, RowHandler rowHandler) {
readBySax(FileUtil.file(path), sheetIndex, rowHandler);
} | #vulnerable code
public static void readBySax(String path, int sheetIndex, RowHandler rowHandler) {
BufferedInputStream in = null;
try {
in = FileUtil.getInputStream(path);
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 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 6
#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 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
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 33
#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
public SM2 setMode(SM2Engine.Mode mode) {
this.mode = mode;
this.engine = null;
return this;
} | #vulnerable code
public SM2 setMode(SM2Engine.Mode mode) {
this.mode = mode;
if (null != this.engine) {
this.engine = null;
}
return this;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | 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
@Deprecated
public CellStyle createStyleForCell(int x, int y) {
return createCellStyle(x, y);
} | #vulnerable code
@Deprecated
public CellStyle createStyleForCell(int x, int y) {
final Cell cell = getOrCreateCell(x, y);
final CellStyle cellStyle = this.workbook.createCellStyle();
cell.setCellStyle(cellStyle);
return cellStyle;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void 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 byte[] decryptFromBcd(String data, KeyType keyType, Charset charset) {
Assert.notNull(data, "Bcd string must be not null!");
final byte[] dataBytes = BCD.ascToBcd(StrUtil.bytes(data, charset));
return decrypt(dataBytes, keyType);
} | #vulnerable code
public byte[] decryptFromBcd(String data, KeyType keyType, Charset charset) {
final byte[] dataBytes = BCD.ascToBcd(StrUtil.bytes(data, charset));
return decrypt(dataBytes, keyType);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private List<GalenSuite> read(InputStream inputStream, String filePath) throws IOException {
try {
GalenSuiteLineProcessor lineProcessor = new GalenSuiteLineProcessor(getContextPath(filePath));
lineProcessor.readLines(inputStream);
return lineProcessor.buildSuites();
}
catch (SyntaxException e) {
int lineNumber = -1;
if (e.getLine() != null) {
lineNumber = e.getLine().getNumber();
}
throw new FileSyntaxException(e, filePath, lineNumber);
}
} | #vulnerable code
private List<GalenSuite> read(InputStream inputStream, String filePath) throws IOException {
try {
GalenSuiteLineProcessor lineProcessor = new GalenSuiteLineProcessor();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = bufferedReader.readLine();
int lineNumber = 0;
while(line != null){
lineNumber++;
lineProcessor.processLine(line, lineNumber);
line = bufferedReader.readLine();
}
return lineProcessor.buildSuites();
}
catch (SyntaxException e) {
int lineNumber = -1;
if (e.getLine() != null) {
lineNumber = e.getLine().getNumber();
}
throw new FileSyntaxException(e, filePath, lineNumber);
}
}
#location 16
#vulnerability type RESOURCE_LEAK | 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
@Test
public void sendTest() {
//Make sure all methods call each other appropiatly
final String string = "AString";
final User user = new User(bot, "AUser");
final Channel chan = new Channel(bot, "AChannel");
final BaseEvent event = new Action.Event(bot, user, chan, string);
bot.sendAction(event, string);
signal.compare("AUser", string);
bot.sendAction(user, string);
signal.compare("AUser", string);
bot.sendAction(chan, string);
signal.compare("AChannel", string);
bot.sendCTCPCommand(event, string);
signal.compare("AUser", string);
bot.sendCTCPCommand(user, string);
signal.compare("AUser", string);
bot.sendCTCPResponse(event, string);
signal.compare("AUser", string);
bot.sendCTCPResponse(user, string);
signal.compare("AUser", string);
bot.sendInvite(event, string);
signal.compare("AUser", string);
bot.sendInvite(event, chan);
signal.compare("AUser", "AChannel");
bot.sendInvite(event, chan);
signal.compare("AUser", "AChannel");
bot.sendInvite(user, chan);
signal.compare("AUser", "AChannel");
bot.sendInvite(chan, chan);
signal.compare("AChannel", "AChannel");
bot.sendMessage(event, string);
signal.compare("AUser", string);
bot.sendMessage(user, string);
signal.compare("AUser", string);
bot.sendMessage(chan, string);
signal.compare("AChannel", string);
bot.sendNotice(event, string);
signal.compare("AUser", string);
bot.sendNotice(user, string);
signal.compare("AUser", string);
bot.sendNotice(chan, string);
signal.compare("AChannel", string);
} | #vulnerable code
@Test
public void sendTest() {
//Setup
PircBotX bot = new PircBotX() {
@Override
public void sendAction(String target, String action) {
signal.set(target, action);
}
@Override
public void sendCTCPCommand(String target, String command) {
signal.set(target, command);
}
@Override
public void sendCTCPResponse(String target, String message) {
signal.set(target, message);
}
@Override
public void sendInvite(String nick, String channel) {
signal.set(nick, channel);
}
@Override
public void sendMessage(String target, String message) {
signal.set(target, message);
}
@Override
public void sendNotice(String target, String notice) {
signal.set(target, notice);
}
};
//Make sure all methods call each other appropiatly
final String string = "AString";
final User user = new User(bot, "AUser");
final Channel chan = new Channel(bot, "AChannel");
final BaseEvent event = new Action.Event(bot, user, chan, string);
bot.sendAction(event, string);
signal.compare("AUser", string);
bot.sendAction(user, string);
signal.compare("AUser", string);
bot.sendAction(chan, string);
signal.compare("AChannel", string);
bot.sendCTCPCommand(event, string);
signal.compare("AUser", string);
bot.sendCTCPCommand(user, string);
signal.compare("AUser", string);
bot.sendCTCPResponse(event, string);
signal.compare("AUser", string);
bot.sendCTCPResponse(user, string);
signal.compare("AUser", string);
bot.sendInvite(event, string);
signal.compare("AUser", string);
bot.sendInvite(event, chan);
signal.compare("AUser", "AChannel");
bot.sendInvite(event, chan);
signal.compare("AUser", "AChannel");
bot.sendInvite(user, chan);
signal.compare("AUser", "AChannel");
bot.sendInvite(chan, chan);
signal.compare("AChannel", "AChannel");
bot.sendMessage(event, string);
signal.compare("AUser", string);
bot.sendMessage(user, string);
signal.compare("AUser", string);
bot.sendMessage(chan, string);
signal.compare("AChannel", string);
bot.sendNotice(event, string);
signal.compare("AUser", string);
bot.sendNotice(user, string);
signal.compare("AUser", string);
bot.sendNotice(chan, string);
signal.compare("AChannel", string);
}
#location 43
#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 41
#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 149
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//payPackage 的商品信息,总价可以通过前端传入
Unifiedorder unifiedorder = new Unifiedorder();
unifiedorder.setAppid(appid);
unifiedorder.setMch_id(mch_id);
unifiedorder.setNonce_str(UUID.randomUUID().toString().replace("-", ""));
unifiedorder.setBody("商品信息");
unifiedorder.setOut_trade_no("123456");
unifiedorder.setTotal_fee("1");//单位分
unifiedorder.setSpbill_create_ip(request.getRemoteAddr());//IP
unifiedorder.setNotify_url("http://mydomain.com/test/notify");
unifiedorder.setTrade_type("JSAPI");//JSAPI,NATIVE,APP,MWEB
UnifiedorderResult unifiedorderResult = PayMchAPI.payUnifiedorder(unifiedorder,key);
//@since 2.8.5 API返回数据签名验证
if(unifiedorderResult.getSign_status() !=null && unifiedorderResult.getSign_status()){
String json = PayUtil.generateMchPayJsRequestJson(unifiedorderResult.getPrepay_id(), appid, key);
//将json 传到jsp 页面
request.setAttribute("json", json);
//示例jsp
request.getRequestDispatcher("pay_example.jsp").forward(request,response);
}
} | #vulnerable code
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//payPackage 的商品信息,总价可以通过前端传入
Unifiedorder unifiedorder = new Unifiedorder();
unifiedorder.setAppid(appid);
unifiedorder.setMch_id(mch_id);
unifiedorder.setNonce_str(UUID.randomUUID().toString().replace("-", ""));
unifiedorder.setBody("商品信息");
unifiedorder.setOut_trade_no("123456");
unifiedorder.setTotal_fee("1");//单位分
unifiedorder.setSpbill_create_ip(request.getRemoteAddr());//IP
unifiedorder.setNotify_url("http://mydomain.com/test/notify");
unifiedorder.setTrade_type("JSAPI");//JSAPI,NATIVE,APP,WAP
UnifiedorderResult unifiedorderResult = PayMchAPI.payUnifiedorder(unifiedorder,key);
//@since 2.8.5 API返回数据签名验证
if(unifiedorderResult.getSign_status() !=null && unifiedorderResult.getSign_status()){
String json = PayUtil.generateMchPayJsRequestJson(unifiedorderResult.getPrepay_id(), appid, key);
//将json 传到jsp 页面
request.setAttribute("json", json);
//示例jsp
request.getRequestDispatcher("pay_example.jsp").forward(request,response);
}
}
#location 21
#vulnerability type NULL_DEREFERENCE | 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
private Designer getDesigner(Object adaptable) {
ResourceResolver resolver = getResourceResolver(adaptable);
if(resolver != null) {
return resolver.adaptTo(Designer.class);
}
return null;
} | #vulnerable code
private Designer getDesigner(Object adaptable) {
return getResourceResolver(adaptable).adaptTo(Designer.class);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public final String get(final String path,
final SlingHttpServletRequest request,
final SlingHttpServletResponse response) {
if (!serveAuthenticatedFromCache && !isAnonymousRequest(request)) {
// For authenticated requests, don't return from cache
return ResourceDataUtil.getIncludeAsString(path, request, response);
}
final long start = System.currentTimeMillis();
CacheEntry cacheEntry = cache.get(path);
final boolean newEntry = cacheEntry == null;
if (newEntry || cacheEntry.isExpired(new Date())) {
// Cache Miss
final String data = ResourceDataUtil.getIncludeAsString(path, request, response);
if (newEntry) {
cacheEntry = new CacheEntry();
}
cacheEntry.setData(data);
cacheEntry.setExpiresIn(ttl);
cacheEntry.incrementMisses();
if (newEntry) {
// Add entry to cache
cache.put(path, cacheEntry);
}
log.info("Served cache MISS for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
} else {
// Cache Hit
final String data = cacheEntry.getData();
cacheEntry.incrementHits();
cache.put(path, cacheEntry);
log.info("Served cache HIT for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
}
} | #vulnerable code
@Override
public final String get(final String path,
final SlingHttpServletRequest request,
final SlingHttpServletResponse response) {
if (!serveAuthenticatedFromCache && !isAnonymousRequest(request)) {
// For authenticated requests, don't return from cache
return ResourceDataUtil.getIncludeAsString(path, request, response);
}
final long start = System.currentTimeMillis();
// Lock the cache because we we increment values within the cache even on valid cache hits
synchronized (this.cache) {
CacheEntry cacheEntry = cache.get(path);
if (cacheEntry == null || cacheEntry.isExpired(new Date())) {
// Cache Miss
if (cacheEntry == null) {
cacheEntry = new CacheEntry();
}
final String data = ResourceDataUtil.getIncludeAsString(path, request, response);
cacheEntry.setData(data);
cacheEntry.setExpiresIn(ttl);
cacheEntry.incrementMisses();
// Add entry to cache
cache.put(path, cacheEntry);
log.info("Served cache MISS for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
} else {
// Cache Hit
final String data = cacheEntry.getData();
cacheEntry.incrementHits();
cache.put(path, cacheEntry);
log.info("Served cache HIT for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
}
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | 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
@Test
public void testStart_WFData() throws Exception {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("process.label", "test");
swr.bindWorkflowProcesses(new WFDataWorkflowProcess(), map);
Map<String, Map<String, Object>> metadata = new HashMap<String, Map<String, Object>>();
swr.start(resourceResolver,
"/content/test",
new String[] {"test"},
metadata);
} | #vulnerable code
@Test
public void testStart_WFData() throws Exception {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("process.label", "test");
swr.bindWorkflowProcesses(new WFDataWorkflowProcess(), map);
Map<String, Map<String, Object>> metadata = new HashMap<String, Map<String, Object>>();
swr.start(null,
"/content/test",
new String[] {"test"},
metadata);
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public final void initialize(Resource resource, final ValueMap params) throws
PersistenceException, RepositoryException {
final ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
log.trace("Entering initialized");
if (properties.get(KEY_INITIALIZED, false)) {
log.warn("Refusing to re-initialize an already initialized Bulk Workflow Manager.");
return;
}
properties.putAll(params);
properties.put(KEY_JOB_NAME, resource.getPath());
// Query for all candidate resources
final ResourceResolver resourceResolver = resource.getResourceResolver();
final Session session = resourceResolver.adaptTo(Session.class);
final QueryManager queryManager = session.getWorkspace().getQueryManager();
final QueryResult queryResult = queryManager.createQuery(properties.get(KEY_QUERY, ""),
Query.JCR_SQL2).execute();
final NodeIterator nodes = queryResult.getNodes();
long size = nodes.getSize();
if (size < 0) {
log.debug("Using provided estimate total size [ {} ] as actual size [ {} ] could not be retrieved.",
properties.get(KEY_ESTIMATED_TOTAL, DEFAULT_ESTIMATED_TOTAL), size);
size = properties.get(KEY_ESTIMATED_TOTAL, DEFAULT_ESTIMATED_TOTAL);
}
final int batchSize = properties.get(KEY_BATCH_SIZE, DEFAULT_BATCH_SIZE);
final Bucket bucket = new Bucket(batchSize, size,
resource.getChild(NN_BATCHES).getPath(), "sling:Folder");
final String relPath = params.get(KEY_RELATIVE_PATH, "");
// Create the structure
String currentBatch = null;
int total = 0;
Node previousBatchNode = null, batchItemNode = null;
while (nodes.hasNext()) {
Node payloadNode = nodes.nextNode();
log.debug("nodes has next: {}", nodes.hasNext());
log.trace("Processing search result [ {} ]", payloadNode.getPath());
if(StringUtils.isNotBlank(relPath)) {
if(payloadNode.hasNode(relPath)) {
payloadNode = payloadNode.getNode(relPath);
} else {
log.warn("Could not find node at [ {} ]", payloadNode.getPath() + "/" + relPath);
continue;
}
// No rel path, so use the Query result node as the payload Node
}
total++;
final String batchPath = bucket.getNextPath(resourceResolver);
if (currentBatch == null) {
// Set the currentBatch to the first batch folder
currentBatch = batchPath;
}
final String batchItemPath = batchPath + "/" + total;
batchItemNode = JcrUtil.createPath(batchItemPath, SLING_FOLDER, JcrConstants.NT_UNSTRUCTURED, session,
false);
log.trace("Created batch item path at [ {} ]", batchItemPath);
JcrUtil.setProperty(batchItemNode, KEY_PATH, payloadNode.getPath());
log.trace("Added payload [ {} ] for batch item [ {} ]", payloadNode.getPath(), batchItemNode.getPath());
if (total % batchSize == 0) {
previousBatchNode = batchItemNode.getParent();
} else if ((total % batchSize == 1) && previousBatchNode != null) {
// Set the "next batch" property, so we know what the next batch to process is when
// the current batch is complete
JcrUtil.setProperty(previousBatchNode, KEY_NEXT_BATCH, batchItemNode.getParent().getPath());
}
if (total % SAVE_THRESHOLD == 0) {
session.save();
}
} // while
if(total > 0) {
// Set last batch's "next batch" property to complete so we know we're done
JcrUtil.setProperty(batchItemNode.getParent(), KEY_NEXT_BATCH, STATE_COMPLETE);
if (total % SAVE_THRESHOLD != 0) {
session.save();
}
properties.put(KEY_CURRENT_BATCH, currentBatch);
properties.put(KEY_TOTAL, total);
properties.put(KEY_INITIALIZED, true);
properties.put(KEY_STATE, STATE_NOT_STARTED);
resource.getResourceResolver().commit();
log.info("Completed initialization of Bulk Workflow Manager");
} else {
throw new IllegalArgumentException("Query returned zero results.");
}
} | #vulnerable code
@Override
public final void initialize(Resource resource, final ValueMap params) throws
PersistenceException, RepositoryException {
final ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
if (properties.get(KEY_INITIALIZED, false)) {
log.warn("Refusing to re-initialize an already initialized Bulk Workflow Manager.");
return;
}
properties.putAll(params);
properties.put(KEY_JOB_NAME, resource.getPath());
// Query for all candidate resources
final ResourceResolver resourceResolver = resource.getResourceResolver();
final Session session = resourceResolver.adaptTo(Session.class);
final QueryManager queryManager = session.getWorkspace().getQueryManager();
final QueryResult queryResult = queryManager.createQuery(properties.get(KEY_QUERY, ""),
Query.JCR_SQL2).execute();
final NodeIterator nodes = queryResult.getNodes();
long size = queryResult.getNodes().getSize();
if (size < 0) {
log.debug("Using provided estimate total size [ {} ] as actual size [ {} ] could not be retrieved.",
properties.get(KEY_ESTIMATED_TOTAL, DEFAULT_ESTIMATED_TOTAL), size);
size = properties.get(KEY_ESTIMATED_TOTAL, DEFAULT_ESTIMATED_TOTAL);
}
final int batchSize = properties.get(KEY_BATCH_SIZE, DEFAULT_BATCH_SIZE);
final Bucket bucket = new Bucket(batchSize, size,
resource.getChild(NN_BATCHES).getPath(), "sling:Folder");
// Create the structure
String currentBatch = null;
int total = 0;
Node previousBatchNode = null, node = null;
while (nodes.hasNext()) {
final String batchPath = bucket.getNextPath(resourceResolver);
if (currentBatch == null) {
// Set the currentBatch to the first batch folder
currentBatch = batchPath;
}
final String batchItemPath = batchPath + "/" + total++;
node = JcrUtil.createPath(batchItemPath, SLING_FOLDER, JcrConstants.NT_UNSTRUCTURED, session, false);
JcrUtil.setProperty(node, KEY_PATH, nodes.nextNode().getPath());
if (total % batchSize == 0) {
previousBatchNode = node.getParent();
} else if ((total % batchSize == 1) && previousBatchNode != null) {
// Set the "next batch" property, so we know what the next batch to process is when
// the current batch is complete
JcrUtil.setProperty(previousBatchNode, KEY_NEXT_BATCH, node.getParent().getPath());
}
if (total % SAVE_THRESHOLD == 0) {
session.save();
}
}
// Set last batch's "next batch" property to complete so we know we're done
JcrUtil.setProperty(node.getParent(), KEY_NEXT_BATCH, STATE_COMPLETE);
if (total % SAVE_THRESHOLD != 0) {
session.save();
}
properties.put(KEY_CURRENT_BATCH, currentBatch);
properties.put(KEY_TOTAL, total);
properties.put(KEY_INITIALIZED, true);
properties.put(KEY_STATE, STATE_NOT_STARTED);
resource.getResourceResolver().commit();
}
#location 66
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void handleRequest(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws IOException,
RepositoryException, ServletException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// Generate current date and time for filename
DateFormat df = new SimpleDateFormat("yyyyddMM_HHmmss");
Date today = Calendar.getInstance().getTime();
String filename = df.format(today);
response.setHeader("Content-Disposition", "filename=jcr-checksum-"
+ filename + ".json");
String optionsName = request.getParameter(ServletConstants.OPTIONS_NAME);
ChecksumGeneratorOptions options =
ChecksumGeneratorOptionsFactory.getOptions(request, optionsName);
if (log.isDebugEnabled()) {
log.debug(options.toString());
}
Set<String> paths = RequestChecksumGeneratorOptions.getPaths(request);
if (CollectionUtils.isEmpty(paths)) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(
"ERROR: At least one path must be specified");
} catch (IOException ioe) {
throw ioe;
}
} else {
Session session = request.getResourceResolver().adaptTo(Session.class);
JsonWriter jsonWriter = new JsonWriter(response.getWriter());
try {
JSONGenerator.generateJSON(session, paths, options, jsonWriter);
jsonWriter.close();
} catch (RepositoryException e) {
throw new ServletException("Error accessing repository", e);
} catch (IOException e) {
throw new ServletException("Unable to generate json", e);
}
}
} | #vulnerable code
private void handleRequest(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws IOException,
RepositoryException, ServletException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// Generate current date and time for filename
DateFormat df = new SimpleDateFormat("yyyyddMM_HHmmss");
Date today = Calendar.getInstance().getTime();
String filename = df.format(today);
response.setHeader("Content-Disposition", "filename=jcr-checksum-"
+ filename + ".json");
String optionsName = request.getParameter(ServletConstants.OPTIONS_NAME);
ChecksumGeneratorOptions options =
ChecksumGeneratorOptionsFactory.getOptions(request, optionsName);
if (log.isDebugEnabled()) {
log.debug(options.toString());
}
Set<String> paths = RequestChecksumGeneratorOptions.getPaths(request);
if (CollectionUtils.isEmpty(paths)) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(
"ERROR: At least one path must be specified");
} catch (IOException ioe) {
throw ioe;
}
}
Session session = request.getResourceResolver().adaptTo(Session.class);
JsonWriter jsonWriter = new JsonWriter(response.getWriter());
try {
JSONGenerator.generateJSON(session, paths, options, jsonWriter);
} catch (RepositoryException e) {
throw new ServletException("Error accessing repository", e);
} catch (IOException e) {
throw new ServletException("Unable to generate json", e);
}
}
#location 41
#vulnerability type RESOURCE_LEAK | 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
@Activate
protected final void activate(Map<String, Object> config) throws RepositoryException {
if (!capabilityHelper.isOak()) {
log.info("Cowardly refusing to create indexes on non-Oak instance.");
return;
}
final String ensureDefinitionsPath = PropertiesUtil.toString(config.get(PROP_ENSURE_DEFINITIONS_PATH),
DEFAULT_ENSURE_DEFINITIONS_PATH);
final String oakIndexesPath = PropertiesUtil.toString(config.get(PROP_OAK_INDEXES_PATH),
DEFAULT_OAK_INDEXES_PATH);
log.info("Ensuring Oak Indexes [ {} ~> {} ]", ensureDefinitionsPath, oakIndexesPath);
ResourceResolver resourceResolver = null;
try {
if (StringUtils.isBlank(ensureDefinitionsPath)) {
throw new IllegalArgumentException("OSGi Configuration Property `"
+ PROP_ENSURE_DEFINITIONS_PATH + "` " + "cannot be blank.");
} else if (StringUtils.isBlank(oakIndexesPath)) {
throw new IllegalArgumentException("OSGi Configuration Property `"
+ PROP_OAK_INDEXES_PATH + "` " + "cannot be blank.");
}
resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
try {
this.ensure(resourceResolver, ensureDefinitionsPath, oakIndexesPath);
} catch (PersistenceException e) {
log.error("Could not ensure management of Oak Index [ {} ]", oakIndexesPath, e);
} catch (IOException e) {
log.error("Could not ensure management of Oak Index [ {} ]", oakIndexesPath, e);
}
} catch (IllegalArgumentException e) {
log.error(e.getMessage());
} catch (LoginException e) {
log.error("Could not get an admin resource resolver to ensure Oak Indexes", e);
} catch (Exception e) {
log.error("Unknown error occurred while ensuring indexes", e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
} | #vulnerable code
@Activate
protected final void activate(Map<String, Object> config) throws RepositoryException {
if (!capabilityHelper.isOak()) {
log.info("Cowardly refusing to create indexes on non-Oak instance.");
return;
}
final String srcPath = PropertiesUtil.toString(config.get(PROP_SOURCE_OAK_INDEX_PATH),
DEFAULT_SOURCE_OAK_INDEX_PATH);
final String destPath = PropertiesUtil.toString(config.get(PROP_DESTINATION_OAK_INDEX_PATH),
DEFAULT_DESTINATION_OAK_INDEX_PATH);
final String[] forceReindexNames =
PropertiesUtil.toStringArray(config.get(PROP_FORCE_REINDEX_OF), new String[]{});
final InfoWriter iw = new InfoWriter();
iw.title("Ensuring Oak Index");
iw.message(" * {} ~> {} ", srcPath, destPath);
iw.line();
if (forceReindexNames.length > 0) {
iw.message("Force reindex of:", forceReindexNames);
}
iw.end();
log.info(iw.toString());
ResourceResolver resourceResolver = null;
try {
if (StringUtils.isBlank(srcPath)) {
throw new IllegalArgumentException("OSGi Configuration Property `"
+ PROP_SOURCE_OAK_INDEX_PATH + "` " + "cannot be blank.");
} else if (StringUtils.isBlank(destPath)) {
throw new IllegalArgumentException("OSGi Configuration Property `"
+ PROP_DESTINATION_OAK_INDEX_PATH + "` " + "cannot be blank.");
}
resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
try {
this.ensure(resourceResolver, srcPath, destPath, forceReindexNames);
} catch (PersistenceException e) {
log.error("Could not ensure management of oak index [ {} ]", destPath, e);
} catch (IOException e) {
log.error("Could not ensure management of oak index [ {} ]", destPath, e);
}
} catch (IllegalArgumentException e) {
log.error(e.getMessage());
} catch (LoginException e) {
log.error("Could not get an admin resource resolver to ensure oak indexes", e);
} catch (Exception e) {
log.error("Unknown error occurred while ensuring indexes", e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
#location 26
#vulnerability type RESOURCE_LEAK | 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 {
final String transformName = PathInfoUtil.getSuffixSegment(request, 0);
final NamedImageTransformer namedImageTransformer = this.namedImageTransformers.get(transformName);
final Image image = this.resolveImage(request);
final String mimeType = this.getMimeType(request, image);
Layer layer = this.getLayer(image);
// Transform the image
layer = namedImageTransformer.transform(layer);
final double quality = (mimeType.equals(MIME_TYPE_GIF) ? IMAGE_GIF_MAX_QUALITY : IMAGE_MAX_QUALITY);
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 {
final String transformName = PathInfoUtil.getSuffixSegment(request, 0);
final NamedImageTransformer namedImageTransformer = this.namedImageTransformers.get(transformName);
final Image image = this.resolveImage(request);
final Layer layer = this.getLayer(image);
final String mimeType = this.getMimeType(request, image);
// Transform the image
namedImageTransformer.transform(layer);
final double quality = (mimeType.equals(MIME_TYPE_GIF) ? IMAGE_GIF_MAX_QUALITY : IMAGE_MAX_QUALITY);
response.setContentType(mimeType);
layer.write(mimeType, quality, response.getOutputStream());
response.flushBuffer();
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public final String get(final String path,
final SlingHttpServletRequest request,
final SlingHttpServletResponse response) {
if (!serveAuthenticatedFromCache && !isAnonymousRequest(request)) {
// For authenticated requests, don't return from cache
return ResourceDataUtil.getIncludeAsString(path, request, response);
}
final long start = System.currentTimeMillis();
CacheEntry cacheEntry = cache.get(path);
final boolean newEntry = cacheEntry == null;
if (newEntry || cacheEntry.isExpired(new Date())) {
// Cache Miss
final String data = ResourceDataUtil.getIncludeAsString(path, request, response);
if (newEntry) {
cacheEntry = new CacheEntry();
}
cacheEntry.setData(data);
cacheEntry.setExpiresIn(ttl);
cacheEntry.incrementMisses();
if (newEntry) {
// Add entry to cache
cache.put(path, cacheEntry);
}
log.info("Served cache MISS for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
} else {
// Cache Hit
final String data = cacheEntry.getData();
cacheEntry.incrementHits();
cache.put(path, cacheEntry);
log.info("Served cache HIT for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
}
} | #vulnerable code
@Override
public final String get(final String path,
final SlingHttpServletRequest request,
final SlingHttpServletResponse response) {
if (!serveAuthenticatedFromCache && !isAnonymousRequest(request)) {
// For authenticated requests, don't return from cache
return ResourceDataUtil.getIncludeAsString(path, request, response);
}
final long start = System.currentTimeMillis();
// Lock the cache because we we increment values within the cache even on valid cache hits
synchronized (this.cache) {
CacheEntry cacheEntry = cache.get(path);
if (cacheEntry == null || cacheEntry.isExpired(new Date())) {
// Cache Miss
if (cacheEntry == null) {
cacheEntry = new CacheEntry();
}
final String data = ResourceDataUtil.getIncludeAsString(path, request, response);
cacheEntry.setData(data);
cacheEntry.setExpiresIn(ttl);
cacheEntry.incrementMisses();
// Add entry to cache
cache.put(path, cacheEntry);
log.info("Served cache MISS for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
} else {
// Cache Hit
final String data = cacheEntry.getData();
cacheEntry.incrementHits();
cache.put(path, cacheEntry);
log.info("Served cache HIT for [ {} ] in [ {} ] ms", path, System.currentTimeMillis() - start);
return data;
}
}
}
#location 15
#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
private PageManager getPageManager(Object adaptable) {
ResourceResolver resolver = getResourceResolver(adaptable);
if(resolver != null) {
return resolver.adaptTo(PageManager.class);
}
return null;
} | #vulnerable code
private PageManager getPageManager(Object adaptable) {
return getResourceResolver(adaptable).adaptTo(PageManager.class);
}
#location 2
#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
@Test
public void testCreateRuntime_Injection() {
BQRuntime runtime = testFactory.app("-x").autoLoadModules().createRuntime();
assertArrayEquals(new String[]{"-x"}, runtime.getArgs());
} | #vulnerable code
@Test
public void testCreateRuntime_Injection() {
BQTestRuntime runtime = testFactory.app("-x").autoLoadModules().createRuntime();
assertArrayEquals(new String[]{"-x"}, runtime.getRuntime().getArgs());
}
#location 4
#vulnerability type RESOURCE_LEAK | 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
public static GaugeRollup buildFromGaugeRollups(Points<GaugeRollup> input) throws IOException {
GaugeRollup rollup = new GaugeRollup();
rollup.computeFromRollups(BasicRollup.recast(input, IBasicRollup.class));
Points.Point<SimpleNumber> latest = rollup.latestValue;
for (Map.Entry<Long, Points.Point<GaugeRollup>> entry : input.getPoints().entrySet()) {
if (latest == null || entry.getValue().getTimestamp() > latest.getTimestamp())
latest = entry.getValue().getData().latestValue;
}
rollup.latestValue = latest;
return rollup;
} | #vulnerable code
public static GaugeRollup buildFromGaugeRollups(Points<GaugeRollup> input) throws IOException {
// return the one with the latest timestamp.
int numSamples = 0;
Points.Point<GaugeRollup> latest = null;
for (Points.Point<GaugeRollup> point : input.getPoints().values()) {
if (latest == null)
latest = point;
else if (latest.getTimestamp() < point.getTimestamp())
latest = point;
numSamples += point.getData().getNumSamplesUnsafe();
}
GaugeRollup newGauge = new GaugeRollup().withGauge(latest.getData().getValue());
newGauge.numSamples = numSamples;
return newGauge;
}
#location 12
#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
public static void main(String[] args) {
if (args.length != 5){
System.err.println("Usage: java " + AFLDriver.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 AFLGuidance(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 " + AFLDriver.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 AFLGuidance(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
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 16
#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
@Override
public void evaluate() throws Throwable {
// Construct generators for each parameter
List<Generator<?>> generators = Arrays.stream(method.getMethod().getParameters())
.map(this::createParameterTypeContext)
.map(this::produceGenerator)
.collect(Collectors.toList());
// Keep fuzzing until no more input or I/O error with guidance
Guidance guidance = GuidedFuzzing.getGuidance();
try {
// Keep fuzzing as long as guidance wants to
while (guidance.hasInput()) {
Result result = INVALID;
Throwable error = null;
// Initialize guided fuzzing using a file-backed random number source
try {
StreamBackedRandom randomFile = new StreamBackedRandom(guidance.getInput(), Long.BYTES);
// Generate input values
Object[] args;
try {
SourceOfRandomness random = new FastSourceOfRandomness(randomFile);
GenerationStatus genStatus = new NonTrackingGenerationStatus(random);
args = generators.stream()
.map(g -> g.generate(random, genStatus))
.toArray();
} catch (IllegalStateException e) {
// This happens when we reach EOF before reading all the random values.
// Treat this as an assumption failure, so that the guidance considers the
// generated input as INVALID
throw new AssumptionViolatedException("StreamBackedRandom does not have enough data", e);
} catch (AssumptionViolatedException e) {
// Propagate assumption violations out
throw e;
} catch (Throwable e) {
// Throw the guidance exception outside to stop fuzzing
throw new GuidanceException(e);
} finally {
// System.out.println(randomFile.getTotalBytesRead() + " random bytes read");
}
// Attempt to run the trial
new TrialRunner(testClass.getJavaClass(), method, args).run();
// If we reached here, then the trial must be a success
result = SUCCESS;
} catch (GuidanceException e) {
// Throw the guidance exception outside to stop fuzzing
throw e;
} catch (AssumptionViolatedException e) {
result = INVALID;
error = e;
} catch (Throwable e) {
// Check if this exception was expected
if (isExceptionExpected(e.getClass())) {
result = SUCCESS; // Swallow the error
} else {
result = FAILURE;
error = e;
}
} finally {
// Wait for any instrumentation events to finish processing
SingleSnoop.waitForQuiescence();
// Inform guidance about the outcome of this trial
guidance.handleResult(result, error);
}
}
} catch (GuidanceException e) {
System.err.println("Fuzzing stopped due to guidance exception: " + e.getMessage());
}
} | #vulnerable code
@Override
public void evaluate() throws Throwable {
// Construct generators for each parameter
List<Generator<?>> generators = Arrays.stream(method.getMethod().getParameters())
.map(this::createParameterTypeContext)
.map(this::produceGenerator)
.collect(Collectors.toList());
// Keep fuzzing until no more input or I/O error with guidance
Guidance guidance = GuidedFuzzing.getGuidance();
try {
// Keep fuzzing as long as guidance wants to
while (guidance.hasInput()) {
Result result;
Throwable error = null;
// Initialize guided fuzzing using a file-backed random number source
try (FileBackedRandom randomFile = new FileBackedRandom(guidance.getInputFile(), Long.BYTES)) {
// Generate input values
Object[] args;
try {
SourceOfRandomness random = new FastSourceOfRandomness(randomFile);
GenerationStatus genStatus = new NonTrackingGenerationStatus(random);
args = generators.stream()
.map(g -> g.generate(random, genStatus))
.toArray();
} catch (IllegalStateException e) {
// This happens when we reach EOF before reading all the random values.
// Treat this as an assumption failure, so that the guidance considers the
// generated input as INVALID
throw new AssumptionViolatedException("FileBackedRandom does not have enough data", e);
} catch (AssumptionViolatedException e) {
// Propagate assumption violations out
throw e;
} catch (Throwable e) {
// Throw the guidance exception outside to stop fuzzing
throw new GuidanceException(e);
} finally {
// System.out.println(randomFile.getTotalBytesRead() + " random bytes read");
}
// Attempt to run the trial
new TrialRunner(testClass.getJavaClass(), method, args).run();
// If we reached here, then the trial must be a success
result = SUCCESS;
} catch (GuidanceException e) {
// Throw the guidance exception outside to stop fuzzing
throw e;
} catch (AssumptionViolatedException e) {
result = INVALID;
error = e;
} catch (Throwable e) {
// Check if this exception was expected
if (isExceptionExpected(e.getClass())) {
result = SUCCESS; // Swallow the error
} else {
result = FAILURE;
error = e;
}
}
// Wait for any instrumentation events to finish processing
SingleSnoop.waitForQuiescence();
// Inform guidance about the outcome of this trial
guidance.handleResult(result, error);
}
} catch (GuidanceException e) {
System.err.println("Fuzzing stopped due to guidance exception: " + e.getMessage());
}
}
#location 20
#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
public static Guidance getCurrentGuidance() {
return guidance;
} | #vulnerable code
public static Guidance getCurrentGuidance() {
if (guidance == null) {
System.err.println(String.format("Warning: No guidance set. " +
" Falling back to default %d trials with no feedback", DEFAULT_MAX_TRIALS));
setGuidance(new NoGuidance(DEFAULT_MAX_TRIALS, System.err));
}
return guidance;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | 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
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 16
#vulnerability type RESOURCE_LEAK | 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 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 void channelRead(final ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
final HttpRequest req = (HttpRequest) msg;
if (HttpUtil.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
}
nettyInputStream.clear(); // clearing the content - possible leftover from previous request processing.
final ContainerRequest requestContext = createContainerRequest(ctx, req);
requestContext.setWriter(new NettyResponseWriter(ctx, req, container));
long contentLength = req.headers().contains(HttpHeaderNames.CONTENT_LENGTH) ? HttpUtil.getContentLength(req)
: -1L;
if (contentLength >= MAX_REQUEST_ENTITY_BYTES) {
requestContext.abortWith(javax.ws.rs.core.Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build());
} else {
/**
* Jackson JSON decoder tries to read a minimum of 2 bytes (4
* for BOM). So, during an empty or 1-byte input, we'd want to
* avoid reading the entity to safely handle this edge case by
* eventually throwing a malformed JSON exception.
*/
String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);
boolean isJson = contentType != null ? contentType.toLowerCase().contains(MediaType.APPLICATION_JSON)
: false;
//process entity streams only if there is an entity issued in the request (i.e., content-length >=0).
//Otherwise, it's safe to discard during next processing
if ((!isJson && contentLength != -1) || HttpUtil.isTransferEncodingChunked(req)
|| (isJson && contentLength >= 2)) {
requestContext.setEntityStream(nettyInputStream);
}
}
// copying headers from netty request to jersey container request context.
for (String name : req.headers().names()) {
requestContext.headers(name, req.headers().getAll(name));
}
// must be like this, since there is a blocking read from Jersey
container.getExecutorService().execute(new Runnable() {
@Override
public void run() {
container.getApplicationHandler().handle(requestContext);
}
});
}
if (msg instanceof HttpContent) {
HttpContent httpContent = (HttpContent) msg;
ByteBuf content = httpContent.content();
if (content.isReadable()) {
nettyInputStream.publish(content);
}
if (msg instanceof LastHttpContent) {
nettyInputStream.complete(null);
}
}
} | #vulnerable code
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
final HttpRequest req = (HttpRequest) msg;
if (HttpUtil.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
}
isList.clear(); // clearing the content - possible leftover from previous request processing.
final ContainerRequest requestContext = createContainerRequest(ctx, req);
requestContext.setWriter(new NettyResponseWriter(ctx, req, container));
long contentLength = req.headers().contains(HttpHeaderNames.CONTENT_LENGTH) ? HttpUtil.getContentLength(req)
: -1L;
if (contentLength >= MAX_REQUEST_ENTITY_BYTES) {
requestContext.abortWith(javax.ws.rs.core.Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build());
} else {
/**
* Jackson JSON decoder tries to read a minimum of 2 bytes (4
* for BOM). So, during an empty or 1-byte input, we'd want to
* avoid reading the entity to safely handle this edge case by
* eventually throwing a malformed JSON exception.
*/
String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);
boolean isJson = contentType != null ? contentType.toLowerCase().contains(MediaType.APPLICATION_JSON)
: false;
//process entity streams only if there is an entity issued in the request (i.e., content-length >=0).
//Otherwise, it's safe to discard during next processing
if ((!isJson && contentLength != -1) || HttpUtil.isTransferEncodingChunked(req)
|| (isJson && contentLength >= 2)) {
requestContext.setEntityStream(new NettyInputStream(isList));
}
}
// copying headers from netty request to jersey container request context.
for (String name : req.headers().names()) {
requestContext.headers(name, req.headers().getAll(name));
}
// must be like this, since there is a blocking read from Jersey
container.getExecutorService().execute(new Runnable() {
@Override
public void run() {
container.getApplicationHandler().handle(requestContext);
}
});
}
if (msg instanceof HttpContent) {
HttpContent httpContent = (HttpContent) msg;
ByteBuf content = httpContent.content();
if (content.isReadable()) {
isList.add(content);
}
if (msg instanceof LastHttpContent) {
isList.add(Unpooled.EMPTY_BUFFER);
}
}
}
#location 34
#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 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 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 41
#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
@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 25
#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 4
#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 24
#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
@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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.