input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
|---|---|---|
#vulnerable code
@Test
public void authPlain() throws IOException, MessagingException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo(
"-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlain() throws IOException {
withConnection((printStream, reader) -> {
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
try {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
} catch (UserException e) {
throw new IllegalStateException(e);
}
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static int getLineCount(String str) {
LineNumberReader reader = new LineNumberReader(new StringReader(str));
try {
reader.skip(Long.MAX_VALUE);
return reader.getLineNumber();
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
// Ignore but warn
log.warn("Can not close reader", e);
}
}
}
#location 10
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static int getLineCount(String str) {
if (null == str || str.isEmpty()) {
return 0;
}
int count = 1;
for (char c : str.toCharArray()) {
if ('\n' == c) {
count++;
}
}
return count;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authDisabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(false);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authDisabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(false);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void authPlain(Pop3Connection conn, Pop3State state, String[] args) {
// https://tools.ietf.org/html/rfc4616
String initialResponse;
if (args.length == 2 || args.length == 3 && "=".equals(args[2])) { // Continuation?
conn.println(CONTINUATION);
try {
initialResponse = conn.readLine();
} catch (IOException e) {
conn.println("-ERR Invalid syntax, expected continuation with iniital-response");
return;
}
} else if (args.length == 3) {
initialResponse = args[2];
} else {
conn.println("-ERR Invalid syntax, expected initial-response : AUTH PLAIN [initial-response]");
return;
}
// authorization-id\0authentication-id\0passwd
final BASE64DecoderStream stream = new BASE64DecoderStream(
new ByteArrayInputStream(initialResponse.getBytes(StandardCharsets.UTF_8)));
readTillNullChar(stream); // authorizationId Not used
String authenticationId = readTillNullChar(stream);
GreenMailUser user;
try {
user = state.getUser(authenticationId);
state.setUser(user);
} catch (UserException e) {
log.error("Can not get user <" + authenticationId + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage() /* GreenMail is just a test server */);
return;
}
try {
state.authenticate(readTillNullChar(stream));
conn.println("+OK");
} catch (UserException e) {
log.error("Can not authenticate using user <" + user.getLogin() + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage());
} catch (FolderException e) {
log.error("Can not authenticate using user " + user + ", internal error", e);
conn.println("-ERR Authentication failed, internal error: " + e.getMessage());
}
}
#location 36
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void authPlain(Pop3Connection conn, Pop3State state, String[] args) {
// https://tools.ietf.org/html/rfc4616
String initialResponse;
if (args.length == 2 || args.length == 3 && "=".equals(args[2])) { // Continuation?
conn.println(CONTINUATION);
try {
initialResponse = conn.readLine();
} catch (IOException e) {
conn.println("-ERR Invalid syntax, expected continuation with iniital-response");
return;
}
} else if (args.length == 3) {
initialResponse = args[2];
} else {
conn.println("-ERR Invalid syntax, expected initial-response : AUTH PLAIN [initial-response]");
return;
}
// authorization-id\0authentication-id\0passwd
final SaslMessage saslMessage;
try {
saslMessage = SaslMessage.parse(EncodingUtil.decodeBase64(initialResponse));
} catch(IllegalArgumentException ex) { // Invalid Base64
log.error("Expected base64 encoding but got <"+initialResponse+">", ex); /* GreenMail is just a test server */
conn.println("-ERR Authentication failed, expected base64 encoding : " + ex.getMessage() );
return;
}
GreenMailUser user;
try {
user = state.getUser(saslMessage.getAuthcid());
state.setUser(user);
} catch (UserException e) {
log.error("Can not get user <" + saslMessage.getAuthcid() + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage() /* GreenMail is just a test server */);
return;
}
try {
state.authenticate(saslMessage.getPasswd());
conn.println("+OK");
} catch (UserException e) {
log.error("Can not authenticate using user <" + user.getLogin() + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage());
} catch (FolderException e) {
log.error("Can not authenticate using user " + user + ", internal error", e);
conn.println("-ERR Authentication failed, internal error: " + e.getMessage());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authEnabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(true);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authEnabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(true);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authPlain() throws IOException, MessagingException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo(
"-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlain() throws IOException {
withConnection((printStream, reader) -> {
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
try {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
} catch (UserException e) {
throw new IllegalStateException(e);
}
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public long appendMessage(MimeMessage message,
Flags flags,
Date receivedDate) {
long uid = nextUid;
nextUid++;
try {
message.setFlags(flags, true);
message.setFlag(Flags.Flag.RECENT, true);
} catch (MessagingException e) {
throw new IllegalStateException("Can not set flags", e);
}
StoredMessage storedMessage = new StoredMessage(message,
receivedDate, uid);
int newMsn;
synchronized (mailMessages) {
mailMessages.add(storedMessage);
newMsn = mailMessages.size();
}
// Notify all the listeners of the new message
synchronized (_mailboxListeners) {
for (FolderListener _mailboxListener : _mailboxListeners) {
_mailboxListener.added(newMsn);
}
}
return uid;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public long appendMessage(MimeMessage message,
Flags flags,
Date receivedDate) {
final long uid = nextUid.getAndIncrement();
try {
message.setFlags(flags, true);
message.setFlag(Flags.Flag.RECENT, true);
} catch (MessagingException e) {
throw new IllegalStateException("Can not set flags", e);
}
StoredMessage storedMessage = new StoredMessage(message,
receivedDate, uid);
int newMsn;
synchronized (mailMessages) {
mailMessages.add(storedMessage);
newMsn = mailMessages.size();
}
// Notify all the listeners of the new message
synchronized (_mailboxListeners) {
for (FolderListener _mailboxListener : _mailboxListeners) {
_mailboxListener.added(newMsn);
}
}
return uid;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authEnabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(true);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
}
}
#location 11
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authEnabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(true);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authDisabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(false);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 11
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authDisabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(false);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean waitForIncomingEmail(long timeout, int emailCount) {
final SmtpManager.WaitObject waitObject = managers.getSmtpManager().createAndAddNewWaitObject(emailCount);
final long endTime = System.currentTimeMillis() + timeout;
synchronized (waitObject) {
while (!waitObject.isArrived()) {
final long waitTime = endTime - System.currentTimeMillis();
if (waitTime < 0L) {
return waitObject.isArrived();
}
//this loop is necessary to insure correctness, see documentation on Object.wait()
try {
waitObject.wait(waitTime);
} catch (InterruptedException e) {
throw new IllegalStateException("Interrupted while waiting for incoming email", e);
}
}
}
return waitObject.isArrived();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean waitForIncomingEmail(long timeout, int emailCount) {
final CountDownLatch waitObject = managers.getSmtpManager().createAndAddNewWaitObject(emailCount);
final long endTime = System.currentTimeMillis() + timeout;
while (waitObject.getCount() > 0) {
final long waitTime = endTime - System.currentTimeMillis();
if (waitTime < 0L) {
return waitObject.getCount() == 0;
}
try {
waitObject.await(waitTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Continue loop, in case of premature interruption
}
}
return waitObject.getCount() == 0;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlainWithContinuation() throws IOException, UserException {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION);
printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private boolean authenticate(UserManager userManager, String value) {
// authorization-id\0authentication-id\0passwd
final BASE64DecoderStream stream = new BASE64DecoderStream(
new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8)));
readTillNullChar(stream); // authorizationId Not used
String authenticationId = readTillNullChar(stream);
String passwd = readTillNullChar(stream);
return userManager.test(authenticationId, passwd);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
private boolean authenticate(UserManager userManager, String value) {
// authorization-id\0authentication-id\0passwd
final SaslMessage saslMessage = SaslMessage.parse(value);
return userManager.test(saslMessage.getAuthcid(), saslMessage.getPasswd());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public long getUidNext() {
return nextUid;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public long getUidNext() {
return nextUid.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authPlain() throws IOException, MessagingException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo(
"-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 22
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authPlain() throws IOException {
withConnection((printStream, reader) -> {
// No such user
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User <test> doesn't exist");
try {
greenMail.getManagers().getUserManager()
.createUser("test@localhost", "test", "testpass");
} catch (UserException e) {
throw new IllegalStateException(e);
}
// Invalid pwd
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits");
// Successful auth
printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authDisabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(false);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authDisabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(false);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void run() {
try {
serverSocket = openServerSocket();
setRunning(true);
synchronized (this) {
this.notifyAll();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
final ProtocolHandler handler = createProtocolHandler(clientSocket);
addHandler(handler);
new Thread(new Runnable() {
@Override
public void run() {
handler.run(); // NOSONAR
// Make sure to deregister, see https://github.com/greenmail-mail-test/greenmail/issues/18
removeHandler(handler);
}
}).start();
}
} catch (IOException ignored) {
//ignored
if(log.isTraceEnabled()) {
log.trace("Error while processing socket", ignored);
}
}
}
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void run() {
try {
serverSocket = openServerSocket();
setRunning(true);
synchronized (this) {
this.notifyAll();
}
synchronized (startupMonitor) {
startupMonitor.notifyAll();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
final ProtocolHandler handler = createProtocolHandler(clientSocket);
addHandler(handler);
new Thread(new Runnable() {
@Override
public void run() {
handler.run(); // NOSONAR
// Make sure to deregister, see https://github.com/greenmail-mail-test/greenmail/issues/18
removeHandler(handler);
}
}).start();
}
} catch (IOException ignored) {
//ignored
if (log.isTraceEnabled()) {
log.trace("Error while processing socket", ignored);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void authEnabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(true);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void authEnabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(true);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER blar@blar.com" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
});
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testMergeSelf_forceNormal() throws CardinalityMergeException, IOException {
final int[] cardinalities = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int cardinality : cardinalities) {
for (int j = 4; j < 24; j++) {
System.out.println("p=" + j);
HyperLogLogPlus hllPlus = new HyperLogLogPlus(j, 0);
for (int l = 0; l < cardinality; l++) {
hllPlus.offer(Math.random());
}
System.out.println("hllcardinality=" + hllPlus.cardinality() + " cardinality=" + cardinality);
HyperLogLogPlus deserialized = HyperLogLogPlus.Builder.build(hllPlus.getBytes());
assertEquals(hllPlus.cardinality(), deserialized.cardinality());
ICardinality merged = hllPlus.merge(deserialized);
System.out.println(merged.cardinality() + " : " + hllPlus.cardinality());
assertEquals(hllPlus.cardinality(), merged.cardinality());
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testMergeSelf_forceNormal() throws CardinalityMergeException, IOException {
final int[] cardinalities = {0, 1, 10, 100, 1000, 10000, 100000, 1000000};
for (int cardinality : cardinalities) {
for (int j = 4; j < 24; j++) {
System.out.println("p=" + j);
HyperLogLogPlus hllPlus = new HyperLogLogPlus(j, 0);
for (int l = 0; l < cardinality; l++) {
hllPlus.offer(Math.random());
}
System.out.println("hllcardinality=" + hllPlus.cardinality() + " cardinality=" + cardinality);
HyperLogLogPlus deserialized = HyperLogLogPlus.Builder.build(hllPlus.getBytes());
assertEquals(hllPlus.cardinality(), deserialized.cardinality());
ICardinality merged = hllPlus.merge(deserialized);
System.out.println(merged.cardinality() + " : " + hllPlus.cardinality());
assertEquals(hllPlus.cardinality(), merged.cardinality());
assertEquals(hllPlus.cardinality(), hllPlus.cardinality());
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private ResponseEntity<String> mina(IPageData pd, JSONObject paramIn, JSONObject paramOut, String userId, List<OwnerAppUserDto> ownerAppUserDtos) {
ResponseEntity<String> responseEntity = null;
//查询微信信息
pd = PageData.newInstance().builder(userId, "", "", pd.getReqData(),
"", "", "", "",
pd.getAppId());
responseEntity = this.callCenterService(restTemplate, pd, "",
ServiceConstant.SERVICE_API_URL + "/api/smallWeChat.listSmallWeChats?appId="
+ paramIn.getString("appId") + "&page=1&row=1", HttpMethod.GET);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
return responseEntity;
}
JSONObject smallWechatObj = JSONObject.parseObject(responseEntity.getBody().toString());
JSONArray smallWeChats = smallWechatObj.getJSONArray("smallWeChats");
String appId = wechatAuthProperties.getAppId();
String secret = wechatAuthProperties.getSecret();
if (smallWeChats.size() > 0) {
appId = smallWeChats.getJSONObject(0).getString("appId");
secret = smallWeChats.getJSONObject(0).getString("appSecret");
}
String code = paramIn.getString("code");
String urlString = "?appid={appId}&secret={secret}&js_code={code}&grant_type={grantType}";
String response = outRestTemplate.getForObject(
wechatAuthProperties.getSessionHost() + urlString, String.class,
appId,
secret,
code,
wechatAuthProperties.getGrantType());
logger.debug("wechatAuthProperties:" + JSONObject.toJSONString(wechatAuthProperties));
logger.debug("微信返回报文:" + response);
//Assert.jsonObjectHaveKey(response, "errcode", "返回报文中未包含 错误编码,接口出错");
JSONObject responseObj = JSONObject.parseObject(response);
if (responseObj.containsKey("errcode") && !"0".equals(responseObj.getString("errcode"))) {
throw new IllegalArgumentException("微信验证失败,可能是code失效" + responseObj);
}
String openId = responseObj.getString("openid");
OwnerAppUserDto ownerAppUserDto = judgeCurrentOwnerBind(ownerAppUserDtos, OwnerAppUserDto.APP_TYPE_WECHAT_MINA);
//说明 当前的openId 就是最新的
if (ownerAppUserDto != null && openId.equals(ownerAppUserDto.getOpenId())) {
return new ResponseEntity<>(paramOut.toJSONString(), HttpStatus.OK);
}
OwnerAppUserDto tmpOwnerAppUserDto = new OwnerAppUserDto();
ownerAppUserDto.setOpenId(openId);
ownerAppUserDto.setAppType(OwnerAppUserDto.APP_TYPE_WECHAT_MINA);
if (ownerAppUserDto != null) {
ownerAppUserDto.setAppUserId(tmpOwnerAppUserDto.getAppUserId());
ownerAppUserDto.setCommunityId(tmpOwnerAppUserDto.getCommunityId());
} else {
ownerAppUserDto.setOldAppUserId(ownerAppUserDtos.get(0).getAppUserId());
ownerAppUserDto.setAppUserId("-1");
ownerAppUserDto.setCommunityId(ownerAppUserDtos.get(0).getCommunityId());
}
//查询微信信息
pd = PageData.newInstance().builder(userId, "", "", pd.getReqData(),
"", "", "", "",
pd.getAppId());
super.postForApi(pd, ownerAppUserDto, ServiceCodeConstant.REFRESH_APP_USER_BINDING_OWNER_OPEN_ID,
OwnerAppUserDto.class);
return new ResponseEntity<>(paramOut.toJSONString(), HttpStatus.OK);
}
#location 54
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private ResponseEntity<String> mina(IPageData pd, JSONObject paramIn, JSONObject paramOut, String userId, List<OwnerAppUserDto> ownerAppUserDtos) {
ResponseEntity<String> responseEntity = null;
//查询微信信息
pd = PageData.newInstance().builder(userId, "", "", pd.getReqData(),
"", "", "", "",
pd.getAppId());
responseEntity = this.callCenterService(restTemplate, pd, "",
ServiceConstant.SERVICE_API_URL + "/api/smallWeChat.listSmallWeChats?appId="
+ paramIn.getString("appId") + "&page=1&row=1", HttpMethod.GET);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
return responseEntity;
}
JSONObject smallWechatObj = JSONObject.parseObject(responseEntity.getBody().toString());
JSONArray smallWeChats = smallWechatObj.getJSONArray("smallWeChats");
String appId = wechatAuthProperties.getAppId();
String secret = wechatAuthProperties.getSecret();
if (smallWeChats.size() > 0) {
appId = smallWeChats.getJSONObject(0).getString("appId");
secret = smallWeChats.getJSONObject(0).getString("appSecret");
}
String code = paramIn.getString("code");
String urlString = "?appid={appId}&secret={secret}&js_code={code}&grant_type={grantType}";
String response = outRestTemplate.getForObject(
wechatAuthProperties.getSessionHost() + urlString, String.class,
appId,
secret,
code,
wechatAuthProperties.getGrantType());
logger.debug("wechatAuthProperties:" + JSONObject.toJSONString(wechatAuthProperties));
logger.debug("微信返回报文:" + response);
//Assert.jsonObjectHaveKey(response, "errcode", "返回报文中未包含 错误编码,接口出错");
JSONObject responseObj = JSONObject.parseObject(response);
if (responseObj.containsKey("errcode") && !"0".equals(responseObj.getString("errcode"))) {
throw new IllegalArgumentException("微信验证失败,可能是code失效" + responseObj);
}
String openId = responseObj.getString("openid");
OwnerAppUserDto ownerAppUserDto = judgeCurrentOwnerBind(ownerAppUserDtos, OwnerAppUserDto.APP_TYPE_WECHAT_MINA);
//说明 当前的openId 就是最新的
if (ownerAppUserDto != null && openId.equals(ownerAppUserDto.getOpenId())) {
return new ResponseEntity<>(paramOut.toJSONString(), HttpStatus.OK);
}
OwnerAppUserDto tmpOwnerAppUserDto = new OwnerAppUserDto();
tmpOwnerAppUserDto.setOpenId(openId);
tmpOwnerAppUserDto.setAppType(OwnerAppUserDto.APP_TYPE_WECHAT_MINA);
if (ownerAppUserDto != null) {
tmpOwnerAppUserDto.setAppUserId(ownerAppUserDto.getAppUserId());
tmpOwnerAppUserDto.setCommunityId(ownerAppUserDto.getCommunityId());
} else {
tmpOwnerAppUserDto.setOldAppUserId(ownerAppUserDtos.get(0).getAppUserId());
tmpOwnerAppUserDto.setAppUserId("-1");
tmpOwnerAppUserDto.setCommunityId(ownerAppUserDtos.get(0).getCommunityId());
}
//查询微信信息
pd = PageData.newInstance().builder(userId, "", "", pd.getReqData(),
"", "", "", "",
pd.getAppId());
super.postForApi(pd, tmpOwnerAppUserDto, ServiceCodeConstant.REFRESH_APP_USER_BINDING_OWNER_OPEN_ID,
OwnerAppUserDto.class);
return new ResponseEntity<>(paramOut.toJSONString(), HttpStatus.OK);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void soService(ServiceDataFlowEvent event) {
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
JSONObject data = dataFlowContext.getReqJson();
Assert.hasKeyAndValue(data,"page","请求报文中未包含page节点");
Assert.hasKeyAndValue(data,"rows","请求报文中未包含rows节点");
Assert.hasKeyAndValue(data,"storeId","请求报文中未包含storeId节点");
Assert.hasKeyAndValue(data,"name","请求报文中未包含name节点");
ResponseEntity<String> responseEntity = null;
//根据名称查询用户信息
responseEntity = super.callService(dataFlowContext,ServiceCodeConstant.SERVICE_CODE_QUERY_USER_BY_NAME,data);
if(responseEntity.getStatusCode() != HttpStatus.OK){
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
JSONArray resultInfo = JSONObject.parseObject(responseEntity.getBody().toString()).getJSONArray("users");
if(resultInfo != null || resultInfo.size() < 1){
responseEntity = new ResponseEntity<String>(new JSONArray().toJSONString(),HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void soService(ServiceDataFlowEvent event) throws ListenerExecuteException{
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
JSONObject data = dataFlowContext.getReqJson();
Assert.hasKeyAndValue(data,"storeId","请求报文中未包含storeId节点");
Assert.hasKeyAndValue(data,"name","请求报文中未包含name节点");
ResponseEntity<String> responseEntity = null;
//根据名称查询用户信息
responseEntity = super.callService(dataFlowContext,ServiceCodeConstant.SERVICE_CODE_QUERY_USER_BY_NAME,data);
if(responseEntity.getStatusCode() != HttpStatus.OK){
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String useIds = getUserIds(responseEntity,dataFlowContext);
if(StringUtil.isEmpty(useIds)){
responseEntity = new ResponseEntity<String>(new JSONArray().toJSONString(),HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
JSONArray userInfos = getUserInfos(responseEntity);
Map<String,String> paramIn = new HashMap<>();
paramIn.put("userIds",useIds);
paramIn.put("storeId",data.getString("storeId"));
//查询是商户员工的userId
responseEntity = super.callService(dataFlowContext,ServiceCodeConstant.SERVICE_CODE_QUERY_STOREUSER_BYUSERIDS,paramIn);
if(responseEntity.getStatusCode() != HttpStatus.OK){
return ;
}
responseEntity = new ResponseEntity<String>(getStaffUsers(userInfos,responseEntity).toJSONString(),HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private ResponseEntity<String> savedFloorAndUnitInfo(IPageData pd, List<ImportFloor> floors, ComponentValidateResult result) {
String apiUrl = "";
JSONObject paramIn = null;
ResponseEntity<String> responseEntity = null;
for (ImportFloor importFloor : floors) {
paramIn = new JSONObject();
//先保存 楼栋信息
JSONObject savedFloorInfo = getExistsFloor(pd, result, importFloor);
// 如果不存在,才插入
if (savedFloorInfo == null) {
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.saveFloor";
paramIn.put("communityId", result.getCommunityId());
paramIn.put("floorNum", importFloor.getFloorNum());
paramIn.put("userId", result.getUserId());
paramIn.put("name", importFloor.getFloorNum() + "号楼");
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
}
if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息
continue;
}
savedFloorInfo = getExistsFloor(pd, result, importFloor);
if (savedFloorInfo == null) {
continue;
}
importFloor.setFloorId(savedFloorInfo.getString("floorId"));
paramIn.clear();
//判断单元信息是否已经存在,如果存在则不保存数据unit.queryUnits
if (getExistsUnit(pd, result, importFloor) != null) {
continue;
}
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.saveUnit";
paramIn.put("communityId", result.getCommunityId());
paramIn.put("floorId", savedFloorInfo.getString("floorId"));
paramIn.put("unitNum", importFloor.getUnitNum());
paramIn.put("layerCount", importFloor.getLayerCount());
paramIn.put("lift", importFloor.getLift());
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
//将unitId 刷入ImportFloor对象
JSONObject savedUnitInfo = getExistsUnit(pd, result, importFloor);
importFloor.setUnitId(savedUnitInfo.getString("unitId"));
}
return responseEntity;
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private ResponseEntity<String> savedFloorAndUnitInfo(IPageData pd, List<ImportFloor> floors, ComponentValidateResult result) {
String apiUrl = "";
JSONObject paramIn = null;
ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功",HttpStatus.OK);
for (ImportFloor importFloor : floors) {
paramIn = new JSONObject();
//先保存 楼栋信息
JSONObject savedFloorInfo = getExistsFloor(pd, result, importFloor);
// 如果不存在,才插入
if (savedFloorInfo == null) {
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.saveFloor";
paramIn.put("communityId", result.getCommunityId());
paramIn.put("floorNum", importFloor.getFloorNum());
paramIn.put("userId", result.getUserId());
paramIn.put("name", importFloor.getFloorNum() + "号楼");
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
}
if (responseEntity != null && responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息
continue;
}
savedFloorInfo = getExistsFloor(pd, result, importFloor);
if (savedFloorInfo == null) {
continue;
}
importFloor.setFloorId(savedFloorInfo.getString("floorId"));
paramIn.clear();
//判断单元信息是否已经存在,如果存在则不保存数据unit.queryUnits
JSONObject savedUnitInfo = getExistsUnit(pd, result, importFloor);
if ( savedUnitInfo != null) {
importFloor.setUnitId(savedUnitInfo.getString("unitId"));
continue;
}
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.saveUnit";
paramIn.put("communityId", result.getCommunityId());
paramIn.put("floorId", savedFloorInfo.getString("floorId"));
paramIn.put("unitNum", importFloor.getUnitNum());
paramIn.put("layerCount", importFloor.getLayerCount());
paramIn.put("lift", importFloor.getLift());
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
//将unitId 刷入ImportFloor对象
savedUnitInfo = getExistsUnit(pd, result, importFloor);
importFloor.setUnitId(savedUnitInfo.getString("unitId"));
}
return responseEntity;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void soService(ServiceDataFlowEvent event) {
//获取数据上下文对象
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
String paramIn = dataFlowContext.getReqData();
Assert.isJsonObject(paramIn,"用户注册请求参数有误,不是有效的json格式 "+paramIn);
Assert.jsonObjectHaveKey(paramIn,"username","用户登录,未包含username节点,请检查" + paramIn);
Assert.jsonObjectHaveKey(paramIn,"passwd","用户登录,未包含passwd节点,请检查" + paramIn);
RestTemplate restTemplate = super.getRestTemplate();
ResponseEntity responseEntity= null;
JSONObject paramInJson = JSONObject.parseObject(paramIn);
//根据AppId 查询 是否有登录的服务,查询登录地址调用
AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
String requestUrl = appService.getUrl() + "?userCode="+paramInJson.getString("username");
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(),ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
try{
responseEntity = restTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, String.class);
}catch (HttpStatusCodeException e){ //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
responseEntity = new ResponseEntity<String>("请求登录查询异常,"+e.getResponseBodyAsString(),e.getStatusCode());
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String resultBody = responseEntity.getBody().toString();
Assert.isJsonObject(resultBody,"调用登录查询异常,返回报文有误,不是有效的json格式 "+resultBody);
JSONObject resultInfo = JSONObject.parseObject(resultBody);
if(!resultInfo.containsKey("user") || !resultInfo.getJSONObject("user").containsKey("userPwd")
|| !resultInfo.getJSONObject("user").containsKey("userId")){
responseEntity = new ResponseEntity<String>("用户或密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
JSONObject userInfo = resultInfo.getJSONObject("user");
String userPwd = userInfo.getString("userPwd");
if(!userPwd.equals(paramInJson.getString("passwd"))){
responseEntity = new ResponseEntity<String>("密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
try {
Map userMap = new HashMap();
userMap.put(CommonConstant.LOGIN_USER_ID,userInfo.getString("userId"));
String token = AuthenticationFactory.createAndSaveToken(userMap);
userInfo.remove("userPwd");
userInfo.put("token",token);
responseEntity = new ResponseEntity<String>(userInfo.toJSONString(), HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
}catch (Exception e){
logger.error("登录异常:",e);
throw new SMOException(ResponseConstant.RESULT_CODE_INNER_ERROR,"系统内部错误,请联系管理员");
}
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void soService(ServiceDataFlowEvent event) {
//获取数据上下文对象
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
String paramIn = dataFlowContext.getReqData();
Assert.isJsonObject(paramIn,"用户注册请求参数有误,不是有效的json格式 "+paramIn);
Assert.jsonObjectHaveKey(paramIn,"username","用户登录,未包含username节点,请检查" + paramIn);
Assert.jsonObjectHaveKey(paramIn,"passwd","用户登录,未包含passwd节点,请检查" + paramIn);
RestTemplate restTemplate = super.getRestTemplate();
ResponseEntity responseEntity= null;
JSONObject paramInJson = JSONObject.parseObject(paramIn);
//根据AppId 查询 是否有登录的服务,查询登录地址调用
AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
if(appService == null){
responseEntity = new ResponseEntity<String>("当前没有权限访问"+ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN,HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String requestUrl = appService.getUrl() + "?userCode="+paramInJson.getString("username");
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(),ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
try{
responseEntity = restTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, String.class);
}catch (HttpStatusCodeException e){ //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
responseEntity = new ResponseEntity<String>("请求登录查询异常,"+e.getResponseBodyAsString(),e.getStatusCode());
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String resultBody = responseEntity.getBody().toString();
Assert.isJsonObject(resultBody,"调用登录查询异常,返回报文有误,不是有效的json格式 "+resultBody);
JSONObject resultInfo = JSONObject.parseObject(resultBody);
if(!resultInfo.containsKey("user") || !resultInfo.getJSONObject("user").containsKey("userPwd")
|| !resultInfo.getJSONObject("user").containsKey("userId")){
responseEntity = new ResponseEntity<String>("用户或密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
JSONObject userInfo = resultInfo.getJSONObject("user");
String userPwd = userInfo.getString("userPwd");
if(!userPwd.equals(paramInJson.getString("passwd"))){
responseEntity = new ResponseEntity<String>("密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
try {
Map userMap = new HashMap();
userMap.put(CommonConstant.LOGIN_USER_ID,userInfo.getString("userId"));
String token = AuthenticationFactory.createAndSaveToken(userMap);
userInfo.remove("userPwd");
userInfo.put("token",token);
responseEntity = new ResponseEntity<String>(userInfo.toJSONString(), HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
}catch (Exception e){
logger.error("登录异常:",e);
throw new SMOException(ResponseConstant.RESULT_CODE_INNER_ERROR,"系统内部错误,请联系管理员");
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
try {
File file = new File("/home/hc/img/"+ UUID.randomUUID().toString()+".jpg");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
out.write(fileImg);
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
//String context = new BASE64Encoder().encode(fileImg);
String context = Base64Convert.byteToBase64(fileImg);
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
}
#location 27
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
// byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
// java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
// java110Properties.getFtpUserPassword());
//
// //String context = new BASE64Encoder().encode(fileImg);
// String context = Base64Convert.byteToBase64(fileImg);
String context = ftpUploadTemplate.download(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void validate(String paramIn) {
Assert.jsonObjectHaveKey(paramIn, "communityId", "请求报文中未包含communityId节点");
Assert.jsonObjectHaveKey(paramIn, "squarePrice", "请求报文中未包含squarePrice节点");
Assert.jsonObjectHaveKey(paramIn, "additionalAmount", "请求报文中未包含additionalAmount节点");
Assert.jsonObjectHaveKey(paramIn, "feeTypeCd", "请求报文中未包含feeTypeCd节点");
JSONObject reqJson = JSONObject.parseObject(paramIn);
Assert.isMoney(reqJson.getString("squarePrice"), "squarePrice不是有效金额格式");
Assert.isMoney(reqJson.getString("additionalAmount"), "additionalAmount不是有效金额格式");
FeeConfigDto feeConfigDto = new FeeConfigDto();
feeConfigDto.setCommunityId(reqJson.getString("communityId"));
feeConfigDto.setFeeTypeCd(reqJson.getString("feeTypeCd"));
//校验小区楼ID和小区是否有对应关系
List<FeeConfigDto> configDtos = feeConfigInnerServiceSMOImpl.queryFeeConfigs(feeConfigDto);
if (configDtos != null || configDtos.size() > 0) {
throw new IllegalArgumentException("已经存在费用配置信息");
}
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void validate(String paramIn) {
Assert.jsonObjectHaveKey(paramIn, "communityId", "请求报文中未包含communityId节点");
Assert.jsonObjectHaveKey(paramIn, "squarePrice", "请求报文中未包含squarePrice节点");
Assert.jsonObjectHaveKey(paramIn, "additionalAmount", "请求报文中未包含additionalAmount节点");
Assert.jsonObjectHaveKey(paramIn, "feeTypeCd", "请求报文中未包含feeTypeCd节点");
JSONObject reqJson = JSONObject.parseObject(paramIn);
Assert.isMoney(reqJson.getString("squarePrice"), "squarePrice不是有效金额格式");
Assert.isMoney(reqJson.getString("additionalAmount"), "additionalAmount不是有效金额格式");
FeeConfigDto feeConfigDto = new FeeConfigDto();
feeConfigDto.setCommunityId(reqJson.getString("communityId"));
feeConfigDto.setFeeTypeCd(reqJson.getString("feeTypeCd"));
//校验小区楼ID和小区是否有对应关系
List<FeeConfigDto> configDtos = feeConfigInnerServiceSMOImpl.queryFeeConfigs(feeConfigDto);
if (configDtos != null && configDtos.size() > 0) {
throw new IllegalArgumentException("已经存在费用配置信息");
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
try {
File file = new File("/home/hc/img/"+ UUID.randomUUID().toString()+".jpg");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
out.write(fileImg);
}catch (Exception e){
e.printStackTrace();
}
//String context = new BASE64Encoder().encode(fileImg);
String context = Base64Convert.byteToBase64(fileImg);
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
}
#location 24
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
try {
File file = new File("/home/hc/img/"+ UUID.randomUUID().toString()+".jpg");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
out.write(fileImg);
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
//String context = new BASE64Encoder().encode(fileImg);
String context = Base64Convert.byteToBase64(fileImg);
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
JSONObject outParam = null;
ResponseEntity<String> responseEntity = null;
Map<String, String> reqHeader = context.getRequestHeaders();
String communityId = reqHeader.get("communityId");
String machineCode = reqHeader.get("machinecode");
HttpHeaders headers = new HttpHeaders();
for (String key : reqHeader.keySet()) {
if (key.toLowerCase().equals("content-length")) {
continue;
}
headers.add(key, reqHeader.get(key));
}
//根据设备编码查询 设备信息
MachineDto machineDto = new MachineDto();
machineDto.setMachineCode(machineCode);
machineDto.setCommunityId(communityId);
List<MachineDto> machineDtos = machineInnerServiceSMOImpl.queryMachines(machineDto);
if (machineDtos == null || machineDtos.size() < 1) {
outParam.put("code", -1);
outParam.put("message", "该设备【" + machineCode + "】未在该小区【" + communityId + "】注册");
responseEntity = new ResponseEntity<>(outParam.toJSONString(), headers, HttpStatus.OK);
context.setResponseEntity(responseEntity);
return;
}
//设备方向
String direction = machineDtos.get(0).getDirection();
//进入
if (MACHINE_DIRECTION_IN.equals(direction)) {
dealCarIn(event, context, reqJson, machineDtos.get(0), communityId);
} else {
dealCarOut(event, context, reqJson, machineDtos.get(0), communityId);
}
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
//JSONObject outParam = null;
ResponseEntity<String> responseEntity = null;
Map<String, String> reqHeader = context.getRequestHeaders();
String communityId = reqHeader.get("communityId");
String machineCode = reqHeader.get("machinecode");
HttpHeaders headers = new HttpHeaders();
for (String key : reqHeader.keySet()) {
if (key.toLowerCase().equals("content-length")) {
continue;
}
headers.add(key, reqHeader.get(key));
}
//根据设备编码查询 设备信息
MachineDto machineDto = new MachineDto();
machineDto.setMachineCode(machineCode);
machineDto.setCommunityId(communityId);
List<MachineDto> machineDtos = machineInnerServiceSMOImpl.queryMachines(machineDto);
if (machineDtos == null || machineDtos.size() < 1) {
responseEntity = MachineResDataVo.getResData(MachineResDataVo.CODE_ERROR,"该设备【" + machineCode + "】未在该小区【" + communityId + "】注册");
context.setResponseEntity(responseEntity);
return;
}
//设备方向
String direction = machineDtos.get(0).getDirection();
//进入
if (MACHINE_DIRECTION_IN.equals(direction)) {
dealCarIn(event, context, reqJson, machineDtos.get(0), communityId);
} else {
dealCarOut(event, context, reqJson, machineDtos.get(0), communityId);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void notify(DelegateTask delegateTask) {
logger.info("查询部门审核人员");
auditUserInnerServiceSMOImpl = ApplicationContextFactory.getBean("auditUserInnerServiceSMOImpl", IAuditUserInnerServiceSMO.class);
AuditUserDto auditUserDto = new AuditUserDto();
PurchaseApplyDto purchaseApplyDto = (PurchaseApplyDto)delegateTask.getVariable("purchaseApplyDto");
auditUserDto.setStoreId(purchaseApplyDto.getStoreId());
auditUserDto.setObjCode("resourceEntry");
auditUserDto.setAuditLink("809001");
List<AuditUserDto> auditUserDtos = auditUserInnerServiceSMOImpl.queryAuditUsers(auditUserDto);
for (AuditUserDto tmpAuditUser : auditUserDtos) {
AuditUser auditUser = BeanConvertUtil.covertBean(tmpAuditUser, AuditUser.class);
logger.info("查询到用户:"+tmpAuditUser.getUserName());
delegateTask.setVariable(auditUser.getUserId(), auditUser);
}
logger.info("查询审核人员人数:"+auditUserDtos.size());
if (auditUserDtos == null || auditUserDtos.size() < 1) {
return;
}
delegateTask.setAssignee(auditUserDtos.get(0).getUserId());
logger.info("设置部门审核人员:"+auditUserDtos.get(0).getUserId()+auditUserDtos.get(0).getUserName());
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void notify(DelegateTask delegateTask) {
logger.info("查询部门审核人员");
// auditUserInnerServiceSMOImpl = ApplicationContextFactory.getBean("auditUserInnerServiceSMOImpl", IAuditUserInnerServiceSMO.class);
// AuditUserDto auditUserDto = new AuditUserDto();
// PurchaseApplyDto purchaseApplyDto = (PurchaseApplyDto)delegateTask.getVariable("purchaseApplyDto");
String nextAuditStaffId = delegateTask.getVariable("nextAuditStaffId").toString();
/*auditUserDto.setStoreId(purchaseApplyDto.getStoreId());
auditUserDto.setObjCode("resourceEntry");
auditUserDto.setAuditLink("809001");
List<AuditUserDto> auditUserDtos = auditUserInnerServiceSMOImpl.queryAuditUsers(auditUserDto);
for (AuditUserDto tmpAuditUser : auditUserDtos) {
AuditUser auditUser = BeanConvertUtil.covertBean(tmpAuditUser, AuditUser.class);
logger.info("查询到用户:"+tmpAuditUser.getUserName());
delegateTask.setVariable(auditUser.getUserId(), auditUser);
}
logger.info("查询审核人员人数:"+auditUserDtos.size());
if (auditUserDtos == null || auditUserDtos.size() < 1) {
return;
}*/
delegateTask.setAssignee(nextAuditStaffId);
logger.info("设置部门审核人员:"+nextAuditStaffId);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private ResponseEntity<String> savedParkingSpaceInfo(IPageData pd, List<ImportParkingSpace> parkingSpaces, ComponentValidateResult result) {
String apiUrl = "";
JSONObject paramIn = null;
ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功",HttpStatus.OK);
ImportOwner owner = null;
for (ImportParkingSpace parkingSpace : parkingSpaces) {
JSONObject savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace);
if (savedParkingSpaceInfo != null) {
continue;
}
paramIn = new JSONObject();
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.saveParkingSpace";
paramIn.put("communityId", result.getCommunityId());
paramIn.put("userId", result.getUserId());
paramIn.put("num", parkingSpace.getPsNum());
paramIn.put("area", parkingSpace.getArea());
paramIn.put("typeCd", parkingSpace.getTypeCd());
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
continue;
}
savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace);
if (savedParkingSpaceInfo != null) {
continue;
}
//是否有业主信息
if (parkingSpace.getImportOwner() == null) {
continue;
}
paramIn.clear();
paramIn.put("communityId", result.getCommunityId());
paramIn.put("ownerId", parkingSpace.getImportOwner().getOwnerId());
paramIn.put("carNum", parkingSpace.getCarNum());
paramIn.put("carBrand", parkingSpace.getCarBrand());
paramIn.put("carType", parkingSpace.getCarType());
paramIn.put("carColor", parkingSpace.getCarColor());
paramIn.put("psId", savedParkingSpaceInfo.getString("psId"));
paramIn.put("storeId", result.getStoreId());
paramIn.put("sellOrHire", parkingSpace.getSellOrHire());
String feeTypeCd = "1001".equals(parkingSpace.getTypeCd())
? FeeTypeConstant.FEE_TYPE_SELL_UP_PARKING_SPACE : FeeTypeConstant.FEE_TYPE_SELL_DOWN_PARKING_SPACE;
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/fee.queryFeeConfig?communityId=" + result.getCommunityId() + "&feeTypeCd=" + feeTypeCd;
responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
continue;
}
JSONObject configInfo = JSONObject.parseObject(responseEntity.getBody());
if(!configInfo.containsKey("additionalAmount")){
continue;
}
paramIn.put("receivedAmount", configInfo.getString("additionalAmount"));
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.sellParkingSpace";
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
}
return responseEntity;
}
#location 45
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private ResponseEntity<String> savedParkingSpaceInfo(IPageData pd, List<ImportParkingSpace> parkingSpaces, ComponentValidateResult result) {
String apiUrl = "";
JSONObject paramIn = null;
ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK);
ImportOwner owner = null;
for (ImportParkingSpace parkingSpace : parkingSpaces) {
JSONObject savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace);
if (savedParkingSpaceInfo != null) {
continue;
}
paramIn = new JSONObject();
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.saveParkingSpace";
paramIn.put("communityId", result.getCommunityId());
paramIn.put("userId", result.getUserId());
paramIn.put("num", parkingSpace.getPsNum());
paramIn.put("area", parkingSpace.getArea());
paramIn.put("typeCd", parkingSpace.getTypeCd());
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
continue;
}
savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace);
if (savedParkingSpaceInfo == null) {
continue;
}
//是否有业主信息
if (parkingSpace.getImportOwner() == null) {
continue;
}
paramIn.clear();
paramIn.put("communityId", result.getCommunityId());
paramIn.put("ownerId", parkingSpace.getImportOwner().getOwnerId());
paramIn.put("carNum", parkingSpace.getCarNum());
paramIn.put("carBrand", parkingSpace.getCarBrand());
paramIn.put("carType", parkingSpace.getCarType());
paramIn.put("carColor", parkingSpace.getCarColor());
paramIn.put("psId", savedParkingSpaceInfo.getString("psId"));
paramIn.put("storeId", result.getStoreId());
paramIn.put("sellOrHire", parkingSpace.getSellOrHire());
String feeTypeCd = "1001".equals(parkingSpace.getTypeCd())
? FeeTypeConstant.FEE_TYPE_SELL_UP_PARKING_SPACE : FeeTypeConstant.FEE_TYPE_SELL_DOWN_PARKING_SPACE;
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/fee.queryFeeConfig?communityId=" + result.getCommunityId() + "&feeTypeCd=" + feeTypeCd;
responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
continue;
}
JSONObject configInfo = JSONArray.parseArray(responseEntity.getBody()).getJSONObject(0);
if (!configInfo.containsKey("additionalAmount")) {
continue;
}
paramIn.put("receivedAmount", configInfo.getString("additionalAmount"));
apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.sellParkingSpace";
responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST);
}
return responseEntity;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private JSONObject builderStaffInfo(JSONObject paramObj, DataFlowContext dataFlowContext) {
//首先根据员工ID查询员工信息,根据员工信息修改相应的数据
ResponseEntity responseEntity = null;
AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_USERINFO);
if (appService == null) {
throw new ListenerExecuteException(1999, "当前没有权限访问" + ServiceCodeConstant.SERVICE_CODE_QUERY_USER_USERINFO);
}
String requestUrl = appService.getUrl() + "?userId=" + paramObj.getString("userId");
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_USERINFO);
dataFlowContext.getRequestHeaders().put("REQUEST_URL", requestUrl);
HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
doRequest(dataFlowContext, appService, httpEntity);
responseEntity = dataFlowContext.getResponseEntity();
if (responseEntity.getStatusCode() != HttpStatus.OK) {
dataFlowContext.setResponseEntity(responseEntity);
}
JSONObject userInfo = JSONObject.parseObject(responseEntity.getBody().toString());
if (!paramObj.getString("oldPwd").equals(userInfo.getString("password"))) {
throw new IllegalArgumentException("原始密码错误");
}
userInfo.putAll(paramObj);
userInfo.put("password", paramObj.getString("newPwd"));
return userInfo;
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private JSONObject builderStaffInfo(JSONObject paramObj, DataFlowContext dataFlowContext) {
UserDto userDto = new UserDto();
userDto.setStatusCd("0");
userDto.setUserId(paramObj.getString("userId"));
List<UserDto> userDtos = userInnerServiceSMOImpl.getUserHasPwd(userDto);
Assert.listOnlyOne(userDtos, "数据错误查询到多条用户信息或单条");
JSONObject userInfo = JSONObject.parseObject(JSONObject.toJSONString(userDtos.get(0)));
if (!paramObj.getString("oldPwd").equals(userDtos.get(0).getPassword())) {
throw new IllegalArgumentException("原始密码错误");
}
userInfo.putAll(paramObj);
userInfo.put("password", paramObj.getString("newPwd"));
return userInfo;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static List<com.java110.entity.order.Business> getSynchronousBusinesses(IOrderDataFlowContext dataFlow){
AppService service = null;
AppRoute route = null;
List<com.java110.entity.order.Business> syschronousBusinesses = new ArrayList<com.java110.entity.order.Business>();
for(com.java110.entity.order.Business business :dataFlow.getBusinessList()){
if(CommonConstant.ORDER_INVOKE_METHOD_SYNCHRONOUS.equals(business.getInvokeModel()) || StringUtil.isEmpty(business.getInvokeModel())){
business.setSeq(service.getSeq());
syschronousBusinesses.add(business);
}
}
if(syschronousBusinesses.size() > 0) {
Collections.sort(syschronousBusinesses);
}
return syschronousBusinesses;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static List<com.java110.entity.order.Business> getSynchronousBusinesses(IOrderDataFlowContext dataFlow){
List<com.java110.entity.order.Business> syschronousBusinesses = new ArrayList<com.java110.entity.order.Business>();
for(com.java110.entity.order.Business business :dataFlow.getBusinessList()){
if(CommonConstant.ORDER_INVOKE_METHOD_SYNCHRONOUS.equals(business.getInvokeModel()) || StringUtil.isEmpty(business.getInvokeModel())){
syschronousBusinesses.add(business);
}
}
if(syschronousBusinesses.size() > 0) {
Collections.sort(syschronousBusinesses);
}
return syschronousBusinesses;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException {
final ClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, fileManager.getClassLoader(StandardLocation.CLASS_PATH));
final List<Class<?>> classes = new ArrayList<Class<?>>(classFiles.size());
for (final JavaFile classFile : classFiles) {
final Class<?> clazz = loader.loadClass(classFile.getClassName());
classes.add(clazz);
}
return classes;
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException {
final URLClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, fileManager.getClassLoader(StandardLocation.CLASS_PATH));
try {
final List<Class<?>> classes = new ArrayList<Class<?>>(classFiles.size());
for (final JavaFile classFile : classFiles) {
final Class<?> clazz = loader.loadClass(classFile.getClassName());
classes.add(clazz);
}
return classes;
} finally {
try {
loader.close();
} catch (IOException e) {
System.err.println("close failed: " + e);
e.printStackTrace();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException {
final ClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, fileManager.getClassLoader(StandardLocation.CLASS_PATH));
final List<Class<?>> classes = new ArrayList<Class<?>>(classFiles.size());
for (final JavaFile classFile : classFiles) {
final Class<?> clazz = loader.loadClass(classFile.getClassName());
classes.add(clazz);
}
return classes;
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException {
final URLClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, fileManager.getClassLoader(StandardLocation.CLASS_PATH));
try {
final List<Class<?>> classes = new ArrayList<Class<?>>(classFiles.size());
for (final JavaFile classFile : classFiles) {
final Class<?> clazz = loader.loadClass(classFile.getClassName());
classes.add(clazz);
}
return classes;
} finally {
try {
loader.close();
} catch (IOException e) {
System.err.println("close failed: " + e);
e.printStackTrace();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Object call(String method, Object[] params) throws XMLRPCException {
try {
Call c = createCall(method, params);
URLConnection conn = this.url.openConnection();
if(!(conn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("The URL is not for a http connection.");
}
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod(HTTP_POST);
http.setDoOutput(true);
http.setDoInput(true);
// Set the request parameters
for(Map.Entry<String,String> param : httpParameters.entrySet()) {
http.setRequestProperty(param.getKey(), param.getValue());
}
OutputStreamWriter stream = new OutputStreamWriter(http.getOutputStream());
stream.write(c.getXML());
stream.flush();
stream.close();
InputStream istream = http.getInputStream();
if(http.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new XMLRPCException("The status code of the http response must be 200.");
}
// Check for strict parameters
if(isFlagSet(FLAGS_STRICT)) {
if(!http.getContentType().startsWith(TYPE_XML)) {
throw new XMLRPCException("The Content-Type of the response must be text/xml.");
}
}
return responseParser.parse(istream);
} catch (IOException ex) {
throw new XMLRPCException(ex);
}
}
#location 41
#vulnerability type RESOURCE_LEAK
|
#fixed code
public Object call(String method, Object[] params) throws XMLRPCException {
return new Caller().call(method, params);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Object call(String method, Object[] params) throws XMLRPCException {
try {
Call c = createCall(method, params);
URLConnection conn = this.url.openConnection();
if(!(conn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("The URL is not for a http connection.");
}
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod(HTTP_POST);
http.setDoOutput(true);
http.setDoInput(true);
// Set the request parameters
for(Map.Entry<String,String> param : httpParameters.entrySet()) {
http.setRequestProperty(param.getKey(), param.getValue());
}
OutputStreamWriter stream = new OutputStreamWriter(http.getOutputStream());
stream.write(c.getXML());
stream.flush();
stream.close();
InputStream istream = http.getInputStream();
if(http.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new XMLRPCException("The status code of the http response must be 200.");
}
// Check for strict parameters
if(isFlagSet(FLAGS_STRICT)) {
if(!http.getContentType().startsWith(TYPE_XML)) {
throw new XMLRPCException("The Content-Type of the response must be text/xml.");
}
}
return responseParser.parse(istream);
} catch (IOException ex) {
throw new XMLRPCException(ex);
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
public Object call(String method, Object[] params) throws XMLRPCException {
return new Caller().call(method, params);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void canParseMilliseconds() throws Exception {
Date ms500 = (Date) new DateTimeSerializer().deserialize("1985-03-04T12:21:36.5");
assertEquals(500, ms500.getTime() - new Date(85, 2, 4, 12, 21, 36).getTime());
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void canParseMilliseconds() throws Exception {
Date ms500 = (Date) new DateTimeSerializer(false).deserialize("1985-03-04T12:21:36.5");
assertEquals(500, ms500.getTime() - new Date(85, 2, 4, 12, 21, 36).getTime());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Object call(String method, Object[] params) throws XMLRPCException {
try {
Call c = createCall(method, params);
URLConnection conn = this.url.openConnection();
if(!(conn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("The URL is not for a http connection.");
}
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod(HTTP_POST);
http.setDoOutput(true);
http.setDoInput(true);
// Set the request parameters
for(Map.Entry<String,String> param : httpParameters.entrySet()) {
http.setRequestProperty(param.getKey(), param.getValue());
}
OutputStreamWriter stream = new OutputStreamWriter(http.getOutputStream());
stream.write(c.getXML());
stream.flush();
stream.close();
InputStream istream = http.getInputStream();
if(http.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new XMLRPCException("The status code of the http response must be 200.");
}
// Check for strict parameters
if(isFlagSet(FLAGS_STRICT)) {
if(!http.getContentType().startsWith(TYPE_XML)) {
throw new XMLRPCException("The Content-Type of the response must be text/xml.");
}
}
return responseParser.parse(istream);
} catch (IOException ex) {
throw new XMLRPCException(ex);
}
}
#location 41
#vulnerability type RESOURCE_LEAK
|
#fixed code
public Object call(String method, Object[] params) throws XMLRPCException {
return new Caller().call(method, params);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int launch() throws Throwable {
int returnCode = -1;
Thread t = Thread.currentThread();
String currentThreadName = t.getName();
t.setName("Executing "+ env.displayName());
before();
try {
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
ClassLoader cl = new ClassLoaderBuilder(jenkins.getPluginManager().uberClassLoader)
.collectJars(new File(bootstrap.appRepo, "io/jenkins/jenkinsfile-runner/payload"))
.make();
Class<?> c = cl.loadClass("io.jenkins.jenkinsfile.runner.Runner");
returnCode = (int)c.getMethod("run", Bootstrap.class).invoke(c.newInstance(), bootstrap);
} finally {
after();
t.setName(currentThreadName);
}
return returnCode;
}
#location 14
#vulnerability type RESOURCE_LEAK
|
#fixed code
public int launch() throws Throwable {
int returnCode = -1;
Thread t = Thread.currentThread();
String currentThreadName = t.getName();
t.setName("Executing "+ env.displayName());
before();
try {
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
Class<?> c = bootstrap.hasClass(RUNNER_CLASS_NAME)? Class.forName(RUNNER_CLASS_NAME) : getRunnerClassFromJar();
returnCode = (int)c.getMethod("run", Bootstrap.class).invoke(c.newInstance(), bootstrap);
} finally {
after();
t.setName(currentThreadName);
}
return returnCode;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static File explodeWar(String jarPath) throws IOException {
JarFile jarfile = new JarFile(new File(jarPath));
Enumeration<JarEntry> enu = jarfile.entries();
// Get current working directory path
Path currentPath = FileSystems.getDefault().getPath("").toAbsolutePath();
//Create Temporary directory
Path path = Files.createTempDirectory(currentPath.toAbsolutePath(), "jenkinsfile-runner");
File destDir = path.toFile();
while(enu.hasMoreElements()) {
JarEntry je = enu.nextElement();
File file = new File(destDir, je.getName());
if (!file.exists()) {
file.getParentFile().mkdirs();
file = new File(destDir, je.getName());
}
if (je.isDirectory()) {
continue;
}
InputStream is = jarfile.getInputStream(je);
try (FileOutputStream fo = new FileOutputStream(file)) {
while (is.available() > 0) {
fo.write(is.read());
}
fo.close();
is.close();
}
}
return destDir;
}
#location 31
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static File explodeWar(String jarPath) throws IOException {
try (JarFile jarfile = new JarFile(new File(jarPath))) {
Enumeration<JarEntry> enu = jarfile.entries();
// Get current working directory path
Path currentPath = FileSystems.getDefault().getPath("").toAbsolutePath();
//Create Temporary directory
Path path = Files.createTempDirectory(currentPath.toAbsolutePath(), "jenkinsfile-runner");
File destDir = path.toFile();
while (enu.hasMoreElements()) {
JarEntry je = enu.nextElement();
File file = new File(destDir, je.getName());
if (!file.exists()) {
file.getParentFile().mkdirs();
file = new File(destDir, je.getName());
}
if (je.isDirectory()) {
continue;
}
InputStream is = jarfile.getInputStream(je);
try (FileOutputStream fo = new FileOutputStream(file)) {
while (is.available() > 0) {
fo.write(is.read());
}
fo.close();
is.close();
}
}
return destDir;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int run() throws Throwable {
ClassLoader jenkins = createJenkinsWarClassLoader();
ClassLoader setup = createSetupClassLoader(jenkins);
Class<?> c = setup.loadClass("io.jenkins.jenkinsfile.runner.App");
return (int)c.getMethod("run",File.class,File.class).invoke(
c.newInstance(), warDir, pluginsDir
);
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
public int run() throws Throwable {
ClassLoader jenkins = createJenkinsWarClassLoader();
ClassLoader setup = createSetupClassLoader(jenkins);
Thread.currentThread().setContextClassLoader(setup); // or should this be 'jenkins'?
Class<?> c = setup.loadClass("io.jenkins.jenkinsfile.runner.App");
return (int)c.getMethod("run",File.class,File.class).invoke(
c.newInstance(), warDir, pluginsDir
);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static File explodeWar(String jarPath) throws IOException {
JarFile jarfile = new JarFile(new File(jarPath));
Enumeration<JarEntry> enu = jarfile.entries();
// Get current working directory path
Path currentPath = FileSystems.getDefault().getPath("").toAbsolutePath();
//Create Temporary directory
Path path = Files.createTempDirectory(currentPath.toAbsolutePath(), "jenkinsfile-runner");
File destDir = path.toFile();
while(enu.hasMoreElements()) {
JarEntry je = enu.nextElement();
File file = new File(destDir, je.getName());
if (!file.exists()) {
file.getParentFile().mkdirs();
file = new File(destDir, je.getName());
}
if (je.isDirectory()) {
continue;
}
InputStream is = jarfile.getInputStream(je);
try (FileOutputStream fo = new FileOutputStream(file)) {
while (is.available() > 0) {
fo.write(is.read());
}
fo.close();
is.close();
}
}
return destDir;
}
#location 23
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static File explodeWar(String jarPath) throws IOException {
try (JarFile jarfile = new JarFile(new File(jarPath))) {
Enumeration<JarEntry> enu = jarfile.entries();
// Get current working directory path
Path currentPath = FileSystems.getDefault().getPath("").toAbsolutePath();
//Create Temporary directory
Path path = Files.createTempDirectory(currentPath.toAbsolutePath(), "jenkinsfile-runner");
File destDir = path.toFile();
while (enu.hasMoreElements()) {
JarEntry je = enu.nextElement();
File file = new File(destDir, je.getName());
if (!file.exists()) {
file.getParentFile().mkdirs();
file = new File(destDir, je.getName());
}
if (je.isDirectory()) {
continue;
}
InputStream is = jarfile.getInputStream(je);
try (FileOutputStream fo = new FileOutputStream(file)) {
while (is.available() > 0) {
fo.write(is.read());
}
fo.close();
is.close();
}
}
return destDir;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int run() throws Throwable {
ClassLoader jenkins = createJenkinsWarClassLoader();
ClassLoader setup = createSetupClassLoader(jenkins);
Thread.currentThread().setContextClassLoader(setup); // or should this be 'jenkins'?
try {
Class<?> c = setup.loadClass("io.jenkins.jenkinsfile.runner.App");
return ((IApp) c.newInstance()).run(this);
} catch (ClassNotFoundException e) {
if (setup instanceof URLClassLoader) {
throw new ClassNotFoundException(e.getMessage() + " not found in " + appRepo + ","
+ new File(warDir, "WEB-INF/lib") + " " + Arrays.toString(((URLClassLoader) setup).getURLs()),
e);
} else {
throw e;
}
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
public int run() throws Throwable {
String appClassName = "io.jenkins.jenkinsfile.runner.App";
if (hasClass(appClassName)) {
Class<?> c = Class.forName(appClassName);
return ((IApp) c.newInstance()).run(this);
}
ClassLoader jenkins = createJenkinsWarClassLoader();
ClassLoader setup = createSetupClassLoader(jenkins);
Thread.currentThread().setContextClassLoader(setup); // or should this be 'jenkins'?
try {
Class<?> c = setup.loadClass(appClassName);
return ((IApp) c.newInstance()).run(this);
} catch (ClassNotFoundException e) {
if (setup instanceof URLClassLoader) {
throw new ClassNotFoundException(e.getMessage() + " not found in " + getAppRepo() + ","
+ new File(warDir, "WEB-INF/lib") + " " + Arrays.toString(((URLClassLoader) setup).getURLs()),
e);
} else {
throw e;
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void doCreateSlave(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name,
@QueryParameter String description, @QueryParameter int executors,
@QueryParameter String remoteFsRoot, @QueryParameter String labels,
@QueryParameter String secret, @QueryParameter Node.Mode mode,
@QueryParameter(fixEmpty = true) String hash,
@QueryParameter boolean deleteExistingClients) throws IOException {
if (!getSwarmSecret().equals(secret)) {
rsp.setStatus(SC_FORBIDDEN);
return;
}
try {
Jenkins jenkins = Jenkins.getInstance();
jenkins.checkPermission(SlaveComputer.CREATE);
List<NodeProperty<Node>> nodeProperties = new ArrayList<>();
String[] toolLocations = req.getParameterValues("toolLocation");
if (!ArrayUtils.isEmpty(toolLocations)) {
List<ToolLocation> parsedToolLocations = parseToolLocations(toolLocations);
nodeProperties.add(new ToolLocationNodeProperty(parsedToolLocations));
}
String[] environmentVariables = req.getParameterValues("environmentVariable");
if (!ArrayUtils.isEmpty(environmentVariables)) {
List<EnvironmentVariablesNodeProperty.Entry> parsedEnvironmentVariables =
parseEnvironmentVariables(environmentVariables);
nodeProperties.add(
new EnvironmentVariablesNodeProperty(parsedEnvironmentVariables));
}
if (hash == null && jenkins.getNode(name) != null && !deleteExistingClients) {
// this is a legacy client, they won't be able to pick up the new name, so throw them away
// perhaps they can find another master to connect to
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf(
"A slave called '%s' already exists and legacy clients do not support name disambiguation%n",
name);
return;
}
if (hash != null) {
// try to make the name unique. Swarm clients are often replicated VMs, and they may have the same name.
name = name + '-' + hash;
}
// check for existing connections
{
Node n = jenkins.getNode(name);
if (n != null && !deleteExistingClients) {
Computer c = n.toComputer();
if (c != null && c.isOnline()) {
// this is an existing connection, we'll only cause issues
// if we trample over an online connection
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' is already created and on-line%n", name);
return;
}
}
}
SwarmSlave slave =
new SwarmSlave(
name,
"Swarm slave from "
+ req.getRemoteHost()
+ ((description == null || description.isEmpty())
? ""
: (": " + description)),
remoteFsRoot,
String.valueOf(executors),
mode,
"swarm " + Util.fixNull(labels),
nodeProperties);
jenkins.addNode(slave);
rsp.setContentType("text/plain; charset=iso-8859-1");
Properties props = new Properties();
props.put("name", name);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
props.store(bos, "");
byte[] response = bos.toByteArray();
rsp.setContentLength(response.length);
ServletOutputStream outputStream = rsp.getOutputStream();
outputStream.write(response);
outputStream.flush();
} catch (FormException e) {
e.printStackTrace();
}
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void doCreateSlave(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name,
@QueryParameter String description, @QueryParameter int executors,
@QueryParameter String remoteFsRoot, @QueryParameter String labels,
@QueryParameter String secret, @QueryParameter Node.Mode mode,
@QueryParameter(fixEmpty = true) String hash,
@QueryParameter boolean deleteExistingClients) throws IOException {
if (!getSwarmSecret().equals(secret)) {
rsp.setStatus(SC_FORBIDDEN);
return;
}
try {
Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(SlaveComputer.CREATE);
List<NodeProperty<Node>> nodeProperties = new ArrayList<>();
String[] toolLocations = req.getParameterValues("toolLocation");
if (!ArrayUtils.isEmpty(toolLocations)) {
List<ToolLocation> parsedToolLocations = parseToolLocations(toolLocations);
nodeProperties.add(new ToolLocationNodeProperty(parsedToolLocations));
}
String[] environmentVariables = req.getParameterValues("environmentVariable");
if (!ArrayUtils.isEmpty(environmentVariables)) {
List<EnvironmentVariablesNodeProperty.Entry> parsedEnvironmentVariables =
parseEnvironmentVariables(environmentVariables);
nodeProperties.add(
new EnvironmentVariablesNodeProperty(parsedEnvironmentVariables));
}
if (hash == null && jenkins.getNode(name) != null && !deleteExistingClients) {
// this is a legacy client, they won't be able to pick up the new name, so throw them away
// perhaps they can find another master to connect to
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf(
"A slave called '%s' already exists and legacy clients do not support name disambiguation%n",
name);
return;
}
if (hash != null) {
// try to make the name unique. Swarm clients are often replicated VMs, and they may have the same name.
name = name + '-' + hash;
}
// check for existing connections
{
Node n = jenkins.getNode(name);
if (n != null && !deleteExistingClients) {
Computer c = n.toComputer();
if (c != null && c.isOnline()) {
// this is an existing connection, we'll only cause issues
// if we trample over an online connection
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' is already created and on-line%n", name);
return;
}
}
}
SwarmSlave slave =
new SwarmSlave(
name,
"Swarm slave from "
+ req.getRemoteHost()
+ ((description == null || description.isEmpty())
? ""
: (": " + description)),
remoteFsRoot,
String.valueOf(executors),
mode,
"swarm " + Util.fixNull(labels),
nodeProperties);
jenkins.addNode(slave);
rsp.setContentType("text/plain; charset=iso-8859-1");
Properties props = new Properties();
props.put("name", name);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
props.store(bos, "");
byte[] response = bos.toByteArray();
rsp.setContentLength(response.length);
ServletOutputStream outputStream = rsp.getOutputStream();
outputStream.write(response);
outputStream.flush();
} catch (FormException e) {
e.printStackTrace();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Restricted(NoExternalUse.class)
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
Plugin plugin = Jenkins.getInstance().getPlugin("swarm");
if (plugin != null) {
plugin.doDynamic(req, rsp);
}
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Restricted(NoExternalUse.class)
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
Plugin plugin = Jenkins.get().getPlugin("swarm");
if (plugin != null) {
plugin.doDynamic(req, rsp);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressFBWarnings(
value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
justification = "False positive for try-with-resources in Java 11")
public void doSlaveInfo(StaplerRequest req, StaplerResponse rsp) throws IOException {
Jenkins jenkins = Jenkins.getInstance();
jenkins.checkPermission(SlaveComputer.CREATE);
rsp.setContentType("text/xml");
try (Writer w = rsp.getCompressedWriter(req)) {
w.write("<slaveInfo><swarmSecret>" + getSwarmSecret() + "</swarmSecret></slaveInfo>");
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressFBWarnings(
value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
justification = "False positive for try-with-resources in Java 11")
public void doSlaveInfo(StaplerRequest req, StaplerResponse rsp) throws IOException {
Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(SlaveComputer.CREATE);
rsp.setContentType("text/xml");
try (Writer w = rsp.getCompressedWriter(req)) {
w.write("<slaveInfo><swarmSecret>" + getSwarmSecret() + "</swarmSecret></slaveInfo>");
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private Node getNodeByName(String name, StaplerResponse rsp) throws IOException {
Jenkins jenkins = Jenkins.getInstance();
try {
Node n = jenkins.getNode(name);
if (n == null) {
rsp.setStatus(SC_NOT_FOUND);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' does not exist.%n", name);
return null;
}
return n;
} catch (NullPointerException ignored) {}
return null;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private Node getNodeByName(String name, StaplerResponse rsp) throws IOException {
Jenkins jenkins = Jenkins.get();
try {
Node n = jenkins.getNode(name);
if (n == null) {
rsp.setStatus(SC_NOT_FOUND);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' does not exist.%n", name);
return null;
}
return n;
} catch (NullPointerException ignored) {}
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
}
#location 35
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.START)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Starting %s on %s%n", jobId, hosts);
}
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 28
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.START)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Starting %s on %s%n", jobId, hosts);
}
return Utils.setGoalOnHosts(client, out, json, hosts, deployment,
options.getString(tokenArg.getDest()));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void assertDockerReachable(final int probePort) throws Exception {
final DockerClient docker = new DefaultDockerClient(DOCKER_HOST.uri());
try {
docker.inspectImage(BUSYBOX);
} catch (ImageNotFoundException e) {
docker.pull(BUSYBOX);
}
final ContainerConfig config = ContainerConfig.builder()
.image(BUSYBOX)
.cmd("nc", "-p", "4711", "-lle", "cat")
.exposedPorts(ImmutableSet.of("4711/tcp"))
.build();
final HostConfig hostConfig = HostConfig.builder()
.portBindings(ImmutableMap.of("4711/tcp",
asList(PortBinding.of("0.0.0.0", probePort))))
.build();
final ContainerCreation creation = docker.createContainer(config, testTag + "-probe");
final String containerId = creation.id();
docker.startContainer(containerId, hostConfig);
// Wait for container to come up
Polling.await(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
final ContainerInfo info = docker.inspectContainer(containerId);
return info.state().running() ? true : null;
}
});
log.info("Verifying that docker containers are reachable");
try {
Polling.awaitUnchecked(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
log.info("Probing: {}:{}", DOCKER_HOST.address(), probePort);
try (final Socket ignored = new Socket(DOCKER_HOST.address(), probePort)) {
return true;
} catch (IOException e) {
return false;
}
}
});
} catch (TimeoutException e) {
fail("Please ensure that DOCKER_HOST is set to an address that where containers can " +
"be reached. If docker is running in a local VM, DOCKER_HOST must be set to the " +
"address of that VM. If docker can only be reached on a limited port range, " +
"set the environment variable DOCKER_PORT_RANGE=start:end");
}
docker.killContainer(containerId);
}
#location 52
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void assertDockerReachable(final int probePort) throws Exception {
try (final DefaultDockerClient docker = new DefaultDockerClient(DOCKER_HOST.uri())) {
try {
docker.inspectImage(BUSYBOX);
} catch (ImageNotFoundException e) {
docker.pull(BUSYBOX);
}
final ContainerConfig config = ContainerConfig.builder()
.image(BUSYBOX)
.cmd("nc", "-p", "4711", "-lle", "cat")
.exposedPorts(ImmutableSet.of("4711/tcp"))
.build();
final HostConfig hostConfig = HostConfig.builder()
.portBindings(ImmutableMap.of("4711/tcp",
asList(PortBinding.of("0.0.0.0", probePort))))
.build();
final ContainerCreation creation = docker.createContainer(config, testTag + "-probe");
final String containerId = creation.id();
docker.startContainer(containerId, hostConfig);
// Wait for container to come up
Polling.await(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
final ContainerInfo info = docker.inspectContainer(containerId);
return info.state().running() ? true : null;
}
});
log.info("Verifying that docker containers are reachable");
try {
Polling.awaitUnchecked(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
log.info("Probing: {}:{}", DOCKER_HOST.address(), probePort);
try (final Socket ignored = new Socket(DOCKER_HOST.address(), probePort)) {
return true;
} catch (IOException e) {
return false;
}
}
});
} catch (TimeoutException e) {
fail("Please ensure that DOCKER_HOST is set to an address that where containers can " +
"be reached. If docker is running in a local VM, DOCKER_HOST must be set to the " +
"address of that VM. If docker can only be reached on a limited port range, " +
"set the environment variable DOCKER_PORT_RANGE=start:end");
}
docker.killContainer(containerId);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@After
public void baseTeardown() throws Exception {
tearDownJobs();
for (final HeliosClient client : clients) {
client.close();
}
clients.clear();
for (Service service : services) {
try {
service.stopAsync();
} catch (Exception e) {
log.error("Uncaught exception", e);
}
}
for (Service service : services) {
try {
service.awaitTerminated();
} catch (Exception e) {
log.error("Service failed", e);
}
}
services.clear();
// Clean up docker
try {
final DockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri());
final List<Container> containers = dockerClient.listContainers();
for (final Container container : containers) {
for (final String name : container.names()) {
if (name.contains(testTag)) {
try {
dockerClient.killContainer(container.id());
} catch (DockerException e) {
e.printStackTrace();
}
break;
}
}
}
} catch (Exception e) {
log.error("Docker client exception", e);
}
if (zk != null) {
zk.close();
}
listThreads();
}
#location 45
#vulnerability type RESOURCE_LEAK
|
#fixed code
@After
public void baseTeardown() throws Exception {
tearDownJobs();
for (final HeliosClient client : clients) {
client.close();
}
clients.clear();
for (Service service : services) {
try {
service.stopAsync();
} catch (Exception e) {
log.error("Uncaught exception", e);
}
}
for (Service service : services) {
try {
service.awaitTerminated();
} catch (Exception e) {
log.error("Service failed", e);
}
}
services.clear();
// Clean up docker
try (final DefaultDockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri())) {
final List<Container> containers = dockerClient.listContainers();
for (final Container container : containers) {
for (final String name : container.names()) {
if (name.contains(testTag)) {
try {
dockerClient.killContainer(container.id());
} catch (DockerException e) {
e.printStackTrace();
}
break;
}
}
}
} catch (Exception e) {
log.error("Docker client exception", e);
}
if (zk != null) {
zk.close();
}
listThreads();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void verifyAgentReportsDockerVersion() throws Exception {
startDefaultMaster();
startDefaultAgent(testHost());
final HeliosClient client = defaultClient();
final DockerVersion dockerVersion = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<DockerVersion>() {
@Override
public DockerVersion call() throws Exception {
final HostStatus status = client.hostStatus(testHost()).get();
return status == null
? null
: status.getHostInfo() == null
? null
: status.getHostInfo().getDockerVersion();
}
});
final DockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri());
final String expectedDockerVersion = dockerClient.version().version();
assertThat(dockerVersion.getVersion(), is(expectedDockerVersion));
}
#location 21
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void verifyAgentReportsDockerVersion() throws Exception {
startDefaultMaster();
startDefaultAgent(testHost());
final HeliosClient client = defaultClient();
final DockerVersion dockerVersion = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<DockerVersion>() {
@Override
public DockerVersion call() throws Exception {
final HostStatus status = client.hostStatus(testHost()).get();
return status == null
? null
: status.getHostInfo() == null
? null
: status.getHostInfo().getDockerVersion();
}
});
try (final DefaultDockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri())) {
final String expectedDockerVersion = dockerClient.version().version();
assertThat(dockerVersion.getVersion(), is(expectedDockerVersion));
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testDeploymentFailure() throws Exception {
final long start = System.currentTimeMillis();
assertThat(testResult(TempJobFailureTestImpl.class),
hasSingleFailureContaining("AssertionError: Unexpected job state"));
final long end = System.currentTimeMillis();
assertTrue("Test should not time out", (end-start) < Jobs.TIMEOUT_MILLIS);
final byte[] testReport = Files.readAllBytes(reportDir.getRoot().listFiles()[0].toPath());
final TemporaryJobEvent[] events = Json.read(testReport, TemporaryJobEvent[].class);
for (final TemporaryJobEvent event : events) {
if (event.getStep().equals("test")) {
assertFalse("test should be reported as failed", event.isSuccess());
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testDeploymentFailure() throws Exception {
final long start = System.currentTimeMillis();
assertThat(testResult(TempJobFailureTestImpl.class),
hasSingleFailureContaining("AssertionError: Unexpected job state"));
final long end = System.currentTimeMillis();
assertTrue("Test should not time out", (end - start) < Jobs.TIMEOUT_MILLIS);
final byte[] testReport = Files.readAllBytes(REPORT_DIR.getRoot().listFiles()[0].toPath());
final TemporaryJobEvent[] events = Json.read(testReport, TemporaryJobEvent[].class);
for (final TemporaryJobEvent event : events) {
if (event.getStep().equals("test")) {
assertFalse("test should be reported as failed", event.isSuccess());
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReRegisterHost() throws Exception {
ZooKeeperTestingServerManager testingServerManager = null;
try {
testingServerManager = new ZooKeeperTestingServerManager();
testingServerManager.awaitUp(5, TimeUnit.SECONDS);
final ZooKeeperClient zkClient = new DefaultZooKeeperClient(
testingServerManager.curatorWithSuperAuth());
// Register the host & add some fake data to its status & config dirs
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1));
zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1));
final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1));
// ... and then re-register it
final String newId = UUID.randomUUID().toString();
ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId);
// Verify that the host-id was updated
assertEquals(newId, new String(zkClient.getData(idPath)));
// Verify that /status/hosts/<host>/jobs exists and is EMPTY
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)),
contains(Paths.statusHostJobs(HOSTNAME)));
// Verify that re-registering didn't change the nodes in /config/hosts/<host>/jobs
assertEquals(
jobConfigStat,
zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1))
);
} finally {
if (testingServerManager != null) {
testingServerManager.close();
}
}
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReRegisterHost() throws Exception {
// Register the host & add some fake data to its status & config dirs
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1));
zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1));
final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1));
// ... and then re-register it
final String newId = UUID.randomUUID().toString();
ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId);
// Verify that the host-id was updated
assertEquals(newId, new String(zkClient.getData(idPath)));
// Verify that /status/hosts/<host>/jobs exists and is EMPTY
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)),
contains(Paths.statusHostJobs(HOSTNAME)));
// Verify that re-registering didn't change the nodes in /config/hosts/<host>/jobs
assertEquals(
jobConfigStat,
zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1))
);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReRegisterHost() throws Exception {
ZooKeeperTestingServerManager testingServerManager = null;
try {
testingServerManager = new ZooKeeperTestingServerManager();
testingServerManager.awaitUp(5, TimeUnit.SECONDS);
final ZooKeeperClient zkClient = new DefaultZooKeeperClient(
testingServerManager.curatorWithSuperAuth());
// Register the host & add some fake data to its status & config dirs
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1));
zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1));
final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1));
// ... and then re-register it
final String newId = UUID.randomUUID().toString();
ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId);
// Verify that the host-id was updated
assertEquals(newId, new String(zkClient.getData(idPath)));
// Verify that /status/hosts/<host>/jobs exists and is EMPTY
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)),
contains(Paths.statusHostJobs(HOSTNAME)));
// Verify that re-registering didn't change the nodes in /config/hosts/<host>/jobs
assertEquals(
jobConfigStat,
zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1))
);
} finally {
if (testingServerManager != null) {
testingServerManager.close();
}
}
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testReRegisterHost() throws Exception {
// Register the host & add some fake data to its status & config dirs
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1));
zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1));
final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1));
// ... and then re-register it
final String newId = UUID.randomUUID().toString();
ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId);
// Verify that the host-id was updated
assertEquals(newId, new String(zkClient.getData(idPath)));
// Verify that /status/hosts/<host>/jobs exists and is EMPTY
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)),
contains(Paths.statusHostJobs(HOSTNAME)));
// Verify that re-registering didn't change the nodes in /config/hosts/<host>/jobs
assertEquals(
jobConfigStat,
zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1))
);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void assertDockerReachable(final int probePort) throws Exception {
final DockerClient docker = new DefaultDockerClient(DOCKER_HOST.uri());
try {
docker.inspectImage(BUSYBOX);
} catch (ImageNotFoundException e) {
docker.pull(BUSYBOX);
}
final ContainerConfig config = ContainerConfig.builder()
.image(BUSYBOX)
.cmd("nc", "-p", "4711", "-lle", "cat")
.exposedPorts(ImmutableSet.of("4711/tcp"))
.build();
final HostConfig hostConfig = HostConfig.builder()
.portBindings(ImmutableMap.of("4711/tcp",
asList(PortBinding.of("0.0.0.0", probePort))))
.build();
final ContainerCreation creation = docker.createContainer(config, testTag + "-probe");
final String containerId = creation.id();
docker.startContainer(containerId, hostConfig);
// Wait for container to come up
Polling.await(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
final ContainerInfo info = docker.inspectContainer(containerId);
return info.state().running() ? true : null;
}
});
log.info("Verifying that docker containers are reachable");
try {
Polling.awaitUnchecked(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
log.info("Probing: {}:{}", DOCKER_HOST.address(), probePort);
try (final Socket ignored = new Socket(DOCKER_HOST.address(), probePort)) {
return true;
} catch (IOException e) {
return false;
}
}
});
} catch (TimeoutException e) {
fail("Please ensure that DOCKER_HOST is set to an address that where containers can " +
"be reached. If docker is running in a local VM, DOCKER_HOST must be set to the " +
"address of that VM. If docker can only be reached on a limited port range, " +
"set the environment variable DOCKER_PORT_RANGE=start:end");
}
docker.killContainer(containerId);
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void assertDockerReachable(final int probePort) throws Exception {
try (final DefaultDockerClient docker = new DefaultDockerClient(DOCKER_HOST.uri())) {
try {
docker.inspectImage(BUSYBOX);
} catch (ImageNotFoundException e) {
docker.pull(BUSYBOX);
}
final ContainerConfig config = ContainerConfig.builder()
.image(BUSYBOX)
.cmd("nc", "-p", "4711", "-lle", "cat")
.exposedPorts(ImmutableSet.of("4711/tcp"))
.build();
final HostConfig hostConfig = HostConfig.builder()
.portBindings(ImmutableMap.of("4711/tcp",
asList(PortBinding.of("0.0.0.0", probePort))))
.build();
final ContainerCreation creation = docker.createContainer(config, testTag + "-probe");
final String containerId = creation.id();
docker.startContainer(containerId, hostConfig);
// Wait for container to come up
Polling.await(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
final ContainerInfo info = docker.inspectContainer(containerId);
return info.state().running() ? true : null;
}
});
log.info("Verifying that docker containers are reachable");
try {
Polling.awaitUnchecked(5, SECONDS, new Callable<Object>() {
@Override
public Object call() throws Exception {
log.info("Probing: {}:{}", DOCKER_HOST.address(), probePort);
try (final Socket ignored = new Socket(DOCKER_HOST.address(), probePort)) {
return true;
} catch (IOException e) {
return false;
}
}
});
} catch (TimeoutException e) {
fail("Please ensure that DOCKER_HOST is set to an address that where containers can " +
"be reached. If docker is running in a local VM, DOCKER_HOST must be set to the " +
"address of that VM. If docker can only be reached on a limited port range, " +
"set the environment variable DOCKER_PORT_RANGE=start:end");
}
docker.killContainer(containerId);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
final Map<String, List<String>> headers,
final String hostname, final AgentProxy agentProxy,
final Identity identity)
throws IOException {
if (log.isTraceEnabled()) {
log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
Joiner.on(',').withKeyValueSeparator("=").join(headers),
entity.length, Json.asPrettyStringUnchecked(entity));
} else {
log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
}
final URLConnection urlConnection = ipUri.toURL().openConnection();
final HttpURLConnection connection = (HttpURLConnection) urlConnection;
// We verify the TLS certificate against the original hostname since verifying against the
// IP address will fail
if (urlConnection instanceof HttpsURLConnection) {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
connection.setRequestProperty("Host", hostname);
final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String ip, SSLSession sslSession) {
final String tHostname = hostname.endsWith(".") ?
hostname.substring(0, hostname.length() - 1) : hostname;
return new DefaultHostnameVerifier().verify(tHostname, sslSession);
}
});
if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
httpsConnection.setSSLSocketFactory(factory);
}
}
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (final String value : header.getValue()) {
connection.addRequestProperty(header.getKey(), value);
}
}
if (entity.length > 0) {
connection.setDoOutput(true);
connection.getOutputStream().write(entity);
}
if (urlConnection instanceof HttpsURLConnection) {
setRequestMethod(connection, method, true);
} else {
setRequestMethod(connection, method, false);
}
final int responseCode = connection.getResponseCode();
if (responseCode == HTTP_BAD_GATEWAY) {
throw new ConnectException("502 Bad Gateway");
} else if ((responseCode == HTTP_FORBIDDEN) || (responseCode == HTTP_UNAUTHORIZED)) {
throw new SecurityException("Response code: " + responseCode);
}
return connection;
}
#location 61
#vulnerability type RESOURCE_LEAK
|
#fixed code
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
final Map<String, List<String>> headers,
final String hostname, final AgentProxy agentProxy,
final Identity identity)
throws IOException {
if (log.isTraceEnabled()) {
log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
Joiner.on(',').withKeyValueSeparator("=").join(headers),
entity.length, Json.asPrettyStringUnchecked(entity));
} else {
log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
}
final URLConnection urlConnection = ipUri.toURL().openConnection();
final HttpURLConnection connection = (HttpURLConnection) urlConnection;
// We verify the TLS certificate against the original hostname since verifying against the
// IP address will fail
if (urlConnection instanceof HttpsURLConnection) {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
connection.setRequestProperty("Host", hostname);
final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override public boolean verify(String ip, SSLSession sslSession) {
final String tHostname =
hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1) : hostname;
return new DefaultHostnameVerifier().verify(tHostname, sslSession);
}
});
if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
httpsConnection.setSSLSocketFactory(factory);
}
}
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (final String value : header.getValue()) {
connection.addRequestProperty(header.getKey(), value);
}
}
if (entity.length > 0) {
connection.setDoOutput(true);
connection.getOutputStream().write(entity);
}
if (urlConnection instanceof HttpsURLConnection) {
setRequestMethod(connection, method, true);
} else {
setRequestMethod(connection, method, false);
}
final int responseCode = connection.getResponseCode();
if (responseCode == HTTP_BAD_GATEWAY) {
throw new ConnectException("502 Bad Gateway");
}
return connection;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean quiet = options.getBoolean(quietArg.getDest());
final Job.Builder builder;
final String id = options.getString(idArg.getDest());
final String imageIdentifier = options.getString(imageArg.getDest());
// Read job configuration from file
// TODO (dano): look for e.g. Heliosfile in cwd by default?
final String templateJobId = options.getString(templateArg.getDest());
final File file = options.get(fileArg.getDest());
if (file != null && templateJobId != null) {
throw new IllegalArgumentException("Please use only one of -t/--template and -f/--file");
}
if (file != null) {
if (!file.exists() || !file.isFile() || !file.canRead()) {
throw new IllegalArgumentException("Cannot read file " + file);
}
final byte[] bytes = Files.readAllBytes(file.toPath());
final String config = new String(bytes, UTF_8);
final Job job = Json.read(config, Job.class);
builder = job.toBuilder();
} else if (templateJobId != null) {
final Map<JobId, Job> jobs = client.jobs(templateJobId).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.UNKNOWN_JOB, null, null);
out.printf(createJobResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.printf(createJobResponse.toJsonString());
}
return 1;
}
final Job template = Iterables.getOnlyElement(jobs.values());
builder = template.toBuilder();
if (id == null) {
throw new IllegalArgumentException("Please specify new job name and version");
}
} else {
if (id == null || imageIdentifier == null) {
throw new IllegalArgumentException(
"Please specify a file, or a template, or a job name, version and container image");
}
builder = Job.newBuilder();
}
// Merge job configuration options from command line arguments
if (id != null) {
final String[] parts = id.split(":");
switch (parts.length) {
case 3:
builder.setHash(parts[2]);
// fall through
case 2:
builder.setVersion(parts[1]);
// fall through
case 1:
builder.setName(parts[0]);
break;
default:
throw new IllegalArgumentException("Invalid Job id: " + id);
}
}
if (imageIdentifier != null) {
builder.setImage(imageIdentifier);
}
final String hostname = options.getString(hostnameArg.getDest());
if (!isNullOrEmpty(hostname)) {
builder.setHostname(hostname);
}
final List<String> command = options.getList(argsArg.getDest());
if (command != null && !command.isEmpty()) {
builder.setCommand(command);
}
final List<String> envList = options.getList(envArg.getDest());
// TODO (mbrown): does this mean that env config is only added when there is a CLI flag too?
if (!envList.isEmpty()) {
final Map<String, String> env = Maps.newHashMap();
// Add environmental variables from helios job configuration file
env.putAll(builder.getEnv());
// Add environmental variables passed in via CLI
// Overwrite any redundant keys to make CLI args take precedence
env.putAll(parseListOfPairs(envList, "environment variable"));
builder.setEnv(env);
}
Map<String, String> metadata = Maps.newHashMap();
metadata.putAll(defaultMetadata());
final List<String> metadataList = options.getList(metadataArg.getDest());
if (!metadataList.isEmpty()) {
// TODO (mbrown): values from job conf file (which maybe involves dereferencing env vars?)
metadata.putAll(parseListOfPairs(metadataList, "metadata"));
}
builder.setMetadata(metadata);
// Parse port mappings
final List<String> portSpecs = options.getList(portArg.getDest());
final Map<String, PortMapping> explicitPorts = Maps.newHashMap();
final Pattern portPattern = compile("(?<n>[_\\-\\w]+)=(?<i>\\d+)(:(?<e>\\d+))?(/(?<p>\\w+))?");
for (final String spec : portSpecs) {
final Matcher matcher = portPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad port mapping: " + spec);
}
final String portName = matcher.group("n");
final int internal = Integer.parseInt(matcher.group("i"));
final Integer external = nullOrInteger(matcher.group("e"));
final String protocol = fromNullable(matcher.group("p")).or(TCP);
if (explicitPorts.containsKey(portName)) {
throw new IllegalArgumentException("Duplicate port mapping: " + portName);
}
explicitPorts.put(portName, PortMapping.of(internal, external, protocol));
}
// Merge port mappings
final Map<String, PortMapping> ports = Maps.newHashMap();
ports.putAll(builder.getPorts());
ports.putAll(explicitPorts);
builder.setPorts(ports);
// Parse service registrations
final Map<ServiceEndpoint, ServicePorts> explicitRegistration = Maps.newHashMap();
final Pattern registrationPattern =
compile("(?<srv>[a-zA-Z][_\\-\\w]+)(?:/(?<prot>\\w+))?(?:=(?<port>[_\\-\\w]+))?");
final List<String> registrationSpecs = options.getList(registrationArg.getDest());
for (final String spec : registrationSpecs) {
final Matcher matcher = registrationPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad registration: " + spec);
}
final String service = matcher.group("srv");
final String proto = fromNullable(matcher.group("prot")).or(HTTP);
final String optionalPort = matcher.group("port");
final String port;
if (ports.size() == 0) {
throw new IllegalArgumentException("Need port mappings for service registration.");
}
if (optionalPort == null) {
if (ports.size() != 1) {
throw new IllegalArgumentException(
"Need exactly one port mapping for implicit service registration");
}
port = Iterables.getLast(ports.keySet());
} else {
port = optionalPort;
}
explicitRegistration.put(ServiceEndpoint.of(service, proto), ServicePorts.of(port));
}
builder.setRegistrationDomain(options.getString(registrationDomainArg.getDest()));
// Merge service registrations
final Map<ServiceEndpoint, ServicePorts> registration = Maps.newHashMap();
registration.putAll(builder.getRegistration());
registration.putAll(explicitRegistration);
builder.setRegistration(registration);
// Get grace period interval
final Integer gracePeriod = options.getInt(gracePeriodArg.getDest());
if (gracePeriod != null) {
builder.setGracePeriod(gracePeriod);
}
// Parse volumes
final List<String> volumeSpecs = options.getList(volumeArg.getDest());
for (final String spec : volumeSpecs) {
final String[] parts = spec.split(":", 2);
switch (parts.length) {
// Data volume
case 1:
builder.addVolume(parts[0]);
break;
// Bind mount
case 2:
final String path = parts[1];
final String source = parts[0];
builder.addVolume(path, source);
break;
default:
throw new IllegalArgumentException("Invalid volume: " + spec);
}
}
// Parse expires timestamp
final String expires = options.getString(expiresArg.getDest());
if (expires != null) {
// Use DateTime to parse the ISO-8601 string
builder.setExpires(new DateTime(expires).toDate());
}
// Parse health check
final String execString = options.getString(healthCheckExecArg.getDest());
final List<String> execHealthCheck =
(execString == null) ? null : Arrays.asList(execString.split(" "));
final String httpHealthCheck = options.getString(healthCheckHttpArg.getDest());
final String tcpHealthCheck = options.getString(healthCheckTcpArg.getDest());
int numberOfHealthChecks = 0;
for (final String c : asList(httpHealthCheck, tcpHealthCheck)) {
if (!isNullOrEmpty(c)) {
numberOfHealthChecks++;
}
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
numberOfHealthChecks++;
}
if (numberOfHealthChecks > 1) {
throw new IllegalArgumentException("Only one health check may be specified.");
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
builder.setHealthCheck(ExecHealthCheck.of(execHealthCheck));
} else if (!isNullOrEmpty(httpHealthCheck)) {
final String[] parts = httpHealthCheck.split(":", 2);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid HTTP health check: " + httpHealthCheck);
}
builder.setHealthCheck(HttpHealthCheck.of(parts[0], parts[1]));
} else if (!isNullOrEmpty(tcpHealthCheck)) {
builder.setHealthCheck(TcpHealthCheck.of(tcpHealthCheck));
}
final List<String> securityOpt = options.getList(securityOptArg.getDest());
if (securityOpt != null && !securityOpt.isEmpty()) {
builder.setSecurityOpt(securityOpt);
}
final String networkMode = options.getString(networkModeArg.getDest());
if (!isNullOrEmpty(networkMode)) {
builder.setNetworkMode(networkMode);
}
final String token = options.getString(tokenArg.getDest());
if (!isNullOrEmpty(token)) {
builder.setToken(token);
}
// We build without a hash here because we want the hash to be calculated server-side.
// This allows different CLI versions to be cross-compatible with different master versions
// that have either more or fewer job parameters.
final Job job = builder.buildWithoutHash();
final Collection<String> errors = JOB_VALIDATOR.validate(job);
if (!errors.isEmpty()) {
if (!json) {
for (String error : errors) {
out.println(error);
}
} else {
CreateJobResponse createJobResponse = new CreateJobResponse(
CreateJobResponse.Status.INVALID_JOB_DEFINITION, ImmutableList.copyOf(errors),
job.getId().toString());
out.println(createJobResponse.toJsonString());
}
return 1;
}
if (!quiet && !json) {
out.println("Creating job: " + job.toJsonString());
}
final CreateJobResponse status = client.createJob(job).get();
if (status.getStatus() == CreateJobResponse.Status.OK) {
if (!quiet && !json) {
out.println("Done.");
}
if (json) {
out.println(status.toJsonString());
} else {
out.println(status.getId());
}
return 0;
} else {
if (!quiet && !json) {
out.println("Failed: " + status);
} else if (json) {
out.println(status.toJsonString());
}
return 1;
}
}
#location 40
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean quiet = options.getBoolean(quietArg.getDest());
final Job.Builder builder;
final String id = options.getString(idArg.getDest());
final String imageIdentifier = options.getString(imageArg.getDest());
// Read job configuration from file
// TODO (dano): look for e.g. Heliosfile in cwd by default?
final String templateJobId = options.getString(templateArg.getDest());
final File file = options.get(fileArg.getDest());
if (file != null && templateJobId != null) {
throw new IllegalArgumentException("Please use only one of -t/--template and -f/--file");
}
if (file != null) {
if (!file.exists() || !file.isFile() || !file.canRead()) {
throw new IllegalArgumentException("Cannot read file " + file);
}
final byte[] bytes = Files.readAllBytes(file.toPath());
final String config = new String(bytes, UTF_8);
final Job job = Json.read(config, Job.class);
builder = job.toBuilder();
} else if (templateJobId != null) {
final Map<JobId, Job> jobs = client.jobs(templateJobId).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.UNKNOWN_JOB, null, null);
out.print(createJobResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.print(createJobResponse.toJsonString());
}
return 1;
}
final Job template = Iterables.getOnlyElement(jobs.values());
builder = template.toBuilder();
if (id == null) {
throw new IllegalArgumentException("Please specify new job name and version");
}
} else {
if (id == null || imageIdentifier == null) {
throw new IllegalArgumentException(
"Please specify a file, or a template, or a job name, version and container image");
}
builder = Job.newBuilder();
}
// Merge job configuration options from command line arguments
if (id != null) {
final String[] parts = id.split(":");
switch (parts.length) {
case 3:
builder.setHash(parts[2]);
// fall through
case 2:
builder.setVersion(parts[1]);
// fall through
case 1:
builder.setName(parts[0]);
break;
default:
throw new IllegalArgumentException("Invalid Job id: " + id);
}
}
if (imageIdentifier != null) {
builder.setImage(imageIdentifier);
}
final String hostname = options.getString(hostnameArg.getDest());
if (!isNullOrEmpty(hostname)) {
builder.setHostname(hostname);
}
final List<String> command = options.getList(argsArg.getDest());
if (command != null && !command.isEmpty()) {
builder.setCommand(command);
}
final List<String> envList = options.getList(envArg.getDest());
// TODO (mbrown): does this mean that env config is only added when there is a CLI flag too?
if (!envList.isEmpty()) {
final Map<String, String> env = Maps.newHashMap();
// Add environmental variables from helios job configuration file
env.putAll(builder.getEnv());
// Add environmental variables passed in via CLI
// Overwrite any redundant keys to make CLI args take precedence
env.putAll(parseListOfPairs(envList, "environment variable"));
builder.setEnv(env);
}
Map<String, String> metadata = Maps.newHashMap();
metadata.putAll(defaultMetadata());
final List<String> metadataList = options.getList(metadataArg.getDest());
if (!metadataList.isEmpty()) {
// TODO (mbrown): values from job conf file (which maybe involves dereferencing env vars?)
metadata.putAll(parseListOfPairs(metadataList, "metadata"));
}
builder.setMetadata(metadata);
// Parse port mappings
final List<String> portSpecs = options.getList(portArg.getDest());
final Map<String, PortMapping> explicitPorts = Maps.newHashMap();
final Pattern portPattern = compile("(?<n>[_\\-\\w]+)=(?<i>\\d+)(:(?<e>\\d+))?(/(?<p>\\w+))?");
for (final String spec : portSpecs) {
final Matcher matcher = portPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad port mapping: " + spec);
}
final String portName = matcher.group("n");
final int internal = Integer.parseInt(matcher.group("i"));
final Integer external = nullOrInteger(matcher.group("e"));
final String protocol = fromNullable(matcher.group("p")).or(TCP);
if (explicitPorts.containsKey(portName)) {
throw new IllegalArgumentException("Duplicate port mapping: " + portName);
}
explicitPorts.put(portName, PortMapping.of(internal, external, protocol));
}
// Merge port mappings
final Map<String, PortMapping> ports = Maps.newHashMap();
ports.putAll(builder.getPorts());
ports.putAll(explicitPorts);
builder.setPorts(ports);
// Parse service registrations
final Map<ServiceEndpoint, ServicePorts> explicitRegistration = Maps.newHashMap();
final Pattern registrationPattern =
compile("(?<srv>[a-zA-Z][_\\-\\w]+)(?:/(?<prot>\\w+))?(?:=(?<port>[_\\-\\w]+))?");
final List<String> registrationSpecs = options.getList(registrationArg.getDest());
for (final String spec : registrationSpecs) {
final Matcher matcher = registrationPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad registration: " + spec);
}
final String service = matcher.group("srv");
final String proto = fromNullable(matcher.group("prot")).or(HTTP);
final String optionalPort = matcher.group("port");
final String port;
if (ports.size() == 0) {
throw new IllegalArgumentException("Need port mappings for service registration.");
}
if (optionalPort == null) {
if (ports.size() != 1) {
throw new IllegalArgumentException(
"Need exactly one port mapping for implicit service registration");
}
port = Iterables.getLast(ports.keySet());
} else {
port = optionalPort;
}
explicitRegistration.put(ServiceEndpoint.of(service, proto), ServicePorts.of(port));
}
builder.setRegistrationDomain(options.getString(registrationDomainArg.getDest()));
// Merge service registrations
final Map<ServiceEndpoint, ServicePorts> registration = Maps.newHashMap();
registration.putAll(builder.getRegistration());
registration.putAll(explicitRegistration);
builder.setRegistration(registration);
// Get grace period interval
final Integer gracePeriod = options.getInt(gracePeriodArg.getDest());
if (gracePeriod != null) {
builder.setGracePeriod(gracePeriod);
}
// Parse volumes
final List<String> volumeSpecs = options.getList(volumeArg.getDest());
for (final String spec : volumeSpecs) {
final String[] parts = spec.split(":", 2);
switch (parts.length) {
// Data volume
case 1:
builder.addVolume(parts[0]);
break;
// Bind mount
case 2:
final String path = parts[1];
final String source = parts[0];
builder.addVolume(path, source);
break;
default:
throw new IllegalArgumentException("Invalid volume: " + spec);
}
}
// Parse expires timestamp
final String expires = options.getString(expiresArg.getDest());
if (expires != null) {
// Use DateTime to parse the ISO-8601 string
builder.setExpires(new DateTime(expires).toDate());
}
// Parse health check
final String execString = options.getString(healthCheckExecArg.getDest());
final List<String> execHealthCheck =
(execString == null) ? null : Arrays.asList(execString.split(" "));
final String httpHealthCheck = options.getString(healthCheckHttpArg.getDest());
final String tcpHealthCheck = options.getString(healthCheckTcpArg.getDest());
int numberOfHealthChecks = 0;
for (final String c : asList(httpHealthCheck, tcpHealthCheck)) {
if (!isNullOrEmpty(c)) {
numberOfHealthChecks++;
}
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
numberOfHealthChecks++;
}
if (numberOfHealthChecks > 1) {
throw new IllegalArgumentException("Only one health check may be specified.");
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
builder.setHealthCheck(ExecHealthCheck.of(execHealthCheck));
} else if (!isNullOrEmpty(httpHealthCheck)) {
final String[] parts = httpHealthCheck.split(":", 2);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid HTTP health check: " + httpHealthCheck);
}
builder.setHealthCheck(HttpHealthCheck.of(parts[0], parts[1]));
} else if (!isNullOrEmpty(tcpHealthCheck)) {
builder.setHealthCheck(TcpHealthCheck.of(tcpHealthCheck));
}
final List<String> securityOpt = options.getList(securityOptArg.getDest());
if (securityOpt != null && !securityOpt.isEmpty()) {
builder.setSecurityOpt(securityOpt);
}
final String networkMode = options.getString(networkModeArg.getDest());
if (!isNullOrEmpty(networkMode)) {
builder.setNetworkMode(networkMode);
}
final String token = options.getString(tokenArg.getDest());
if (!isNullOrEmpty(token)) {
builder.setToken(token);
}
// We build without a hash here because we want the hash to be calculated server-side.
// This allows different CLI versions to be cross-compatible with different master versions
// that have either more or fewer job parameters.
final Job job = builder.buildWithoutHash();
final Collection<String> errors = JOB_VALIDATOR.validate(job);
if (!errors.isEmpty()) {
if (!json) {
for (String error : errors) {
out.println(error);
}
} else {
CreateJobResponse createJobResponse = new CreateJobResponse(
CreateJobResponse.Status.INVALID_JOB_DEFINITION, ImmutableList.copyOf(errors),
job.getId().toString());
out.println(createJobResponse.toJsonString());
}
return 1;
}
if (!quiet && !json) {
out.println("Creating job: " + job.toJsonString());
}
final CreateJobResponse status = client.createJob(job).get();
if (status.getStatus() == CreateJobResponse.Status.OK) {
if (!quiet && !json) {
out.println("Done.");
}
if (json) {
out.println(status.toJsonString());
} else {
out.println(status.getId());
}
return 0;
} else {
if (!quiet && !json) {
out.println("Failed: " + status);
} else if (json) {
out.println(status.toJsonString());
}
return 1;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException {
final boolean full = options.getBoolean(fullArg.getDest());
final boolean quiet = options.getBoolean(quietArg.getDest());
final String pattern = options.getString(patternArg.getDest());
final boolean deployed = options.getBoolean(deployedArg.getDest());
final Map<JobId, Job> jobs;
if (pattern == null) {
jobs = client.jobs().get();
} else {
jobs = client.jobs(pattern).get();
}
if (!Strings.isNullOrEmpty(pattern) && jobs.isEmpty()) {
if (json) {
out.println(Json.asPrettyStringUnchecked(jobs));
} else if (!quiet) {
out.printf("job pattern %s matched no jobs%n", pattern);
}
return 1;
}
final Map<JobId, ListenableFuture<JobStatus>> oldFutures =
JobStatusFetcher.getJobsStatuses(client, jobs.keySet());
final Map<JobId, ListenableFuture<JobStatus>> futures = Maps.newHashMap();
// maybe filter on deployed jobs
if (!deployed) {
futures.putAll(oldFutures);
} else {
for (final Entry<JobId, ListenableFuture<JobStatus>> e : oldFutures.entrySet()) {
if (!e.getValue().get().getDeployments().isEmpty()) {
futures.put(e.getKey(), e.getValue());
}
}
}
final Set<JobId> sortedJobIds = Sets.newTreeSet(futures.keySet());
if (json) {
if (quiet) {
out.println(Json.asPrettyStringUnchecked(sortedJobIds));
} else {
final Map<JobId, Job> filteredJobs = Maps.newHashMap();
for (final Entry<JobId, Job> entry : jobs.entrySet()) {
if (futures.containsKey(entry.getKey())) {
filteredJobs.put(entry.getKey(), entry.getValue());
}
}
out.println(Json.asPrettyStringUnchecked(filteredJobs));
}
} else {
if (quiet) {
for (final JobId jobId : sortedJobIds) {
out.println(jobId);
}
} else {
final Table table = table(out);
table.row("JOB ID", "NAME", "VERSION", "HOSTS", "COMMAND", "ENVIRONMENT");
for (final JobId jobId : sortedJobIds) {
final Job job = jobs.get(jobId);
final String command = on(' ').join(escape(job.getCommand()));
final String env = Joiner.on(" ").withKeyValueSeparator("=").join(job.getEnv());
final JobStatus status = futures.get(jobId).get();
table.row(full ? jobId : jobId.toShortString(), jobId.getName(), jobId.getVersion(),
status != null ? status.getDeployments().keySet().size() : 0,
command, env);
}
table.print();
}
}
return 0;
}
#location 69
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException {
final boolean full = options.getBoolean(fullArg.getDest());
final boolean quiet = options.getBoolean(quietArg.getDest());
final String pattern = options.getString(patternArg.getDest());
final boolean deployed = options.getBoolean(deployedArg.getDest());
final Map<JobId, Job> jobs;
if (pattern == null) {
jobs = client.jobs().get();
} else {
jobs = client.jobs(pattern).get();
}
if (!Strings.isNullOrEmpty(pattern) && jobs.isEmpty()) {
if (json) {
out.println(Json.asPrettyStringUnchecked(jobs));
} else if (!quiet) {
out.printf("job pattern %s matched no jobs%n", pattern);
}
return 1;
}
final Map<JobId, JobStatus> jobStatuses = getJobStatuses(client, jobs, deployed);
final Set<JobId> sortedJobIds = Sets.newTreeSet(jobStatuses.keySet());
if (json) {
if (quiet) {
out.println(Json.asPrettyStringUnchecked(sortedJobIds));
} else {
final Map<JobId, Job> filteredJobs = Maps.newHashMap();
for (final Entry<JobId, Job> entry : jobs.entrySet()) {
if (jobStatuses.containsKey(entry.getKey())) {
filteredJobs.put(entry.getKey(), entry.getValue());
}
}
out.println(Json.asPrettyStringUnchecked(filteredJobs));
}
} else {
if (quiet) {
for (final JobId jobId : sortedJobIds) {
out.println(jobId);
}
} else {
final Table table = table(out);
table.row("JOB ID", "NAME", "VERSION", "HOSTS", "COMMAND", "ENVIRONMENT");
for (final JobId jobId : sortedJobIds) {
final Job job = jobs.get(jobId);
final String command = on(' ').join(escape(job.getCommand()));
final String env = Joiner.on(" ").withKeyValueSeparator("=").join(job.getEnv());
final JobStatus status = jobStatuses.get(jobId);
table.row(full ? jobId : jobId.toShortString(), jobId.getName(), jobId.getVersion(),
status != null ? status.getDeployments().keySet().size() : 0,
command, env);
}
table.print();
}
}
return 0;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.START)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Starting %s on %s%n", jobId, hosts);
}
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 28
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.START)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Starting %s on %s%n", jobId, hosts);
}
return Utils.setGoalOnHosts(client, out, json, hosts, deployment,
options.getString(tokenArg.getDest()));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean all = options.getBoolean(allArg.getDest());
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
final List<String> hosts;
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (all) {
final JobStatus status = client.jobStatus(jobId).get();
hosts = ImmutableList.copyOf(status.getDeployments().keySet());
if (hosts.isEmpty()) {
out.printf("%s is not currently deployed on any hosts.", jobId);
return 0;
}
if (!yes && !force) {
out.printf("This will undeploy %s from %s%n", jobId, hosts);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
} else {
hosts = options.getList(hostsArg.getDest());
if (hosts.isEmpty()) {
out.println("Please either specify a list of hosts or use the -a/--all flag.");
return 1;
}
}
if (!json) {
out.printf("Undeploying %s from %s%n", jobId, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobUndeployResponse response = client.undeploy(jobId, host, token).get();
if (response.getStatus() == JobUndeployResponse.Status.OK) {
if (!json) {
out.println("done");
} else {
out.printf(response.toJsonString());
}
} else {
if (!json) {
out.println("failed: " + response);
} else {
out.printf(response.toJsonString());
}
code = -1;
}
}
return code;
}
#location 60
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean all = options.getBoolean(allArg.getDest());
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
final List<String> hosts;
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (all) {
final JobStatus status = client.jobStatus(jobId).get();
hosts = ImmutableList.copyOf(status.getDeployments().keySet());
if (hosts.isEmpty()) {
out.printf("%s is not currently deployed on any hosts.", jobId);
return 0;
}
if (!yes && !force) {
out.printf("This will undeploy %s from %s%n", jobId, hosts);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
} else {
hosts = options.getList(hostsArg.getDest());
if (hosts.isEmpty()) {
out.println("Please either specify a list of hosts or use the -a/--all flag.");
return 1;
}
}
if (!json) {
out.printf("Undeploying %s from %s%n", jobId, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobUndeployResponse response = client.undeploy(jobId, host, token).get();
if (response.getStatus() == JobUndeployResponse.Status.OK) {
if (!json) {
out.println("done");
} else {
out.print(response.toJsonString());
}
} else {
if (!json) {
out.println("failed: " + response);
} else {
out.print(response.toJsonString());
}
code = -1;
}
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
}
#location 35
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 14
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static Builder builder(final String profile) {
return new Builder(profile);
}
#location 2
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static Builder builder(final String profile) {
return builder(profile, System.getenv());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final String jobIdString = options.getString(jobArg.getDest());
final Map<JobId, Job> jobs = client.jobs(jobIdString).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.JOB_NOT_FOUND, null, null);
out.printf(jobDeployResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.printf(jobDeployResponse.toJsonString());
}
return 1;
}
final JobId jobId = Iterables.getOnlyElement(jobs.keySet());
return runWithJobId(options, client, out, json, jobId, stdin);
}
#location 15
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final String jobIdString = options.getString(jobArg.getDest());
final Map<JobId, Job> jobs = client.jobs(jobIdString).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.JOB_NOT_FOUND, null, null);
out.print(jobDeployResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.print(jobDeployResponse.toJsonString());
}
return 1;
}
final JobId jobId = Iterables.getOnlyElement(jobs.keySet());
return runWithJobId(options, client, out, json, jobId, stdin);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment job = Deployment.of(jobId,
options.getBoolean(noStartArg.getDest()) ? STOP : START);
if (!json) {
out.printf("Deploying %s on %s%n", job, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
final List<String> resolvedHosts = Lists.newArrayList();
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
resolvedHosts.add(host);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobDeployResponse result = client.deploy(job, host, token).get();
if (result.getStatus() == JobDeployResponse.Status.OK) {
if (!json) {
out.printf("done%n");
} else {
out.printf(result.toJsonString());
}
} else {
if (!json) {
out.printf("failed: %s%n", result);
} else {
out.printf(result.toJsonString());
}
code = 1;
}
}
if (code == 0 && options.getBoolean(watchArg.getDest())) {
JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId),
options.getInt(intervalArg.getDest()), client);
}
return code;
}
#location 31
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment job = Deployment.of(jobId,
options.getBoolean(noStartArg.getDest()) ? STOP : START);
if (!json) {
out.printf("Deploying %s on %s%n", job, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
final List<String> resolvedHosts = Lists.newArrayList();
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
resolvedHosts.add(host);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobDeployResponse result = client.deploy(job, host, token).get();
if (result.getStatus() == JobDeployResponse.Status.OK) {
if (!json) {
out.printf("done%n");
} else {
out.print(result.toJsonString());
}
} else {
if (!json) {
out.printf("failed: %s%n", result);
} else {
out.print(result.toJsonString());
}
code = 1;
}
}
if (code == 0 && options.getBoolean(watchArg.getDest())) {
JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId),
options.getInt(intervalArg.getDest()), client);
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 27
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
return Utils.setGoalOnHosts(client, out, json, hosts, deployment,
options.getString(tokenArg.getDest()));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected ZooKeeperTestManager zooKeeperTestManager() {
return new ZooKeeperTestingServerManager(zooKeeperNamespace);
}
#location 2
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected ZooKeeperTestManager zooKeeperTestManager() {
return new ZooKeeperTestingServerManager();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 14
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
final Map<String, List<String>> headers,
final String hostname)
throws IOException {
if (log.isTraceEnabled()) {
log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
Joiner.on(',').withKeyValueSeparator("=").join(headers),
entity.length, Json.asPrettyStringUnchecked(entity));
} else {
log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
}
final URLConnection urlConnection = ipUri.toURL().openConnection();
final HttpURLConnection connection = (HttpURLConnection) urlConnection;
// We verify the TLS certificate against the original hostname since verifying against the
// IP address will fail
if (urlConnection instanceof HttpsURLConnection) {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
connection.setRequestProperty("Host", hostname);
((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String ip, SSLSession sslSession) {
final String tHostname = hostname.endsWith(".") ?
hostname.substring(0, hostname.length() - 1) : hostname;
return new DefaultHostnameVerifier().verify(tHostname, sslSession);
}
});
}
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (final String value : header.getValue()) {
connection.addRequestProperty(header.getKey(), value);
}
}
if (entity.length > 0) {
connection.setDoOutput(true);
connection.getOutputStream().write(entity);
}
if (urlConnection instanceof HttpsURLConnection) {
setRequestMethod(connection, method, true);
} else {
setRequestMethod(connection, method, false);
}
connection.getResponseCode();
return connection;
}
#location 50
#vulnerability type RESOURCE_LEAK
|
#fixed code
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
final Map<String, List<String>> headers,
final String hostname)
throws IOException {
if (log.isTraceEnabled()) {
log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
Joiner.on(',').withKeyValueSeparator("=").join(headers),
entity.length, Json.asPrettyStringUnchecked(entity));
} else {
log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
}
final URLConnection urlConnection = ipUri.toURL().openConnection();
final HttpURLConnection connection = (HttpURLConnection) urlConnection;
// We verify the TLS certificate against the original hostname since verifying against the
// IP address will fail
if (urlConnection instanceof HttpsURLConnection) {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
connection.setRequestProperty("Host", hostname);
((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String ip, SSLSession sslSession) {
final String tHostname = hostname.endsWith(".") ?
hostname.substring(0, hostname.length() - 1) : hostname;
return new DefaultHostnameVerifier().verify(tHostname, sslSession);
}
});
}
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (final String value : header.getValue()) {
connection.addRequestProperty(header.getKey(), value);
}
}
if (entity.length > 0) {
connection.setDoOutput(true);
connection.getOutputStream().write(entity);
}
if (urlConnection instanceof HttpsURLConnection) {
setRequestMethod(connection, method, true);
} else {
setRequestMethod(connection, method, false);
}
if (connection.getResponseCode() == HTTP_BAD_GATEWAY) {
throw new ConnectException("502 Bad Gateway");
}
return connection;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<String> listRecursive(final String path) throws KeeperException {
assertClusterIdFlagTrue();
// namespace the path since we're using zookeeper directly
final String namespace = emptyToNull(client.getNamespace());
final String namespacedPath = ZKPaths.fixForNamespace(namespace, path);
try {
final List<String> paths = ZKUtil.listSubTreeBFS(
client.getZookeeperClient().getZooKeeper(), namespacedPath);
if (isNullOrEmpty(namespace)) {
return paths;
} else {
// hide the namespace in the paths returned from zookeeper
final ImmutableList.Builder<String> builder = ImmutableList.builder();
for (final String p : paths) {
final String fixed;
if (p.startsWith("/" + namespace)) {
fixed = (p.length() > namespace.length() + 1)
? p.substring(namespace.length() + 1)
: "/";
} else {
fixed = p;
}
builder.add(fixed);
}
return builder.build();
}
} catch (Exception e) {
propagateIfInstanceOf(e, KeeperException.class);
throw propagate(e);
}
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<String> listRecursive(final String path) throws KeeperException {
assertClusterIdFlagTrue();
try {
return ZKUtil.listSubTreeBFS(client.getZookeeperClient().getZooKeeper(), path);
} catch (Exception e) {
propagateIfInstanceOf(e, KeeperException.class);
throw propagate(e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final String jobIdString = options.getString(jobArg.getDest());
final Map<JobId, Job> jobs = client.jobs(jobIdString).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.JOB_NOT_FOUND, null, null);
out.printf(jobDeployResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.printf(jobDeployResponse.toJsonString());
}
return 1;
}
final JobId jobId = Iterables.getOnlyElement(jobs.keySet());
return runWithJobId(options, client, out, json, jobId, stdin);
}
#location 15
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final String jobIdString = options.getString(jobArg.getDest());
final Map<JobId, Job> jobs = client.jobs(jobIdString).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.JOB_NOT_FOUND, null, null);
out.print(jobDeployResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", jobIdString);
} else {
JobDeployResponse jobDeployResponse =
new JobDeployResponse(JobDeployResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.print(jobDeployResponse.toJsonString());
}
return 1;
}
final JobId jobId = Iterables.getOnlyElement(jobs.keySet());
return runWithJobId(options, client, out, json, jobId, stdin);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@After
public void baseTeardown() throws Exception {
tearDownJobs();
for (final HeliosClient client : clients) {
client.close();
}
clients.clear();
for (Service service : services) {
try {
service.stopAsync();
} catch (Exception e) {
log.error("Uncaught exception", e);
}
}
for (Service service : services) {
try {
service.awaitTerminated();
} catch (Exception e) {
log.error("Service failed", e);
}
}
services.clear();
// Clean up docker
try {
final DockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri());
final List<Container> containers = dockerClient.listContainers();
for (final Container container : containers) {
for (final String name : container.names()) {
if (name.contains(testTag)) {
try {
dockerClient.killContainer(container.id());
} catch (DockerException e) {
e.printStackTrace();
}
break;
}
}
}
} catch (Exception e) {
log.error("Docker client exception", e);
}
if (zk != null) {
zk.close();
}
listThreads();
}
#location 46
#vulnerability type RESOURCE_LEAK
|
#fixed code
@After
public void baseTeardown() throws Exception {
tearDownJobs();
for (final HeliosClient client : clients) {
client.close();
}
clients.clear();
for (Service service : services) {
try {
service.stopAsync();
} catch (Exception e) {
log.error("Uncaught exception", e);
}
}
for (Service service : services) {
try {
service.awaitTerminated();
} catch (Exception e) {
log.error("Service failed", e);
}
}
services.clear();
// Clean up docker
try (final DefaultDockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri())) {
final List<Container> containers = dockerClient.listContainers();
for (final Container container : containers) {
for (final String name : container.names()) {
if (name.contains(testTag)) {
try {
dockerClient.killContainer(container.id());
} catch (DockerException e) {
e.printStackTrace();
}
break;
}
}
}
} catch (Exception e) {
log.error("Docker client exception", e);
}
if (zk != null) {
zk.close();
}
listThreads();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment job = Deployment.of(jobId,
options.getBoolean(noStartArg.getDest()) ? STOP : START);
if (!json) {
out.printf("Deploying %s on %s%n", job, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
final List<String> resolvedHosts = Lists.newArrayList();
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
resolvedHosts.add(host);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobDeployResponse result = client.deploy(job, host, token).get();
if (result.getStatus() == JobDeployResponse.Status.OK) {
if (!json) {
out.printf("done%n");
} else {
out.printf(result.toJsonString());
}
} else {
if (!json) {
out.printf("failed: %s%n", result);
} else {
out.printf(result.toJsonString());
}
code = 1;
}
}
if (code == 0 && options.getBoolean(watchArg.getDest())) {
JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId),
options.getInt(intervalArg.getDest()), client);
}
return code;
}
#location 31
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment job = Deployment.of(jobId,
options.getBoolean(noStartArg.getDest()) ? STOP : START);
if (!json) {
out.printf("Deploying %s on %s%n", job, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
final List<String> resolvedHosts = Lists.newArrayList();
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
resolvedHosts.add(host);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobDeployResponse result = client.deploy(job, host, token).get();
if (result.getStatus() == JobDeployResponse.Status.OK) {
if (!json) {
out.printf("done%n");
} else {
out.print(result.toJsonString());
}
} else {
if (!json) {
out.printf("failed: %s%n", result);
} else {
out.print(result.toJsonString());
}
code = 1;
}
}
if (code == 0 && options.getBoolean(watchArg.getDest())) {
JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId),
options.getInt(intervalArg.getDest()), client);
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 27
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
return Utils.setGoalOnHosts(client, out, json, hosts, deployment,
options.getString(tokenArg.getDest()));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
final Map<String, List<String>> headers,
final String hostname)
throws IOException {
if (log.isTraceEnabled()) {
log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
Joiner.on(',').withKeyValueSeparator("=").join(headers),
entity.length, Json.asPrettyStringUnchecked(entity));
} else {
log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
}
final URLConnection urlConnection = ipUri.toURL().openConnection();
final HttpURLConnection connection = (HttpURLConnection) urlConnection;
// We verify the TLS certificate against the original hostname since verifying against the
// IP address will fail
if (urlConnection instanceof HttpsURLConnection) {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
connection.setRequestProperty("Host", hostname);
((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String ip, SSLSession sslSession) {
final String tHostname = hostname.endsWith(".") ?
hostname.substring(0, hostname.length() - 1) : hostname;
return new DefaultHostnameVerifier().verify(tHostname, sslSession);
}
});
}
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (final String value : header.getValue()) {
connection.addRequestProperty(header.getKey(), value);
}
}
if (entity.length > 0) {
connection.setDoOutput(true);
connection.getOutputStream().write(entity);
}
if (urlConnection instanceof HttpsURLConnection) {
setRequestMethod(connection, method, true);
} else {
setRequestMethod(connection, method, false);
}
connection.getResponseCode();
return connection;
}
#location 50
#vulnerability type RESOURCE_LEAK
|
#fixed code
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
final Map<String, List<String>> headers,
final String hostname)
throws IOException {
if (log.isTraceEnabled()) {
log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
Joiner.on(',').withKeyValueSeparator("=").join(headers),
entity.length, Json.asPrettyStringUnchecked(entity));
} else {
log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
}
final URLConnection urlConnection = ipUri.toURL().openConnection();
final HttpURLConnection connection = (HttpURLConnection) urlConnection;
// We verify the TLS certificate against the original hostname since verifying against the
// IP address will fail
if (urlConnection instanceof HttpsURLConnection) {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
connection.setRequestProperty("Host", hostname);
((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String ip, SSLSession sslSession) {
final String tHostname = hostname.endsWith(".") ?
hostname.substring(0, hostname.length() - 1) : hostname;
return new DefaultHostnameVerifier().verify(tHostname, sslSession);
}
});
}
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (final String value : header.getValue()) {
connection.addRequestProperty(header.getKey(), value);
}
}
if (entity.length > 0) {
connection.setDoOutput(true);
connection.getOutputStream().write(entity);
}
if (urlConnection instanceof HttpsURLConnection) {
setRequestMethod(connection, method, true);
} else {
setRequestMethod(connection, method, false);
}
if (connection.getResponseCode() == HTTP_BAD_GATEWAY) {
throw new ConnectException("502 Bad Gateway");
}
return connection;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void test() throws Exception {
startDefaultMaster();
final String id = "test-" + toHexString(new SecureRandom().nextInt());
final String namespace = "helios-" + id;
final String intruder1 = intruder(namespace);
final String intruder2 = intruder(namespace);
// Start a container in the agent namespace
startContainer(intruder1);
// Start agent
final HeliosClient client = defaultClient();
startDefaultAgent(testHost(), "--id=" + id);
awaitHostRegistered(client, testHost(), LONG_WAIT_SECONDS, SECONDS);
awaitHostStatus(client, testHost(), UP, LONG_WAIT_SECONDS, SECONDS);
// With LXC, killing a container results in exit code 0.
// In docker 1.5 killing a container results in exit code 137, in previous versions it's -1.
final List<Integer> expectedExitCodes = docker.info().executionDriver().startsWith("lxc-")
? Collections.singletonList(0) : asList(-1, 137);
// Wait for the agent to kill the container
final ContainerExit exit1 = docker.waitContainer(intruder1);
assertThat(exit1.statusCode(), isIn(expectedExitCodes));
// Start another container in the agent namespace
startContainer(intruder2);
// Wait for the agent to kill the second container as well
final ContainerExit exit2 = docker.waitContainer(intruder2);
assertThat(exit2.statusCode(), isIn(expectedExitCodes));
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void test() throws Exception {
startDefaultMaster();
final String id = "test-" + toHexString(new SecureRandom().nextInt());
final String namespace = "helios-" + id;
final String intruder1 = intruder(namespace);
final String intruder2 = intruder(namespace);
// Start a container in the agent namespace
startContainer(intruder1);
// Start agent
final HeliosClient client = defaultClient();
startDefaultAgent(testHost(), "--id=" + id);
awaitHostRegistered(client, testHost(), LONG_WAIT_SECONDS, SECONDS);
awaitHostStatus(client, testHost(), UP, LONG_WAIT_SECONDS, SECONDS);
// With LXC, killing a container results in exit code 0.
// In docker 1.5 killing a container results in exit code 137, in previous versions it's -1.
final String executionDriver = docker.info().executionDriver();
final List<Integer> expectedExitCodes =
(executionDriver != null && executionDriver.startsWith("lxc-"))
? Collections.singletonList(0) : asList(-1, 137);
// Wait for the agent to kill the container
final ContainerExit exit1 = docker.waitContainer(intruder1);
assertThat(exit1.statusCode(), isIn(expectedExitCodes));
// Start another container in the agent namespace
startContainer(intruder2);
// Wait for the agent to kill the second container as well
final ContainerExit exit2 = docker.waitContainer(intruder2);
assertThat(exit2.statusCode(), isIn(expectedExitCodes));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean quiet = options.getBoolean(quietArg.getDest());
final Job.Builder builder;
final String id = options.getString(idArg.getDest());
final String imageIdentifier = options.getString(imageArg.getDest());
// Read job configuration from file
// TODO (dano): look for e.g. Heliosfile in cwd by default?
final String templateJobId = options.getString(templateArg.getDest());
final File file = options.get(fileArg.getDest());
if (file != null && templateJobId != null) {
throw new IllegalArgumentException("Please use only one of -t/--template and -f/--file");
}
if (file != null) {
if (!file.exists() || !file.isFile() || !file.canRead()) {
throw new IllegalArgumentException("Cannot read file " + file);
}
final byte[] bytes = Files.readAllBytes(file.toPath());
final String config = new String(bytes, UTF_8);
final Job job = Json.read(config, Job.class);
builder = job.toBuilder();
} else if (templateJobId != null) {
final Map<JobId, Job> jobs = client.jobs(templateJobId).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.UNKNOWN_JOB, null, null);
out.printf(createJobResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.printf(createJobResponse.toJsonString());
}
return 1;
}
final Job template = Iterables.getOnlyElement(jobs.values());
builder = template.toBuilder();
if (id == null) {
throw new IllegalArgumentException("Please specify new job name and version");
}
} else {
if (id == null || imageIdentifier == null) {
throw new IllegalArgumentException(
"Please specify a file, or a template, or a job name, version and container image");
}
builder = Job.newBuilder();
}
// Merge job configuration options from command line arguments
if (id != null) {
final String[] parts = id.split(":");
switch (parts.length) {
case 3:
builder.setHash(parts[2]);
// fall through
case 2:
builder.setVersion(parts[1]);
// fall through
case 1:
builder.setName(parts[0]);
break;
default:
throw new IllegalArgumentException("Invalid Job id: " + id);
}
}
if (imageIdentifier != null) {
builder.setImage(imageIdentifier);
}
final String hostname = options.getString(hostnameArg.getDest());
if (!isNullOrEmpty(hostname)) {
builder.setHostname(hostname);
}
final List<String> command = options.getList(argsArg.getDest());
if (command != null && !command.isEmpty()) {
builder.setCommand(command);
}
final List<String> envList = options.getList(envArg.getDest());
// TODO (mbrown): does this mean that env config is only added when there is a CLI flag too?
if (!envList.isEmpty()) {
final Map<String, String> env = Maps.newHashMap();
// Add environmental variables from helios job configuration file
env.putAll(builder.getEnv());
// Add environmental variables passed in via CLI
// Overwrite any redundant keys to make CLI args take precedence
env.putAll(parseListOfPairs(envList, "environment variable"));
builder.setEnv(env);
}
Map<String, String> metadata = Maps.newHashMap();
metadata.putAll(defaultMetadata());
final List<String> metadataList = options.getList(metadataArg.getDest());
if (!metadataList.isEmpty()) {
// TODO (mbrown): values from job conf file (which maybe involves dereferencing env vars?)
metadata.putAll(parseListOfPairs(metadataList, "metadata"));
}
builder.setMetadata(metadata);
// Parse port mappings
final List<String> portSpecs = options.getList(portArg.getDest());
final Map<String, PortMapping> explicitPorts = Maps.newHashMap();
final Pattern portPattern = compile("(?<n>[_\\-\\w]+)=(?<i>\\d+)(:(?<e>\\d+))?(/(?<p>\\w+))?");
for (final String spec : portSpecs) {
final Matcher matcher = portPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad port mapping: " + spec);
}
final String portName = matcher.group("n");
final int internal = Integer.parseInt(matcher.group("i"));
final Integer external = nullOrInteger(matcher.group("e"));
final String protocol = fromNullable(matcher.group("p")).or(TCP);
if (explicitPorts.containsKey(portName)) {
throw new IllegalArgumentException("Duplicate port mapping: " + portName);
}
explicitPorts.put(portName, PortMapping.of(internal, external, protocol));
}
// Merge port mappings
final Map<String, PortMapping> ports = Maps.newHashMap();
ports.putAll(builder.getPorts());
ports.putAll(explicitPorts);
builder.setPorts(ports);
// Parse service registrations
final Map<ServiceEndpoint, ServicePorts> explicitRegistration = Maps.newHashMap();
final Pattern registrationPattern =
compile("(?<srv>[a-zA-Z][_\\-\\w]+)(?:/(?<prot>\\w+))?(?:=(?<port>[_\\-\\w]+))?");
final List<String> registrationSpecs = options.getList(registrationArg.getDest());
for (final String spec : registrationSpecs) {
final Matcher matcher = registrationPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad registration: " + spec);
}
final String service = matcher.group("srv");
final String proto = fromNullable(matcher.group("prot")).or(HTTP);
final String optionalPort = matcher.group("port");
final String port;
if (ports.size() == 0) {
throw new IllegalArgumentException("Need port mappings for service registration.");
}
if (optionalPort == null) {
if (ports.size() != 1) {
throw new IllegalArgumentException(
"Need exactly one port mapping for implicit service registration");
}
port = Iterables.getLast(ports.keySet());
} else {
port = optionalPort;
}
explicitRegistration.put(ServiceEndpoint.of(service, proto), ServicePorts.of(port));
}
builder.setRegistrationDomain(options.getString(registrationDomainArg.getDest()));
// Merge service registrations
final Map<ServiceEndpoint, ServicePorts> registration = Maps.newHashMap();
registration.putAll(builder.getRegistration());
registration.putAll(explicitRegistration);
builder.setRegistration(registration);
// Get grace period interval
final Integer gracePeriod = options.getInt(gracePeriodArg.getDest());
if (gracePeriod != null) {
builder.setGracePeriod(gracePeriod);
}
// Parse volumes
final List<String> volumeSpecs = options.getList(volumeArg.getDest());
for (final String spec : volumeSpecs) {
final String[] parts = spec.split(":", 2);
switch (parts.length) {
// Data volume
case 1:
builder.addVolume(parts[0]);
break;
// Bind mount
case 2:
final String path = parts[1];
final String source = parts[0];
builder.addVolume(path, source);
break;
default:
throw new IllegalArgumentException("Invalid volume: " + spec);
}
}
// Parse expires timestamp
final String expires = options.getString(expiresArg.getDest());
if (expires != null) {
// Use DateTime to parse the ISO-8601 string
builder.setExpires(new DateTime(expires).toDate());
}
// Parse health check
final String execString = options.getString(healthCheckExecArg.getDest());
final List<String> execHealthCheck =
(execString == null) ? null : Arrays.asList(execString.split(" "));
final String httpHealthCheck = options.getString(healthCheckHttpArg.getDest());
final String tcpHealthCheck = options.getString(healthCheckTcpArg.getDest());
int numberOfHealthChecks = 0;
for (final String c : asList(httpHealthCheck, tcpHealthCheck)) {
if (!isNullOrEmpty(c)) {
numberOfHealthChecks++;
}
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
numberOfHealthChecks++;
}
if (numberOfHealthChecks > 1) {
throw new IllegalArgumentException("Only one health check may be specified.");
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
builder.setHealthCheck(ExecHealthCheck.of(execHealthCheck));
} else if (!isNullOrEmpty(httpHealthCheck)) {
final String[] parts = httpHealthCheck.split(":", 2);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid HTTP health check: " + httpHealthCheck);
}
builder.setHealthCheck(HttpHealthCheck.of(parts[0], parts[1]));
} else if (!isNullOrEmpty(tcpHealthCheck)) {
builder.setHealthCheck(TcpHealthCheck.of(tcpHealthCheck));
}
final List<String> securityOpt = options.getList(securityOptArg.getDest());
if (securityOpt != null && !securityOpt.isEmpty()) {
builder.setSecurityOpt(securityOpt);
}
final String networkMode = options.getString(networkModeArg.getDest());
if (!isNullOrEmpty(networkMode)) {
builder.setNetworkMode(networkMode);
}
final String token = options.getString(tokenArg.getDest());
if (!isNullOrEmpty(token)) {
builder.setToken(token);
}
// We build without a hash here because we want the hash to be calculated server-side.
// This allows different CLI versions to be cross-compatible with different master versions
// that have either more or fewer job parameters.
final Job job = builder.buildWithoutHash();
final Collection<String> errors = JOB_VALIDATOR.validate(job);
if (!errors.isEmpty()) {
if (!json) {
for (String error : errors) {
out.println(error);
}
} else {
CreateJobResponse createJobResponse = new CreateJobResponse(
CreateJobResponse.Status.INVALID_JOB_DEFINITION, ImmutableList.copyOf(errors),
job.getId().toString());
out.println(createJobResponse.toJsonString());
}
return 1;
}
if (!quiet && !json) {
out.println("Creating job: " + job.toJsonString());
}
final CreateJobResponse status = client.createJob(job).get();
if (status.getStatus() == CreateJobResponse.Status.OK) {
if (!quiet && !json) {
out.println("Done.");
}
if (json) {
out.println(status.toJsonString());
} else {
out.println(status.getId());
}
return 0;
} else {
if (!quiet && !json) {
out.println("Failed: " + status);
} else if (json) {
out.println(status.toJsonString());
}
return 1;
}
}
#location 40
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
final boolean json, final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean quiet = options.getBoolean(quietArg.getDest());
final Job.Builder builder;
final String id = options.getString(idArg.getDest());
final String imageIdentifier = options.getString(imageArg.getDest());
// Read job configuration from file
// TODO (dano): look for e.g. Heliosfile in cwd by default?
final String templateJobId = options.getString(templateArg.getDest());
final File file = options.get(fileArg.getDest());
if (file != null && templateJobId != null) {
throw new IllegalArgumentException("Please use only one of -t/--template and -f/--file");
}
if (file != null) {
if (!file.exists() || !file.isFile() || !file.canRead()) {
throw new IllegalArgumentException("Cannot read file " + file);
}
final byte[] bytes = Files.readAllBytes(file.toPath());
final String config = new String(bytes, UTF_8);
final Job job = Json.read(config, Job.class);
builder = job.toBuilder();
} else if (templateJobId != null) {
final Map<JobId, Job> jobs = client.jobs(templateJobId).get();
if (jobs.size() == 0) {
if (!json) {
out.printf("Unknown job: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.UNKNOWN_JOB, null, null);
out.print(createJobResponse.toJsonString());
}
return 1;
} else if (jobs.size() > 1) {
if (!json) {
out.printf("Ambiguous job reference: %s%n", templateJobId);
} else {
CreateJobResponse createJobResponse =
new CreateJobResponse(CreateJobResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
out.print(createJobResponse.toJsonString());
}
return 1;
}
final Job template = Iterables.getOnlyElement(jobs.values());
builder = template.toBuilder();
if (id == null) {
throw new IllegalArgumentException("Please specify new job name and version");
}
} else {
if (id == null || imageIdentifier == null) {
throw new IllegalArgumentException(
"Please specify a file, or a template, or a job name, version and container image");
}
builder = Job.newBuilder();
}
// Merge job configuration options from command line arguments
if (id != null) {
final String[] parts = id.split(":");
switch (parts.length) {
case 3:
builder.setHash(parts[2]);
// fall through
case 2:
builder.setVersion(parts[1]);
// fall through
case 1:
builder.setName(parts[0]);
break;
default:
throw new IllegalArgumentException("Invalid Job id: " + id);
}
}
if (imageIdentifier != null) {
builder.setImage(imageIdentifier);
}
final String hostname = options.getString(hostnameArg.getDest());
if (!isNullOrEmpty(hostname)) {
builder.setHostname(hostname);
}
final List<String> command = options.getList(argsArg.getDest());
if (command != null && !command.isEmpty()) {
builder.setCommand(command);
}
final List<String> envList = options.getList(envArg.getDest());
// TODO (mbrown): does this mean that env config is only added when there is a CLI flag too?
if (!envList.isEmpty()) {
final Map<String, String> env = Maps.newHashMap();
// Add environmental variables from helios job configuration file
env.putAll(builder.getEnv());
// Add environmental variables passed in via CLI
// Overwrite any redundant keys to make CLI args take precedence
env.putAll(parseListOfPairs(envList, "environment variable"));
builder.setEnv(env);
}
Map<String, String> metadata = Maps.newHashMap();
metadata.putAll(defaultMetadata());
final List<String> metadataList = options.getList(metadataArg.getDest());
if (!metadataList.isEmpty()) {
// TODO (mbrown): values from job conf file (which maybe involves dereferencing env vars?)
metadata.putAll(parseListOfPairs(metadataList, "metadata"));
}
builder.setMetadata(metadata);
// Parse port mappings
final List<String> portSpecs = options.getList(portArg.getDest());
final Map<String, PortMapping> explicitPorts = Maps.newHashMap();
final Pattern portPattern = compile("(?<n>[_\\-\\w]+)=(?<i>\\d+)(:(?<e>\\d+))?(/(?<p>\\w+))?");
for (final String spec : portSpecs) {
final Matcher matcher = portPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad port mapping: " + spec);
}
final String portName = matcher.group("n");
final int internal = Integer.parseInt(matcher.group("i"));
final Integer external = nullOrInteger(matcher.group("e"));
final String protocol = fromNullable(matcher.group("p")).or(TCP);
if (explicitPorts.containsKey(portName)) {
throw new IllegalArgumentException("Duplicate port mapping: " + portName);
}
explicitPorts.put(portName, PortMapping.of(internal, external, protocol));
}
// Merge port mappings
final Map<String, PortMapping> ports = Maps.newHashMap();
ports.putAll(builder.getPorts());
ports.putAll(explicitPorts);
builder.setPorts(ports);
// Parse service registrations
final Map<ServiceEndpoint, ServicePorts> explicitRegistration = Maps.newHashMap();
final Pattern registrationPattern =
compile("(?<srv>[a-zA-Z][_\\-\\w]+)(?:/(?<prot>\\w+))?(?:=(?<port>[_\\-\\w]+))?");
final List<String> registrationSpecs = options.getList(registrationArg.getDest());
for (final String spec : registrationSpecs) {
final Matcher matcher = registrationPattern.matcher(spec);
if (!matcher.matches()) {
throw new IllegalArgumentException("Bad registration: " + spec);
}
final String service = matcher.group("srv");
final String proto = fromNullable(matcher.group("prot")).or(HTTP);
final String optionalPort = matcher.group("port");
final String port;
if (ports.size() == 0) {
throw new IllegalArgumentException("Need port mappings for service registration.");
}
if (optionalPort == null) {
if (ports.size() != 1) {
throw new IllegalArgumentException(
"Need exactly one port mapping for implicit service registration");
}
port = Iterables.getLast(ports.keySet());
} else {
port = optionalPort;
}
explicitRegistration.put(ServiceEndpoint.of(service, proto), ServicePorts.of(port));
}
builder.setRegistrationDomain(options.getString(registrationDomainArg.getDest()));
// Merge service registrations
final Map<ServiceEndpoint, ServicePorts> registration = Maps.newHashMap();
registration.putAll(builder.getRegistration());
registration.putAll(explicitRegistration);
builder.setRegistration(registration);
// Get grace period interval
final Integer gracePeriod = options.getInt(gracePeriodArg.getDest());
if (gracePeriod != null) {
builder.setGracePeriod(gracePeriod);
}
// Parse volumes
final List<String> volumeSpecs = options.getList(volumeArg.getDest());
for (final String spec : volumeSpecs) {
final String[] parts = spec.split(":", 2);
switch (parts.length) {
// Data volume
case 1:
builder.addVolume(parts[0]);
break;
// Bind mount
case 2:
final String path = parts[1];
final String source = parts[0];
builder.addVolume(path, source);
break;
default:
throw new IllegalArgumentException("Invalid volume: " + spec);
}
}
// Parse expires timestamp
final String expires = options.getString(expiresArg.getDest());
if (expires != null) {
// Use DateTime to parse the ISO-8601 string
builder.setExpires(new DateTime(expires).toDate());
}
// Parse health check
final String execString = options.getString(healthCheckExecArg.getDest());
final List<String> execHealthCheck =
(execString == null) ? null : Arrays.asList(execString.split(" "));
final String httpHealthCheck = options.getString(healthCheckHttpArg.getDest());
final String tcpHealthCheck = options.getString(healthCheckTcpArg.getDest());
int numberOfHealthChecks = 0;
for (final String c : asList(httpHealthCheck, tcpHealthCheck)) {
if (!isNullOrEmpty(c)) {
numberOfHealthChecks++;
}
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
numberOfHealthChecks++;
}
if (numberOfHealthChecks > 1) {
throw new IllegalArgumentException("Only one health check may be specified.");
}
if (execHealthCheck != null && !execHealthCheck.isEmpty()) {
builder.setHealthCheck(ExecHealthCheck.of(execHealthCheck));
} else if (!isNullOrEmpty(httpHealthCheck)) {
final String[] parts = httpHealthCheck.split(":", 2);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid HTTP health check: " + httpHealthCheck);
}
builder.setHealthCheck(HttpHealthCheck.of(parts[0], parts[1]));
} else if (!isNullOrEmpty(tcpHealthCheck)) {
builder.setHealthCheck(TcpHealthCheck.of(tcpHealthCheck));
}
final List<String> securityOpt = options.getList(securityOptArg.getDest());
if (securityOpt != null && !securityOpt.isEmpty()) {
builder.setSecurityOpt(securityOpt);
}
final String networkMode = options.getString(networkModeArg.getDest());
if (!isNullOrEmpty(networkMode)) {
builder.setNetworkMode(networkMode);
}
final String token = options.getString(tokenArg.getDest());
if (!isNullOrEmpty(token)) {
builder.setToken(token);
}
// We build without a hash here because we want the hash to be calculated server-side.
// This allows different CLI versions to be cross-compatible with different master versions
// that have either more or fewer job parameters.
final Job job = builder.buildWithoutHash();
final Collection<String> errors = JOB_VALIDATOR.validate(job);
if (!errors.isEmpty()) {
if (!json) {
for (String error : errors) {
out.println(error);
}
} else {
CreateJobResponse createJobResponse = new CreateJobResponse(
CreateJobResponse.Status.INVALID_JOB_DEFINITION, ImmutableList.copyOf(errors),
job.getId().toString());
out.println(createJobResponse.toJsonString());
}
return 1;
}
if (!quiet && !json) {
out.println("Creating job: " + job.toJsonString());
}
final CreateJobResponse status = client.createJob(job).get();
if (status.getStatus() == CreateJobResponse.Status.OK) {
if (!quiet && !json) {
out.println("Done.");
}
if (json) {
out.println(status.toJsonString());
} else {
out.println(status.getId());
}
return 0;
} else {
if (!quiet && !json) {
out.println("Failed: " + status);
} else if (json) {
out.println(status.toJsonString());
}
return 1;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean all = options.getBoolean(allArg.getDest());
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
final List<String> hosts;
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (all) {
final JobStatus status = client.jobStatus(jobId).get();
hosts = ImmutableList.copyOf(status.getDeployments().keySet());
if (hosts.isEmpty()) {
out.printf("%s is not currently deployed on any hosts.", jobId);
return 0;
}
if (!yes && !force) {
out.printf("This will undeploy %s from %s%n", jobId, hosts);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
} else {
hosts = options.getList(hostsArg.getDest());
if (hosts.isEmpty()) {
out.println("Please either specify a list of hosts or use the -a/--all flag.");
return 1;
}
}
if (!json) {
out.printf("Undeploying %s from %s%n", jobId, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobUndeployResponse response = client.undeploy(jobId, host, token).get();
if (response.getStatus() == JobUndeployResponse.Status.OK) {
if (!json) {
out.println("done");
} else {
out.printf(response.toJsonString());
}
} else {
if (!json) {
out.println("failed: " + response);
} else {
out.printf(response.toJsonString());
}
code = -1;
}
}
return code;
}
#location 60
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final boolean all = options.getBoolean(allArg.getDest());
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
final List<String> hosts;
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (all) {
final JobStatus status = client.jobStatus(jobId).get();
hosts = ImmutableList.copyOf(status.getDeployments().keySet());
if (hosts.isEmpty()) {
out.printf("%s is not currently deployed on any hosts.", jobId);
return 0;
}
if (!yes && !force) {
out.printf("This will undeploy %s from %s%n", jobId, hosts);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
} else {
hosts = options.getList(hostsArg.getDest());
if (hosts.isEmpty()) {
out.println("Please either specify a list of hosts or use the -a/--all flag.");
return 1;
}
}
if (!json) {
out.printf("Undeploying %s from %s%n", jobId, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobUndeployResponse response = client.undeploy(jobId, host, token).get();
if (response.getStatus() == JobUndeployResponse.Status.OK) {
if (!json) {
out.println("done");
} else {
out.print(response.toJsonString());
}
} else {
if (!json) {
out.println("failed: " + response);
} else {
out.print(response.toJsonString());
}
code = -1;
}
}
return code;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void test() throws Exception {
startDefaultMaster();
final Range<Integer> portRange = temporaryPorts.localPortRange("agent1", 2);
final AgentMain agent1 = startDefaultAgent(testHost(), "--port-range=" +
portRange.lowerEndpoint() + ":" +
portRange.upperEndpoint());
final DockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri());
final HeliosClient client = defaultClient();
awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES);
final Map<String, PortMapping> ports1 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort1));
final ImmutableMap<String, PortMapping> expectedMapping1 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint()),
"bar", PortMapping.of(4712, externalPort1));
final Map<String, PortMapping> ports2 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort2));
final ImmutableMap<String, PortMapping> expectedMapping2 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint() + 1),
"bar", PortMapping.of(4712, externalPort2));
final JobId jobId1 = createJob(testJobName + 1, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports1);
assertNotNull(jobId1);
deployJob(jobId1, testHost());
final TaskStatus firstTaskStatus1 = awaitJobState(client, testHost(), jobId1, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
final JobId jobId2 = createJob(testJobName + 2, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports2);
assertNotNull(jobId2);
deployJob(jobId2, testHost());
final TaskStatus firstTaskStatus2 = awaitJobState(client, testHost(), jobId2, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
assertEquals(expectedMapping1, firstTaskStatus1.getPorts());
assertEquals(expectedMapping2, firstTaskStatus2.getPorts());
// TODO (dano): the supervisor should report the allocated ports at all times
// Verify that port allocation is kept across container restarts
dockerClient.killContainer(firstTaskStatus1.getContainerId());
final TaskStatus restartedTaskStatus1 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId1);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus1.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping1, restartedTaskStatus1.getPorts());
// Verify that port allocation is kept across agent restarts
agent1.stopAsync().awaitTerminated();
dockerClient.killContainer(firstTaskStatus2.getContainerId());
startDefaultAgent(testHost());
final TaskStatus restartedTaskStatus2 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId2);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus2.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping2, restartedTaskStatus2.getPorts());
}
#location 64
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void test() throws Exception {
startDefaultMaster();
final Range<Integer> portRange = temporaryPorts.localPortRange("agent1", 2);
final AgentMain agent1 = startDefaultAgent(testHost(), "--port-range=" +
portRange.lowerEndpoint() + ":" +
portRange.upperEndpoint());
try (final DefaultDockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri())) {
final HeliosClient client = defaultClient();
awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES);
final Map<String, PortMapping> ports1 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort1));
final ImmutableMap<String, PortMapping> expectedMapping1 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint()),
"bar", PortMapping.of(4712, externalPort1));
final Map<String, PortMapping> ports2 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort2));
final ImmutableMap<String, PortMapping> expectedMapping2 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint() + 1),
"bar", PortMapping.of(4712, externalPort2));
final JobId jobId1 = createJob(testJobName + 1, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports1);
assertNotNull(jobId1);
deployJob(jobId1, testHost());
final TaskStatus firstTaskStatus1 = awaitJobState(client, testHost(), jobId1, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
final JobId jobId2 = createJob(testJobName + 2, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports2);
assertNotNull(jobId2);
deployJob(jobId2, testHost());
final TaskStatus firstTaskStatus2 = awaitJobState(client, testHost(), jobId2, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
assertEquals(expectedMapping1, firstTaskStatus1.getPorts());
assertEquals(expectedMapping2, firstTaskStatus2.getPorts());
// TODO (dano): the supervisor should report the allocated ports at all times
// Verify that port allocation is kept across container restarts
dockerClient.killContainer(firstTaskStatus1.getContainerId());
final TaskStatus restartedTaskStatus1 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId1);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus1.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping1, restartedTaskStatus1.getPorts());
// Verify that port allocation is kept across agent restarts
agent1.stopAsync().awaitTerminated();
dockerClient.killContainer(firstTaskStatus2.getContainerId());
startDefaultAgent(testHost());
final TaskStatus restartedTaskStatus2 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId2);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus2.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping2, restartedTaskStatus2.getPorts());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id,
final CountDownLatch zkRegistrationSignal) {
ACLProvider aclProvider = null;
List<AuthInfo> authorization = null;
if (config.isZooKeeperEnableAcls()) {
final String agentUser = config.getZookeeperAclAgentUser();
final String agentPassword = config.getZooKeeperAclAgentPassword();
final String masterUser = config.getZookeeperAclMasterUser();
final String masterDigest = config.getZooKeeperAclMasterDigest();
if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentPassword)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but agent username and/or password not set");
}
if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterDigest)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but master username and/or digest not set");
}
aclProvider = heliosAclProvider(
masterUser, masterDigest,
agentUser, digest(agentUser, agentPassword));
authorization = Lists.newArrayList(new AuthInfo(
"digest", String.format("%s:%s", agentUser, agentPassword).getBytes()));
}
final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework curator = new CuratorClientFactoryImpl().newClient(
config.getZooKeeperConnectionString(),
config.getZooKeeperSessionTimeoutMillis(),
config.getZooKeeperConnectionTimeoutMillis(),
zooKeeperRetryPolicy,
config.getZooKeeperNamespace(),
aclProvider,
authorization);
final ZooKeeperClient client = new DefaultZooKeeperClient(curator,
config.getZooKeeperClusterId());
client.start();
// Register the agent
zkRegistrar = new ZooKeeperRegistrarService(
client,
new AgentZooKeeperRegistrar(this, config.getName(),
id, config.getZooKeeperRegistrationTtlMinutes()),
zkRegistrationSignal);
return client;
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id,
final CountDownLatch zkRegistrationSignal) {
ACLProvider aclProvider = null;
List<AuthInfo> authorization = null;
if (config.isZooKeeperEnableAcls()) {
final String agentUser = config.getZookeeperAclAgentUser();
final String agentPassword = config.getZooKeeperAclAgentPassword();
final String masterUser = config.getZookeeperAclMasterUser();
final String masterDigest = config.getZooKeeperAclMasterDigest();
if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentPassword)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but agent username and/or password not set");
}
if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterDigest)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but master username and/or digest not set");
}
aclProvider = heliosAclProvider(
masterUser, masterDigest,
agentUser, digest(agentUser, agentPassword));
authorization = Lists.newArrayList(new AuthInfo(
"digest", String.format("%s:%s", agentUser, agentPassword).getBytes()));
}
final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework curator = new CuratorClientFactoryImpl().newClient(
config.getZooKeeperConnectionString(),
config.getZooKeeperSessionTimeoutMillis(),
config.getZooKeeperConnectionTimeoutMillis(),
zooKeeperRetryPolicy,
aclProvider,
authorization);
final ZooKeeperClient client = new DefaultZooKeeperClient(curator,
config.getZooKeeperClusterId());
client.start();
// Register the agent
zkRegistrar = new ZooKeeperRegistrarService(
client,
new AgentZooKeeperRegistrar(this, config.getName(),
id, config.getZooKeeperRegistrationTtlMinutes()),
zkRegistrationSignal);
return client;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static String getHeader() {
return getHeader(WebUtil.getRequest());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static String getHeader() {
return getHeader(Objects.requireNonNull(WebUtil.getRequest()));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean deleteLogic(@NotEmpty List<Integer> ids) {
BladeUser user = SecureUtil.getUser();
T entity = BeanUtil.newInstance(modelClass);
entity.setUpdateUser(user.getUserId());
entity.setUpdateTime(LocalDateTime.now());
return super.update(entity, Wrappers.<T>update().lambda().in(T::getId, ids)) && super.removeByIds(ids);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public boolean deleteLogic(@NotEmpty List<Integer> ids) {
BladeUser user = SecureUtil.getUser();
T entity = BeanUtil.newInstance(modelClass);
entity.setUpdateUser(Objects.requireNonNull(user).getUserId());
entity.setUpdateTime(LocalDateTime.now());
return super.removeByIds(ids);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static BladeUser getUser() {
return getUser(WebUtil.getRequest());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static BladeUser getUser() {
HttpServletRequest request = WebUtil.getRequest();
// 优先从 request 中获取
BladeUser bladeUser = (BladeUser) request.getAttribute(BLADE_USER_REQUEST_ATTR);
if (bladeUser == null) {
bladeUser = getUser(request);
if (bladeUser != null) {
// 设置到 request 中
request.setAttribute(BLADE_USER_REQUEST_ATTR, bladeUser);
}
}
return bladeUser;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean updateById(T entity) {
BladeUser user = SecureUtil.getUser();
entity.setUpdateUser(user.getUserId());
entity.setUpdateTime(LocalDateTime.now());
return super.updateById(entity);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public boolean updateById(T entity) {
BladeUser user = SecureUtil.getUser();
entity.setUpdateUser(Objects.requireNonNull(user).getUserId());
entity.setUpdateTime(LocalDateTime.now());
return super.updateById(entity);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean save(T entity) {
BladeUser user = SecureUtil.getUser();
LocalDateTime now = LocalDateTime.now();
entity.setCreateUser(Objects.requireNonNull(user).getUserId());
entity.setCreateTime(now);
entity.setUpdateUser(user.getUserId());
entity.setUpdateTime(now);
entity.setStatus(BladeConstant.DB_STATUS_NORMAL);
entity.setIsDeleted(BladeConstant.DB_NOT_DELETED);
return super.save(entity);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public boolean save(T entity) {
BladeUser user = SecureUtil.getUser();
if (user != null) {
entity.setCreateUser(user.getUserId());
entity.setUpdateUser(user.getUserId());
}
LocalDateTime now = LocalDateTime.now();
entity.setCreateTime(now);
entity.setUpdateTime(now);
if (entity.getStatus() == null) {
entity.setStatus(BladeConstant.DB_STATUS_NORMAL);
}
entity.setIsDeleted(BladeConstant.DB_NOT_DELETED);
return super.save(entity);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static <T extends INode> List<T> merge(List<T> items) {
ForestNodeManager<T> forestNodeManager = new ForestNodeManager<>(items);
for (T forestNode : items) {
if (forestNode.getParentId() != 0) {
INode node = forestNodeManager.getTreeNodeAT(forestNode.getParentId());
node.getChildren().add(forestNode);
}
}
return forestNodeManager.getRoot();
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static <T extends INode> List<T> merge(List<T> items) {
List<Integer> parentIds = new ArrayList<>();
ForestNodeManager<T> forestNodeManager = new ForestNodeManager<>(items);
items.forEach(forestNode -> {
if (forestNode.getParentId() != 0) {
INode node = forestNodeManager.getTreeNodeAT(forestNode.getParentId());
if (node != null) {
node.getChildren().add(forestNode);
} else {
forestNodeManager.addParentId(forestNode.getId());
}
}
});
return forestNodeManager.getRoot();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Result<com.belerweb.social.weibo.bean.User> show(String source, String accessToken,
String uid, String screenName) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addNotNullParameter(params, "uid", uid);
weibo.addNotNullParameter(params, "screen_name", screenName);
String json = weibo.post("https://api.weibo.com/2/users/show.json", params);
return Result.perse(json, com.belerweb.social.weibo.bean.User.class);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Result<com.belerweb.social.weibo.bean.User> show(String source, String accessToken,
String uid, String screenName) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addNotNullParameter(params, "uid", uid);
weibo.addNotNullParameter(params, "screen_name", screenName);
String json = weibo.post("https://api.weibo.com/2/users/show.json", params);
return Result.parse(json, com.belerweb.social.weibo.bean.User.class);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Result<UserCounts> counts(String source, String accessToken, List<String> uids) {
if (uids == null || uids.size() > 100) {
throw new SocialException("需要获取数据的用户UID,必须且最多不超过100个");
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addParameter(params, "uids", StringUtils.join(uids, ","));
String result = weibo.post("https://api.weibo.com/2/users/domain_show.json", params);
return Result.perse(result, UserCounts.class);
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Result<UserCounts> counts(String source, String accessToken, List<String> uids) {
if (uids == null || uids.size() > 100) {
throw new SocialException("需要获取数据的用户UID,必须且最多不超过100个");
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addParameter(params, "uids", StringUtils.join(uids, ","));
String result = weibo.post("https://api.weibo.com/2/users/domain_show.json", params);
return Result.parse(result, UserCounts.class);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType,
String code, String redirectUri) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "client_id", clientId);
weibo.addParameter(params, "client_secret", clientSecret);
weibo.addParameter(params, "grant_type", grantType);
if ("authorization_code".equals(grantType)) {
weibo.addParameter(params, "code", code);
weibo.addParameter(params, "redirect_uri", redirectUri);
}
String result = weibo.post("https://api.weibo.com/oauth2/access_token", params);
return Result.perse(result, AccessToken.class);
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType,
String code, String redirectUri) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "client_id", clientId);
weibo.addParameter(params, "client_secret", clientSecret);
weibo.addParameter(params, "grant_type", grantType);
if ("authorization_code".equals(grantType)) {
weibo.addParameter(params, "code", code);
weibo.addParameter(params, "redirect_uri", redirectUri);
}
String result = weibo.post("https://api.weibo.com/oauth2/access_token", params);
return Result.parse(result, AccessToken.class);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Result<com.belerweb.social.weibo.bean.User> domainShow(String source, String accessToken,
String domain) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addParameter(params, "domain", domain);
String json = weibo.post("https://api.weibo.com/2/users/domain_show.json", params);
return Result.perse(json, com.belerweb.social.weibo.bean.User.class);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Result<com.belerweb.social.weibo.bean.User> domainShow(String source, String accessToken,
String domain) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addParameter(params, "domain", domain);
String json = weibo.post("https://api.weibo.com/2/users/domain_show.json", params);
return Result.parse(json, com.belerweb.social.weibo.bean.User.class);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Result<AccessToken> refreshAccessToken(String clientId, String clientSecret,
String grantType, String refreshToken, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "refresh_token", refreshToken);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params);
String[] results = result.split("\\&");
JSONObject jsonObject = new JSONObject();
for (String param : results) {
String[] keyValue = param.split("\\=");
jsonObject.put(keyValue[0], keyValue.length > 0 ? keyValue[1] : null);
}
String errorCode = jsonObject.optString("code", null);
if (errorCode != null) {
jsonObject.put("ret", errorCode);// To match Error.parse()
}
return Result.parse(jsonObject, AccessToken.class);
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Result<AccessToken> refreshAccessToken(String clientId, String clientSecret,
String grantType, String refreshToken, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "refresh_token", refreshToken);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params);
return parseAccessTokenResult(result);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType,
String code, String redirectUri, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "code", code);
connect.addParameter(params, "redirect_uri", redirectUri);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params);
String[] results = result.split("\\&");
JSONObject jsonObject = new JSONObject();
for (String param : results) {
String[] keyValue = param.split("\\=");
jsonObject.put(keyValue[0], keyValue.length > 0 ? keyValue[1] : null);
}
String errorCode = jsonObject.optString("code", null);
if (errorCode != null) {
jsonObject.put("ret", errorCode);// To match Error.parse()
}
return Result.parse(jsonObject, AccessToken.class);
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType,
String code, String redirectUri, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "code", code);
connect.addParameter(params, "redirect_uri", redirectUri);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params).trim();
return parseAccessTokenResult(result);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testUserInfo() {
String accessToken = System.getProperty("weixin.atoken");
String openId = System.getProperty("weixin.openid");
Result<com.belerweb.social.weixin.bean.User> result =
weixin.getUser().userInfo(accessToken, openId);
Assert.assertTrue(result.success());
System.out.println(result.getResult().getJsonObject());
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testUserInfo() {
String openId = System.getProperty("weixin.openid");
Result<com.belerweb.social.weixin.bean.User> result =
weixin.getUser().userInfo(weixin.getAccessToken().getToken(), openId);
Assert.assertTrue(result.success());
System.out.println(result.getResult().getJsonObject());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Result<TokenInfo> getTokenInfo(String accessToken) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "access_token", accessToken);
String result = weibo.post("https://api.weibo.com/oauth2/get_token_info", params);
return Result.perse(result, TokenInfo.class);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Result<TokenInfo> getTokenInfo(String accessToken) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "access_token", accessToken);
String result = weibo.post("https://api.weibo.com/oauth2/get_token_info", params);
return Result.parse(result, TokenInfo.class);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final TeeRequest request = new TeeRequest(httpRequest);
final TeeResponse response = new TeeResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
#location 10
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final RemoteRequest request = new RemoteRequest(httpRequest);
final LocalResponse response = new LocalResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final TeeRequest request = new TeeRequest(httpRequest);
final TeeResponse response = new TeeResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
#location 20
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final RemoteRequest request = new RemoteRequest(httpRequest);
final LocalResponse response = new LocalResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final TeeRequest request = new TeeRequest(httpRequest);
final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request);
if (correlator.isPresent()) {
final TeeResponse response = new TeeResponse(httpResponse);
chain.doFilter(request, response);
response.getWriter().flush();
logResponse(correlator.get(), request, response);
} else {
chain.doFilter(httpRequest, httpResponse);
}
}
#location 13
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final RemoteRequest request = new RemoteRequest(httpRequest);
final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request);
if (correlator.isPresent()) {
final LocalResponse response = new LocalResponse(httpResponse);
chain.doFilter(request, response);
response.getWriter().flush();
logResponse(correlator.get(), request, response);
} else {
chain.doFilter(httpRequest, httpResponse);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final TeeRequest request = new TeeRequest(httpRequest);
final TeeResponse response = new TeeResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final RemoteRequest request = new RemoteRequest(httpRequest);
final LocalResponse response = new LocalResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void shouldUseSameBody() throws IOException {
final HttpServletResponse mock = mock(HttpServletResponse.class);
when(mock.getOutputStream()).thenReturn(new ServletOutputStream() {
@Override
public void write(final int b) throws IOException {
}
});
final LocalResponse response = new LocalResponse(mock, "1");
response.getOutputStream().write("test".getBytes());
final byte[] body1 = response.getBody();
final byte[] body2 = response.getBody();
assertSame(body1, body2);
}
#location 14
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void shouldUseSameBody() throws IOException {
unit.getOutputStream().write("test".getBytes());
final byte[] body1 = unit.getBody();
final byte[] body2 = unit.getBody();
assertSame(body1, body2);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public HttpRequest withBody() throws IOException {
body = ByteStreams.toByteArray(getInputStream());
return this;
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public HttpRequest withBody() throws IOException {
body = ByteStreams.toByteArray(super.getInputStream());
return this;
}
|
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.