instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void addNonCachedMetricsListener(CuratorFramework curatorFramework) {
nonCachedMetricsIPRWLock = new InterProcessReadWriteLock(curatorFramework, NON_CACHED_METRICS_LOCK_PATH);
testIPRWLock(curatorFramework, nonCachedMetricsIPRWLock, NON_CACHED_METRICS_LOCK_PATH);
nonCachedMetricsIP = new DistributedAtomicValue(curatorFramework, NON_CACHED_METRICS, new RetryForever(1000));
TreeCacheListener nonCachedMetricsListener = new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
LOG.info("Handling nonCachedMetricsIP event {}", event.getType().toString());
readNonCachedMetricsIP();
}
}
};
try (TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS)) {
nonCachedMetricsTreeCache.getListenable().addListener(nonCachedMetricsListener);
nonCachedMetricsTreeCache.start();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
|
#vulnerable code
private void addNonCachedMetricsListener(CuratorFramework curatorFramework) {
nonCachedMetricsIPRWLock = new InterProcessReadWriteLock(curatorFramework, NON_CACHED_METRICS_LOCK_PATH);
testIPRWLock(curatorFramework, nonCachedMetricsIPRWLock, NON_CACHED_METRICS_LOCK_PATH);
nonCachedMetricsIP = new DistributedAtomicValue(curatorFramework, NON_CACHED_METRICS, new RetryForever(1000));
TreeCacheListener nonCachedMetricsListener = new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
LOG.info("Handling nonCachedMetricsIP event {}", event.getType().toString());
readNonCachedMetricsIP();
}
}
};
try {
TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS);
nonCachedMetricsTreeCache.getListenable().addListener(nonCachedMetricsListener);
nonCachedMetricsTreeCache.start();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void track1NameTest() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getHolderFirstname()).isEqualTo("John");
Assertions.assertThat(track1.getHolderLastname()).isEqualTo("Doe");
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
#vulnerable code
@Test
public void track1NameTest() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("563A42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F30303030"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getHolderFirstname()).isEqualTo("John");
Assertions.assertThat(card.getTrack1().getHolderLastname()).isEqualTo("Doe");
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testRefs()
{
List<String> failed = TestInference.testAll("tests", false);
if (failed != null)
{
String msg = "Some tests failed. " +
"\nLook at 'failed_refs.json' in corresponding directories for details.";
msg += "\n----------------------------= FAILED TESTS --------------------------=";
for (String fail : failed)
{
msg += "\n - " + fail;
}
msg += "\n----------------------------------------------------------------------";
fail(msg);
}
}
|
#vulnerable code
@Test
public void testRefs()
{
List<String> failed = TestInference.testAll("tests", false);
String msg = "";
for (String fail : failed)
{
msg += "[failed] " + fail;
}
assertTrue("Some tests failed :\n" + msg, failed == null);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "@";
break;
default:
Util.msg("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
|
#vulnerable code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "&";
break;
default:
System.err.println("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getSingle().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getSingle();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
|
#vulnerable code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getFirstNode().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getFirstNode();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
String[] list(String... names) {
return names;
}
|
#vulnerable code
void buildTupleType() {
Scope bt = BaseTuple.getTable();
String[] tuple_methods = {
"__add__", "__contains__", "__eq__", "__ge__", "__getnewargs__",
"__gt__", "__iter__", "__le__", "__len__", "__lt__", "__mul__",
"__ne__", "__new__", "__rmul__", "count", "index"
};
for (String m : tuple_methods) {
bt.update(m, newLibUrl("stdtypes"), newFunc(), METHOD);
}
Binding b = bt.update("__getslice__", newDataModelUrl("object.__getslice__"),
newFunc(), METHOD);
b.markDeprecated();
bt.update("__getitem__", newDataModelUrl("object.__getitem__"), newFunc(), METHOD);
bt.update("__iter__", newDataModelUrl("object.__iter__"), newFunc(), METHOD);
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int compareTo(@NotNull Object o) {
return getSingle().getStart() - ((Binding)o).getSingle().getStart();
}
|
#vulnerable code
public int compareTo(@NotNull Object o) {
return getFirstNode().getStart() - ((Binding)o).getFirstNode().getStart();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void bindIter(@NotNull Scope s, Node target, @NotNull Node iter, Binding.Kind kind) {
Type iterType = Node.resolveExpr(iter, s);
if (iterType.isListType()) {
bind(s, target, iterType.asListType().getElementType(), kind);
} else if (iterType.isTupleType()) {
bind(s, target, iterType.asTupleType().toListType().getElementType(), kind);
} else {
List<Binding> ents = iterType.getTable().lookupAttr("__iter__");
if (ents != null) {
for (Binding ent : ents) {
if (ent.getType().isFuncType()) {
bind(s, target, ent.getType().asFuncType().getReturnType(), kind);
} else {
iter.addWarning("not an iterable type: " + iterType);
bind(s, target, Indexer.idx.builtins.unknown, kind);
}
}
}
}
}
|
#vulnerable code
public static void bindIter(@NotNull Scope s, Node target, @NotNull Node iter, Binding.Kind kind) {
Type iterType = Node.resolveExpr(iter, s);
if (iterType.isListType()) {
bind(s, target, iterType.asListType().getElementType(), kind);
} else if (iterType.isTupleType()) {
bind(s, target, iterType.asTupleType().toListType().getElementType(), kind);
} else {
List<Binding> ents = iterType.getTable().lookupAttr("__iter__");
for (Binding ent : ents) {
if (ent == null || !ent.getType().isFuncType()) {
if (!iterType.isUnknownType()) {
iter.addWarning("not an iterable type: " + iterType);
}
bind(s, target, Indexer.idx.builtins.unknown, kind);
} else {
bind(s, target, ent.getType().asFuncType().getReturnType(), kind);
}
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, InterruptedException {
Audio audio = Audio.getInstance();
audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);
System.out.println("Press Enter key to stop the program...");
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
br.read();
}
audio.stopService();
}
|
#vulnerable code
public static void main(String[] args) throws UnsupportedAudioFileException, IOException {
Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
Audio.playSound(Audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);
System.out.println("Press Enter key to stop the program...");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.read();
Audio.stopService();
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testSelectAlbum() {
AlbumPage albumPage = albumListPage.selectAlbum("21");
albumPage.navigateToPage();
assertTrue(albumPage.isAt());
}
|
#vulnerable code
@Test
public void testSelectAlbum() {
AlbumListPage albumListPage = new AlbumListPage(new WebClient());
AlbumPage albumPage = albumListPage.selectAlbum("21");
assertTrue(albumPage.isAt());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
Map<String, String> map = null;
try (FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream objIn = new ObjectInputStream(fileIn)) {
map = (Map<String, String>) objIn.readObject();
}
return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map.get("lengthMeters")),
Integer.parseInt(map.get("weightTons")));
}
|
#vulnerable code
public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Map<String, String> map = (Map<String, String>) objIn.readObject();
objIn.close();
fileIn.close();
return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map
.get("lengthMeters")), Integer.parseInt(map.get("weightTons")));
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testSelectAlbum() {
AlbumPage albumPage = albumListPage.selectAlbum("21");
albumPage.navigateToPage();
assertTrue(albumPage.isAt());
}
|
#vulnerable code
@Test
public void testSelectAlbum() {
AlbumListPage albumListPage = new AlbumListPage(new WebClient());
AlbumPage albumPage = albumListPage.selectAlbum("21");
assertTrue(albumPage.isAt());
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void run() {
try {
initServerSocket();
if (log.isDebugEnabled()) {
log.debug("Started " + getName());
}
// Handle connections
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
handleClientSocket(clientSocket);
}
} catch (IOException ignored) {
//ignored
if (log.isTraceEnabled()) {
log.trace("Error while processing client socket for " + getName(), ignored);
}
}
}
} finally {
closeServerSocket();
}
}
|
#vulnerable code
@Override
public void run() {
initServerSocket();
// Notify everybody that we're ready to accept connections
synchronized (startupMonitor) {
startupMonitor.notifyAll();
}
if (log.isDebugEnabled()) {
log.debug("Started " + getName());
}
// Handle connections
while (keepOn()) {
try {
Socket clientSocket = serverSocket.accept();
if (!keepOn()) {
clientSocket.close();
} else {
handleClientSocket(clientSocket);
}
} catch (IOException ignored) {
//ignored
if (log.isTraceEnabled()) {
log.trace("Error while processing client socket for " + getName(), ignored);
}
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testSearch() throws Exception {
GreenMailUser user = greenMail.setUser("to1@localhost", "pwd");
assertNotNull(greenMail.getImap());
MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
Flags fooFlags = new Flags();
fooFlags.add("foo");
storeSearchTestMessages(greenMail.getImap().createSession(), folder, fooFlags);
greenMail.waitForIncomingEmail(2);
final Store store = greenMail.getImap().createStore();
store.connect("to1@localhost", "pwd");
try {
Folder imapFolder = store.getFolder("INBOX");
imapFolder.open(Folder.READ_WRITE);
Message[] imapMessages = imapFolder.getMessages();
assertEquals(4, imapMessages.length);
Message m0 = imapMessages[0];
assertTrue(m0.getSubject().startsWith("#0"));
Message m1 = imapMessages[1];
assertTrue(m1.getSubject().startsWith("#1"));
Message m2 = imapMessages[2];
assertTrue(m2.getSubject().startsWith("#2"));
Message m3 = imapMessages[3];
assertTrue(m3.getSubject().startsWith("#3"));
assertTrue(m0.getFlags().contains(Flags.Flag.ANSWERED));
// Search flags
imapMessages = imapFolder.search(new FlagTerm(new Flags(Flags.Flag.ANSWERED), true));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FlagTerm(fooFlags, true));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getFlags().contains("foo"));
imapMessages = imapFolder.search(new FlagTerm(fooFlags, false));
assertEquals(3, imapMessages.length);
assertTrue(!imapMessages[0].getFlags().contains(fooFlags));
assertTrue(!imapMessages[1].getFlags().contains(fooFlags));
assertTrue(!imapMessages[2].getFlags().contains(fooFlags));
// Search header ids
String id = m0.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
id = m1.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search FROM
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from3@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search TO
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to3@localhost")));
assertEquals(3, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search Subject
imapMessages = imapFolder.search(new SubjectTerm("test0Search"));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("TeSt0Search")); // Case insensitive
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("0S"));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("not found"));
assertEquals(0, imapMessages.length);
imapMessages = imapFolder.search(new SubjectTerm("test"));
assertEquals(2, imapMessages.length);
//Search OrTerm - Search Subject which contains test0Search OR nonexistent
imapMessages = imapFolder.search(new OrTerm(new SubjectTerm("test0Search"), new SubjectTerm("nonexistent")));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m0);
// OrTerm : two matching sub terms
imapMessages = imapFolder.search(new OrTerm(new SubjectTerm("foo"), new SubjectTerm("bar")));
assertEquals(2, imapMessages.length);
assertTrue(imapMessages[0] == m2);
assertTrue(imapMessages[1] == m3);
// OrTerm : no matching
imapMessages = imapFolder.search(new AndTerm(new SubjectTerm("nothing"), new SubjectTerm("nil")));
assertEquals(0, imapMessages.length);
//Search AndTerm - Search Subject which contains test0Search AND test1Search
imapMessages = imapFolder.search(new AndTerm(new SubjectTerm("test0Search"), new SubjectTerm("test1Search")));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0] == m1);
// Content
final String pattern = "\u00e4\u03A0";
imapMessages = imapFolder.search(new SubjectTerm(pattern));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getSubject().contains(pattern));
} finally {
store.close();
}
}
|
#vulnerable code
@Test
public void testSearch() throws Exception {
GreenMailUser user = greenMail.setUser("to1@localhost", "pwd");
assertNotNull(greenMail.getImap());
MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
Flags fooFlags = new Flags();
fooFlags.add("foo");
storeSearchTestMessages(greenMail.getImap().createSession(), folder, fooFlags);
greenMail.waitForIncomingEmail(2);
final Store store = greenMail.getImap().createStore();
store.connect("to1@localhost", "pwd");
try {
Folder imapFolder = store.getFolder("INBOX");
imapFolder.open(Folder.READ_WRITE);
Message[] imapMessages = imapFolder.getMessages();
assertTrue(null != imapMessages && imapMessages.length == 2);
Message m0 = imapMessages[0];
Message m1 = imapMessages[1];
assertTrue(m0.getFlags().contains(Flags.Flag.ANSWERED));
// Search flags
imapMessages = imapFolder.search(new FlagTerm(new Flags(Flags.Flag.ANSWERED), true));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FlagTerm(fooFlags, true));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getFlags().contains("foo"));
imapMessages = imapFolder.search(new FlagTerm(fooFlags, false));
assertEquals(1, imapMessages.length);
assertTrue(!imapMessages[0].getFlags().contains(fooFlags));
// Search header ids
String id = m0.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
id = m1.getHeader("Message-ID")[0];
imapMessages = imapFolder.search(new HeaderTerm("Message-ID", id));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search FROM
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new FromTerm(new InternetAddress("from3@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search TO
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to2@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m0, imapMessages[0]);
imapMessages = imapFolder.search(new RecipientTerm(Message.RecipientType.TO, new InternetAddress("to3@localhost")));
assertEquals(1, imapMessages.length);
assertEquals(m1, imapMessages[0]);
// Search Subject
imapMessages = imapFolder.search(new SubjectTerm("test0Search"));
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("TeSt0Search")); // Case insensitive
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("0S"));
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
imapMessages = imapFolder.search(new SubjectTerm("not found"));
assertEquals(0, imapMessages.length);
imapMessages = imapFolder.search(new SubjectTerm("test"));
assertTrue(imapMessages.length == 2);
//Search OrTerm - Search Subject which contains String1 OR String2
imapMessages = imapFolder.search(new OrTerm(new SubjectTerm("test0Search"),new SubjectTerm("String2")));
assertTrue(imapMessages.length == 2);
assertTrue(imapMessages[0] == m0);
//Search AndTerm - Search Subject which contains String1 AND String2
imapMessages = imapFolder.search(new AndTerm(new SubjectTerm("test0Search"),new SubjectTerm("test1Search")));
assertTrue(imapMessages.length == 1);
assertTrue(imapMessages[0] == m1);
// Content
final String pattern = "\u00e4\u03A0";
imapMessages = imapFolder.search(new SubjectTerm(pattern));
assertEquals(1, imapMessages.length);
assertTrue(imapMessages[0].getSubject().contains(pattern));
} finally {
store.close();
}
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void readDotTerminatedContent(BufferedReader in)
throws IOException {
StringBuilder buf = new StringBuilder();
while (true) {
String line = in.readLine();
if (line == null)
throw new EOFException("Did not receive <CRLF>.<CRLF>");
if (".".equals(line)) {
break;
} else if (line.startsWith(".")) {
println(buf, line.substring(1));
} else {
println(buf, line);
}
}
content = buf.toString();
try {
message = GreenMailUtil.newMimeMessage(content);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
#vulnerable code
public void readDotTerminatedContent(BufferedReader in)
throws IOException {
content = workspace.getTmpFile();
Writer data = content.getWriter();
PrintWriter dataWriter = new InternetPrintWriter(data);
while (true) {
String line = in.readLine();
if (line == null)
throw new EOFException("Did not receive <CRLF>.<CRLF>");
if (".".equals(line)) {
dataWriter.close();
break;
} else if (line.startsWith(".")) {
dataWriter.println(line.substring(1));
} else {
dataWriter.println(line);
}
}
try {
message = GreenMailUtil.newMimeMessage(content.getAsString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
});
}
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void handleBodyFetch(MimeMessage mimeMessage,
String sectionSpecifier,
String partial,
StringBuilder response) throws IOException, MessagingException {
if (sectionSpecifier.length() == 0) {
// TODO - need to use an InputStream from the response here.
ByteArrayOutputStream bout = new ByteArrayOutputStream();
mimeMessage.writeTo(bout);
byte[] bytes = bout.toByteArray();
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("HEADER".equalsIgnoreCase(sectionSpecifier)) {
Enumeration<?> inum = mimeMessage.getAllHeaderLines();
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS.NOT")) {
String[] excludeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS.NOT".length());
Enumeration<?> inum = mimeMessage.getNonMatchingHeaderLines(excludeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS ")) {
String[] includeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS ".length());
Enumeration<?> inum = mimeMessage.getMatchingHeaderLines(includeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.endsWith("MIME")) {
String[] strs = sectionSpecifier.trim().split("\\.");
int partNumber = Integer.parseInt(strs[0]) - 1;
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
byte[] bytes = GreenMailUtil.getHeaderAsBytes(mp.getBodyPart(partNumber));
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("TEXT".equalsIgnoreCase(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
if (log.isDebugEnabled()) {
log.debug("Fetching body part for section specifier " + sectionSpecifier +
" and mime message (contentType=" + mimeMessage.getContentType());
}
String contentType = mimeMessage.getContentType();
if (contentType.toLowerCase().startsWith("text/plain") && "1".equals(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
BodyPart part = null;
// Find part by number spec, eg "1" or "2.1" or "4.3.1" ...
String spec = sectionSpecifier;
int dotIdx = spec.indexOf('.');
String pre = dotIdx < 0 ? spec : spec.substring(0, dotIdx);
while (null != pre && NUMBER_MATCHER.matcher(pre).matches()) {
int partNumber = Integer.parseInt(pre) - 1;
if (null == part) {
part = mp.getBodyPart(partNumber);
} else {
// Content must be multipart
part = ((Multipart) part.getContent()).getBodyPart(partNumber);
}
dotIdx = spec.indexOf('.');
if (dotIdx > 0) { // Another sub part index?
spec = spec.substring(dotIdx + 1);
pre = spec.substring(0, dotIdx);
} else {
pre = null;
}
}
if (null == part) {
throw new IllegalStateException("Got null for " + sectionSpecifier);
}
// A bit optimistic to only cover theses cases ... TODO
if ("message/rfc822".equalsIgnoreCase(part.getContentType())) {
handleBodyFetch((MimeMessage) part.getContent(), spec, partial, response);
} else if ("TEXT".equalsIgnoreCase(spec)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
byte[] bytes = GreenMailUtil.getBodyAsBytes(part);
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
}
}
}
}
|
#vulnerable code
private void handleBodyFetch(MimeMessage mimeMessage,
String sectionSpecifier,
String partial,
StringBuilder response) throws IOException, MessagingException {
if (sectionSpecifier.length() == 0) {
// TODO - need to use an InputStream from the response here.
ByteArrayOutputStream bout = new ByteArrayOutputStream();
mimeMessage.writeTo(bout);
byte[] bytes = bout.toByteArray();
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("HEADER".equalsIgnoreCase(sectionSpecifier)) {
Enumeration<?> inum = mimeMessage.getAllHeaderLines();
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS.NOT")) {
String[] excludeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS.NOT".length());
Enumeration<?> inum = mimeMessage.getNonMatchingHeaderLines(excludeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.startsWith("HEADER.FIELDS ")) {
String[] includeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS ".length());
Enumeration<?> inum = mimeMessage.getMatchingHeaderLines(includeNames);
addHeaders(inum, response);
} else if (sectionSpecifier.endsWith("MIME")) {
String[] strs = sectionSpecifier.trim().split("\\.");
int partNumber = Integer.parseInt(strs[0]) - 1;
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
byte[] bytes = GreenMailUtil.getHeaderAsBytes(mp.getBodyPart(partNumber));
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
} else if ("TEXT".equalsIgnoreCase(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
if (log.isDebugEnabled()) {
log.debug("Fetching body part for section specifier " + sectionSpecifier +
" and mime message (contentType=" + mimeMessage.getContentType());
}
String contentType = mimeMessage.getContentType();
if (contentType.startsWith("text/plain") && "1".equals(sectionSpecifier)) {
handleBodyFetchForText(mimeMessage, partial, response);
} else {
MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
BodyPart part = null;
String[] nestedIdx = sectionSpecifier.split("\\.");
for (String idx : nestedIdx) {
int partNumber = Integer.parseInt(idx) - 1;
if (null == part) {
part = mp.getBodyPart(partNumber);
} else {
// Content must be multipart
part = ((Multipart) part.getContent()).getBodyPart(partNumber);
}
}
byte[] bytes = GreenMailUtil.getBodyAsBytes(part);
bytes = doPartial(partial, bytes, response);
addLiteral(bytes, response);
}
}
}
#location 53
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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");
});
}
|
#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 21
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void 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");
});
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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");
});
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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");
});
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public long getUidNext() {
return nextUid.get();
}
|
#vulnerable code
@Override
public long getUidNext() {
return nextUid;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void 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");
});
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
});
}
|
#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 [email protected]" + CRLF);
assertThat(reader.readLine()).isEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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("已经存在费用配置信息");
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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>");
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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()));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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));
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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()));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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()));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static String getHeader() {
return getHeader(Objects.requireNonNull(WebUtil.getRequest()));
}
|
#vulnerable code
public static String getHeader() {
return getHeader(WebUtil.getRequest());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#vulnerable code
public static BladeUser getUser() {
return getUser(WebUtil.getRequest());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType,
String code, String redirectUri, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "code", code);
connect.addParameter(params, "redirect_uri", redirectUri);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params).trim();
return parseAccessTokenResult(result);
}
|
#vulnerable code
public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType,
String code, String redirectUri, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "code", code);
connect.addParameter(params, "redirect_uri", redirectUri);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params);
String[] results = result.split("\\&");
JSONObject jsonObject = new JSONObject();
for (String param : results) {
String[] keyValue = param.split("\\=");
jsonObject.put(keyValue[0], keyValue.length > 0 ? keyValue[1] : null);
}
String errorCode = jsonObject.optString("code", null);
if (errorCode != null) {
jsonObject.put("ret", errorCode);// To match Error.parse()
}
return Result.parse(jsonObject, AccessToken.class);
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Result<TokenInfo> getTokenInfo(String accessToken) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "access_token", accessToken);
String result = weibo.post("https://api.weibo.com/oauth2/get_token_info", params);
return Result.parse(result, TokenInfo.class);
}
|
#vulnerable code
public Result<TokenInfo> getTokenInfo(String accessToken) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "access_token", accessToken);
String result = weibo.post("https://api.weibo.com/oauth2/get_token_info", params);
return Result.perse(result, TokenInfo.class);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final RemoteRequest request = new RemoteRequest(httpRequest);
final LocalResponse response = new LocalResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
|
#vulnerable code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final TeeRequest request = new TeeRequest(httpRequest);
final TeeResponse response = new TeeResponse(httpResponse);
chain.doFilter(request, response);
if (isUnauthorized(response)) {
final Optional<Correlator> correlator;
if (isFirstRequest(request)) {
correlator = logbook.write(new UnauthorizedRawHttpRequest(request));
} else {
correlator = readCorrelator(request);
}
if (correlator.isPresent()) {
correlator.get().write(response);
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldUseSameBody() throws IOException {
unit.getOutputStream().write("test".getBytes());
final byte[] body1 = unit.getBody();
final byte[] body2 = unit.getBody();
assertSame(body1, body2);
}
|
#vulnerable code
@Test
public void shouldUseSameBody() throws IOException {
final HttpServletResponse mock = mock(HttpServletResponse.class);
when(mock.getOutputStream()).thenReturn(new ServletOutputStream() {
@Override
public void write(final int b) throws IOException {
}
});
final LocalResponse response = new LocalResponse(mock, "1");
response.getOutputStream().write("test".getBytes());
final byte[] body1 = response.getBody();
final byte[] body2 = response.getBody();
assertSame(body1, body2);
}
#location 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public HttpRequest withBody() throws IOException {
body = ByteStreams.toByteArray(super.getInputStream());
return this;
}
|
#vulnerable code
@Override
public HttpRequest withBody() throws IOException {
body = ByteStreams.toByteArray(getInputStream());
return this;
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldUseSameBody() throws IOException {
unit.getOutputStream().write("test".getBytes());
final byte[] body1 = unit.getBody();
final byte[] body2 = unit.getBody();
assertSame(body1, body2);
}
|
#vulnerable code
@Test
public void shouldUseSameBody() throws IOException {
final HttpServletResponse mock = mock(HttpServletResponse.class);
when(mock.getOutputStream()).thenReturn(new ServletOutputStream() {
@Override
public void write(final int b) throws IOException {
}
});
final LocalResponse response = new LocalResponse(mock, "1");
response.getOutputStream().write("test".getBytes());
final byte[] body1 = response.getBody();
final byte[] body2 = response.getBody();
assertSame(body1, body2);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final RemoteRequest request = new RemoteRequest(httpRequest);
final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request);
if (correlator.isPresent()) {
final LocalResponse response = new LocalResponse(httpResponse);
chain.doFilter(request, response);
response.getWriter().flush();
logResponse(correlator.get(), request, response);
} else {
chain.doFilter(httpRequest, httpResponse);
}
}
|
#vulnerable code
@Override
public void doFilter(final Logbook logbook, final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse, final FilterChain chain) throws ServletException, IOException {
final TeeRequest request = new TeeRequest(httpRequest);
final Optional<Correlator> correlator = logRequestIfNecessary(logbook, request);
if (correlator.isPresent()) {
final TeeResponse response = new TeeResponse(httpResponse);
chain.doFilter(request, response);
response.getWriter().flush();
logResponse(correlator.get(), request, response);
} else {
chain.doFilter(httpRequest, httpResponse);
}
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
final PaxDate end = PaxDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case YEARS:
return yearsUntil(end);
case DECADES:
return yearsUntil(end) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(end) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(end) / YEARS_IN_MILLENNIUM;
default:
break;
}
}
return super.until(end, unit);
}
|
#vulnerable code
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
final PaxDate end = PaxDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case DAYS:
return daysUntil(end);
case WEEKS:
return daysUntil(end) / DAYS_IN_WEEK;
case MONTHS:
return monthsUntil(end);
case YEARS:
return yearsUntil(end);
case DECADES:
return yearsUntil(end) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(end) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(end) / YEARS_IN_MILLENNIUM;
case ERAS:
return end.getLong(ERA) - getLong(ERA);
default:
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
}
return unit.between(this, end);
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
final PaxDate end = PaxDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case YEARS:
return yearsUntil(end);
case DECADES:
return yearsUntil(end) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(end) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(end) / YEARS_IN_MILLENNIUM;
default:
break;
}
}
return super.until(end, unit);
}
|
#vulnerable code
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
final PaxDate end = PaxDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case DAYS:
return daysUntil(end);
case WEEKS:
return daysUntil(end) / DAYS_IN_WEEK;
case MONTHS:
return monthsUntil(end);
case YEARS:
return yearsUntil(end);
case DECADES:
return yearsUntil(end) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(end) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(end) / YEARS_IN_MILLENNIUM;
case ERAS:
return end.getLong(ERA) - getLong(ERA);
default:
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
}
return unit.between(this, end);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
final PaxDate end = PaxDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case YEARS:
return yearsUntil(end);
case DECADES:
return yearsUntil(end) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(end) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(end) / YEARS_IN_MILLENNIUM;
default:
break;
}
}
return super.until(end, unit);
}
|
#vulnerable code
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
final PaxDate end = PaxDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case DAYS:
return daysUntil(end);
case WEEKS:
return daysUntil(end) / DAYS_IN_WEEK;
case MONTHS:
return monthsUntil(end);
case YEARS:
return yearsUntil(end);
case DECADES:
return yearsUntil(end) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(end) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(end) / YEARS_IN_MILLENNIUM;
case ERAS:
return end.getLong(ERA) - getLong(ERA);
default:
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
}
return unit.between(this, end);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void writeSpecRunnerToSourceSpecDirectory() throws IOException {
File runnerDestination = new File(jasmineTargetDir,manualSpecRunnerHtmlFileName);
String newRunnerHtml = new SpecRunnerHtmlGenerator(scriptsForRunner(), sourceEncoding).generate(ReporterType.TrivialReporter, customRunnerTemplate);
if(newRunnerDiffersFromOldRunner(runnerDestination, newRunnerHtml)) {
saveRunner(runnerDestination, newRunnerHtml);
} else {
getLog().info("Skipping spec runner generation, because an identical spec runner already exists.");
}
}
|
#vulnerable code
private void writeSpecRunnerToSourceSpecDirectory() throws IOException {
Set<String> scripts = relativizesASetOfScripts.relativize(jasmineTargetDir, resolvesCompleteListOfScriptLocations.resolve(sources, specs, preloadSources));
SpecRunnerHtmlGenerator htmlGenerator = new SpecRunnerHtmlGenerator(scripts, sourceEncoding);
String runner = htmlGenerator.generate(ReporterType.TrivialReporter, customRunnerTemplate);
File destination = new File(jasmineTargetDir,manualSpecRunnerHtmlFileName);
String existingRunner = loadExistingManualRunner(destination);
if(!StringUtils.equals(runner, existingRunner)) {
fileUtilsWrapper.writeStringToFile(destination, runner, sourceEncoding);
} else {
getLog().info("Skipping spec runner generation, because an identical spec runner already exists.");
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws IOException {
GenericSignatureParser parser = new GenericSignatureParser();
MethodSignature sig1 = parser.parseMethodSignature("<U:Ljava/lang/Foo;>(Ljava/lang/Class<TU;>;TU;)Ljava/lang/Class<+TU;>;");
MethodSignature sig2 = parser.parseMethodSignature("<K:Ljava/lang/Object;V:Ljava/lang/Object;>(Ljava/util/Map<TK;TV;>;Ljava/lang/Class<TK;>;Ljava/lang/Class<TV;>;)Ljava/util/Map<TK;TV;>;");
MethodSignature sig3 = parser.parseMethodSignature("<T:Ljava/lang/Object;>(Ljava/util/Collection<-TT;>;[TT;)Z");
MethodSignature sig4 = parser.parseMethodSignature("(Ljava/util/Collection<*>;Ljava/util/Collection<*>;)Z");
MethodSignature sig7 = parser.parseMethodSignature("()Lcom/sun/xml/internal/bind/v2/model/impl/ElementInfoImpl<Ljava/lang/reflect/Type;Ljava/lang/Class;Ljava/lang/reflect/Field;Ljava/lang/reflect/Method;>.PropertyImpl;");
ClassSignature sig5 = parser.parseClassSignature("<C:Lio/undertow/server/protocol/framed/AbstractFramedChannel<TC;TR;TS;>;R:Lio/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel<TC;TR;TS;>;S:Lio/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel<TC;TR;TS;>;>Ljava/lang/Object;Lorg/xnio/channels/ConnectedChannel;");
ClassSignature sig6 = parser.parseClassSignature("Lcom/apple/laf/AquaUtils$RecyclableSingleton<Ljavax/swing/text/LayeredHighlighter$LayerPainter;>;");
System.out.println(sig1);
System.out.println(sig2);
System.out.println(sig3);
System.out.println(sig4);
System.out.println(sig5);
System.out.println(sig6);
System.out.println(sig7);
// BufferedReader reader = new BufferedReader(new FileReader("/Users/jason/sigmethods.txt"));
// String line;
// while ((line = reader.readLine()) != null) {
// try {
// System.out.println(parser.parseMethodSignature(line));
// } catch (Exception e) {
// System.err.println(line);
// e.printStackTrace(System.err);
// System.exit(-1);
// }
// }
}
|
#vulnerable code
public static void main(String[] args) throws IOException {
GenericSignatureParser parser = new GenericSignatureParser();
// MethodSignature sig1 = parser.parseMethodSignature("<U:Ljava/lang/Object;>(Ljava/lang/Class<TU;>;)Ljava/lang/Class<+TU;>;");
// MethodSignature sig2 = parser.parseMethodSignature("<K:Ljava/lang/Object;V:Ljava/lang/Object;>(Ljava/util/Map<TK;TV;>;Ljava/lang/Class<TK;>;Ljava/lang/Class<TV;>;)Ljava/util/Map<TK;TV;>;");
// MethodSignature sig3 = parser.parseMethodSignature("<T:Ljava/lang/Object;>(Ljava/util/Collection<-TT;>;[TT;)Z");
// MethodSignature sig4 = parser.parseMethodSignature("(Ljava/util/Collection<*>;Ljava/util/Collection<*>;)Z");
//MethodSignature sig7 = parser.parseMethodSignature("()Lcom/sun/xml/internal/bind/v2/model/impl/ElementInfoImpl<Ljava/lang/reflect/Type;Ljava/lang/Class;Ljava/lang/reflect/Field;Ljava/lang/reflect/Method;>.PropertyImpl;");
// ClassSignature sig5 = parser.parseClassSignature("<C:Lio/undertow/server/protocol/framed/AbstractFramedChannel<TC;TR;TS;>;R:Lio/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel<TC;TR;TS;>;S:Lio/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel<TC;TR;TS;>;>Ljava/lang/Object;Lorg/xnio/channels/ConnectedChannel;");
// ClassSignature sig6 = parser.parseClassSignature("Lcom/apple/laf/AquaUtils$RecyclableSingleton<Ljavax/swing/text/LayeredHighlighter$LayerPainter;>;");
// System.out.println(sig1);
// System.out.println(sig2);
// System.out.println(sig3);
// System.out.println(sig4);
// System.out.println(sig5);
// System.out.println(sig6);
// System.out.println(sig7);
BufferedReader reader = new BufferedReader(new FileReader("/Users/jason/sigmethods.txt"));
String line;
while ((line = reader.readLine()) != null) {
try {
System.out.println(parser.parseMethodSignature(line));
} catch (Exception e) {
System.err.println(line);
e.printStackTrace(System.err);
System.exit(-1);
}
}
}
#location 27
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Index read() throws IOException {
if(version == -1) {
readVersion();
}
IndexReaderImpl reader = getReader(input, version);
if (reader == null) {
input.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
}
|
#vulnerable code
public Index read() throws IOException {
PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input));
if (stream.readInt() != MAGIC) {
stream.close();
throw new IllegalArgumentException("Not a jandex index");
}
byte version = stream.readByte();
IndexReaderImpl reader = getReader(stream, version);
if (reader == null) {
stream.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static Result createJarIndex(File jarFile, Indexer indexer, boolean modify, boolean newJar, boolean verbose) throws IOException {
File tmpCopy = null;
ZipOutputStream zo = null;
OutputStream out = null;
File outputFile = null;
JarFile jar = new JarFile(jarFile);
if (modify) {
tmpCopy = File.createTempFile(jarFile.getName().substring(0, jarFile.getName().lastIndexOf('.')), "jmp");
out = zo = new ZipOutputStream(new FileOutputStream(tmpCopy));
} else if (newJar) {
outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jandex.jar"));
out = zo = new ZipOutputStream(new FileOutputStream(outputFile));
} else
{
outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jar") + ".idx");
out = new FileOutputStream( outputFile);
}
try {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (modify) {
zo.putNextEntry(entry);
copy(jar.getInputStream(entry), zo);
}
if (entry.getName().endsWith(".class")) {
ClassInfo info = indexer.index(jar.getInputStream(entry));
if (verbose && info != null)
printIndexEntryInfo(info);
}
}
if (modify || newJar) {
zo.putNextEntry(new ZipEntry("META-INF/jandex.idx"));
}
IndexWriter writer = new IndexWriter(out);
Index index = indexer.complete();
int bytes = writer.write(index);
out.close();
zo.close();
jar.close();
if (modify) {
jarFile.delete();
tmpCopy.renameTo(jarFile);
tmpCopy = null;
}
return new Result(index, modify ? "META-INF/jandex.idx" : outputFile.getPath(), bytes);
} finally {
out.flush();
out.close();
if (tmpCopy != null)
tmpCopy.delete();
}
}
|
#vulnerable code
public static Result createJarIndex(File jarFile, Indexer indexer, boolean modify, boolean newJar, boolean verbose) throws IOException {
File tmpCopy = null;
ZipOutputStream zo = null;
OutputStream out = null;
File outputFile = null;
JarFile jar = new JarFile(jarFile);
if (modify) {
tmpCopy = File.createTempFile(jarFile.getName().substring(0, jarFile.getName().lastIndexOf('.')), "jmp");
out = zo = new ZipOutputStream(new FileOutputStream(tmpCopy));
} else if (newJar) {
outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jandex.jar"));
out = zo = new ZipOutputStream(new FileOutputStream(outputFile));
} else
{
outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jar") + ".idx");
out = new FileOutputStream( outputFile);
}
try {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (modify) {
zo.putNextEntry(entry);
copy(jar.getInputStream(entry), zo);
}
if (entry.getName().endsWith(".class")) {
ClassInfo info = indexer.index(jar.getInputStream(entry));
if (verbose && info != null)
printIndexEntryInfo(info);
}
}
if (modify || newJar) {
zo.putNextEntry(new ZipEntry("META-INF/jandex.idx"));
}
IndexWriter writer = new IndexWriter(out);
Index index = indexer.complete();
int bytes = writer.write(index);
if (modify) {
jarFile.delete();
tmpCopy.renameTo(jarFile);
tmpCopy = null;
}
return new Result(index, modify ? "META-INF/jandex.idx" : outputFile.getPath(), bytes);
} finally {
out.flush();
out.close();
if (tmpCopy != null)
tmpCopy.delete();
}
}
#location 37
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Index read() throws IOException {
if(version == -1) {
readVersion();
}
IndexReaderImpl reader = getReader(input, version);
if (reader == null) {
input.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
}
|
#vulnerable code
public Index read() throws IOException {
PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input));
if (stream.readInt() != MAGIC) {
stream.close();
throw new IllegalArgumentException("Not a jandex index");
}
byte version = stream.readByte();
IndexReaderImpl reader = getReader(stream, version);
if (reader == null) {
stream.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
}
#location 2
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Index read() throws IOException {
if(version == -1) {
readVersion();
}
IndexReaderImpl reader = getReader(input, version);
if (reader == null) {
input.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
}
|
#vulnerable code
public Index read() throws IOException {
PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input));
if (stream.readInt() != MAGIC) {
stream.close();
throw new IllegalArgumentException("Not a jandex index");
}
byte version = stream.readByte();
IndexReaderImpl reader = getReader(stream, version);
if (reader == null) {
stream.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
String getStream(int streamId) {
return streams.get(streamId);
}
|
#vulnerable code
LogRecordSet.Writer getLogRecordSetWriter() {
return recordSetWriter;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Around("within(@org.springframework.stereotype.Repository *)")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
if (this.enabled) {
StopWatch sw = new StopWatch(joinPoint.toShortString());
sw.start("invoke");
try {
return joinPoint.proceed();
} finally {
sw.stop();
synchronized (this) {
this.callCount++;
this.accumulatedCallTime += sw.getTotalTimeMillis();
}
}
} else {
return joinPoint.proceed();
}
}
|
#vulnerable code
@Around("within(@org.springframework.stereotype.Repository *)")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
if (this.isEnabled) {
StopWatch sw = new StopWatch(joinPoint.toShortString());
sw.start("invoke");
try {
return joinPoint.proceed();
} finally {
sw.stop();
synchronized (this) {
this.callCount++;
this.accumulatedCallTime += sw.getTotalTimeMillis();
}
}
} else {
return joinPoint.proceed();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void addAllErrors(BindingResult bindingResult) {
for (FieldError fieldError : bindingResult.getFieldErrors()) {
BindingError error = new BindingError();
error.setObjectName(fieldError.getObjectName());
error.setFieldName(fieldError.getField());
error.setFieldValue(String.valueOf(fieldError.getRejectedValue()));
error.setErrorMessage(fieldError.getDefaultMessage());
addError(error);
}
}
|
#vulnerable code
public void addAllErrors(BindingResult bindingResult) {
for (FieldError fieldError : bindingResult.getFieldErrors()) {
BindingError error = new BindingError();
error.setObjectName(fieldError.getObjectName());
error.setFieldName(fieldError.getField());
error.setFieldValue(fieldError.getRejectedValue().toString());
error.setErrorMessage(fieldError.getDefaultMessage());
addError(error);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private RestHighLevelClient buildRestHighLevelClient() throws Exception {
Collection<HttpHost> hosts = new ArrayList<>(esNodes.length);
for (String esNode : esNodes) {
hosts.add(HttpHost.create(esNode));
}
RestClientBuilder rcb = RestClient.builder(hosts.toArray(new HttpHost[]{}));
// We need to check if we have a user security property
String securedUser = properties != null ? properties.getProperty(XPACK_USER, null) : null;
if (securedUser != null) {
// We split the username and the password
String[] split = securedUser.split(":");
if (split.length < 2) {
throw new IllegalArgumentException(XPACK_USER + " must have the form username:password");
}
String username = split[0];
String password = split[1];
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
rcb.setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(credentialsProvider));
}
return new RestHighLevelClient(rcb);
}
|
#vulnerable code
private RestHighLevelClient buildRestHighLevelClient() throws Exception {
Collection<HttpHost> hosts = new ArrayList<>(esNodes.length);
for (String esNode : esNodes) {
Tuple<String, Integer> addressPort = toAddress(esNode);
hosts.add(new HttpHost(addressPort.v1(), addressPort.v2(), "http"));
}
RestClientBuilder rcb = RestClient.builder(hosts.toArray(new HttpHost[]{}));
// We need to check if we have a user security property
String securedUser = properties != null ? properties.getProperty(XPACK_USER, null) : null;
if (securedUser != null) {
// We split the username and the password
String[] split = securedUser.split(":");
if (split.length < 2) {
throw new IllegalArgumentException(XPACK_USER + " must have the form username:password");
}
String username = split[0];
String password = split[1];
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
rcb.setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(credentialsProvider));
}
return new RestHighLevelClient(rcb);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Bean
public ExperimentDAO experimentDAO() {
LOGGER.debug("Setting up database.");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"/spring/database/database-context.xml");
ExperimentDAO database = context.getBean(ExperimentDAO.class);
database.initialize();
context.close();
return database;
}
|
#vulnerable code
@Bean
public ExperimentDAO experimentDAO() {
LOGGER.debug("Setting up database.");
ApplicationContext context = new ClassPathXmlApplicationContext("/spring/database/database-context.xml");
return context.getBean(ExperimentDAO.class);
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int mp3Count() {synchronized (lock){
return mp3Files.size();}
}
|
#vulnerable code
public int mp3Count() {
return mp3Files.size();
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void explore() {
try {
Book b = onlyOneSelected();
File m = audible.getMP3FileDest(b);
if (m.exists()) {
GUI.explore(m);
// Desktop.getDesktop().open(m.getParentFile());
}
} catch (Throwable th) {
showError(th, "showing file in system");
}
}
|
#vulnerable code
public void explore() {
try {
Book b = onlyOneSelected();
File m = audible.getMP3FileDest(b);
if (m.exists()) {
String mac = "open -R ";
String win = "Explorer /select, ";
String cmd = null;
if (Platform.isMac())
cmd = mac;
if (Platform.isWindows())
cmd = win;
// TODO: Support linux.
if (cmd != null) {
cmd += "\"" + m.getAbsolutePath() + "\"";
System.err.println(cmd);
Runtime.getRuntime().exec(cmd);
}
// Desktop.getDesktop().open(m.getParentFile());
}
} catch (Throwable th) {
showError(th, "showing file in system");
}
}
#location 18
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void updateFileCache() {
mp3Files = getFileSet(Directories.MP3);
aaxFiles = getFileSet(Directories.AAX);
needFileCacheUpdate = System.currentTimeMillis();
synchronized (lock) {
toDownload.clear();
toConvert.clear();
long seconds = 0;
for (Book b : getBooks()) {
if (isIgnoredBook(b)) continue;
if (canDownload(b)) toDownload.add(b);
if (canConvert(b)) toConvert.add(b);
seconds += TimeToSeconds.parseTimeStringToSeconds(b.getDuration());
}
totalDuration = seconds;
}
}
|
#vulnerable code
public void updateFileCache() {
mp3Files = getFileSet(Directories.MP3);
aaxFiles = getFileSet(Directories.AAX);
needFileCacheUpdate = System.currentTimeMillis();
HashSet<Book> c = new HashSet<>();
HashSet<Book> d = new HashSet<>();
long seconds = 0;
for (Book b : getBooks()) {
if (isIgnoredBook(b)) continue;
if (canDownload(b)) d.add(b);
if (canConvert(b)) c.add(b);
seconds += TimeToSeconds.parseTimeStringToSeconds(b.getDuration());
}
synchronized (lock) {
toDownload.clear();
toDownload.addAll(d);
toConvert.clear();
toConvert.addAll(c);
totalDuration = seconds;
}
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int aaxCount() {
synchronized (lock) {
return aaxFiles.size();
}
}
|
#vulnerable code
public int aaxCount() {
return aaxFiles.size();
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
InputStream decorate(final InputStream wrapped) throws IOException {
return new DeflateInputStream(wrapped);
}
|
#vulnerable code
@Override
InputStream decorate(final InputStream wrapped) throws IOException {
/*
* A zlib stream will have a header.
*
* CMF | FLG [| DICTID ] | ...compressed data | ADLER32 |
*
* * CMF is one byte.
*
* * FLG is one byte.
*
* * DICTID is four bytes, and only present if FLG.FDICT is set.
*
* Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950,
* section 2.2. http://tools.ietf.org/html/rfc1950#page-4
*
* We need to see if it looks like a proper zlib stream, or whether it is just a deflate
* stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers
* implement deflate Content-Encoding using deflate streams, rather than zlib streams.
*
* We could start looking at the bytes, but to be honest, someone else has already read
* the RFCs and implemented that for us. So we'll just use the JDK libraries and exception
* handling to do this. If that proves slow, then we could potentially change this to check
* the first byte - does it look like a CMF? What about the second byte - does it look like
* a FLG, etc.
*/
/* We read a small buffer to sniff the content. */
final byte[] peeked = new byte[6];
final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length);
final int headerLength = pushback.read(peeked);
if (headerLength == -1) {
throw new IOException("Unable to read the response");
}
/* We try to read the first uncompressed byte. */
final byte[] dummy = new byte[1];
final Inflater inf = new Inflater();
try {
int n;
while ((n = inf.inflate(dummy)) == 0) {
if (inf.finished()) {
/* Not expecting this, so fail loudly. */
throw new IOException("Unable to read the response");
}
if (inf.needsDictionary()) {
/* Need dictionary - then it must be zlib stream with DICTID part? */
break;
}
if (inf.needsInput()) {
inf.setInput(peeked);
}
}
if (n == -1) {
throw new IOException("Unable to read the response");
}
/*
* We read something without a problem, so it's a valid zlib stream. Just need to reset
* and return an unused InputStream now.
*/
pushback.unread(peeked, 0, headerLength);
return new DeflateStream(pushback, new Inflater());
} catch (final DataFormatException e) {
/* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try
* again. */
pushback.unread(peeked, 0, headerLength);
return new DeflateStream(pushback, new Inflater(true));
} finally {
inf.end();
}
}
#location 81
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void handleReference(Reference<?> ref) {
poolLock.lock();
try {
if (ref instanceof BasicPoolEntryRef) {
// check if the GCed pool entry was still in use
//@@@ find a way to detect this without lookup
//@@@ flag in the BasicPoolEntryRef, to be reset when freed?
final boolean lost = issuedConnections.remove(ref);
if (lost) {
final HttpRoute route =
((BasicPoolEntryRef)ref).getRoute();
if (LOG.isDebugEnabled()) {
LOG.debug("Connection garbage collected. " + route);
}
handleLostEntry(route);
}
}
} finally {
poolLock.unlock();
}
}
|
#vulnerable code
public void handleReference(Reference<?> ref) {
poolLock.lock();
try {
if (ref instanceof BasicPoolEntryRef) {
// check if the GCed pool entry was still in use
//@@@ find a way to detect this without lookup
//@@@ flag in the BasicPoolEntryRef, to be reset when freed?
final boolean lost = issuedConnections.remove(ref);
if (lost) {
final HttpRoute route =
((BasicPoolEntryRef)ref).getRoute();
if (LOG.isDebugEnabled()) {
LOG.debug("Connection garbage collected. " + route);
}
handleLostEntry(route);
}
} else if (ref instanceof ConnMgrRef) {
if (LOG.isDebugEnabled()) {
LOG.debug("Connection manager garbage collected.");
}
shutdown();
}
} finally {
poolLock.unlock();
}
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCreateSocket() throws Exception {
HttpParams params = new BasicHttpParams();
String password = "changeit";
char[] pwd = password.toCharArray();
RSAPrivateCrtKeySpec k;
k = new RSAPrivateCrtKeySpec(new BigInteger(RSA_PUBLIC_MODULUS, 16),
new BigInteger(RSA_PUBLIC_EXPONENT, 10),
new BigInteger(RSA_PRIVATE_EXPONENT, 16),
new BigInteger(RSA_PRIME1, 16),
new BigInteger(RSA_PRIME2, 16),
new BigInteger(RSA_EXPONENT1, 16),
new BigInteger(RSA_EXPONENT2, 16),
new BigInteger(RSA_COEFFICIENT, 16));
PrivateKey pk = KeyFactory.getInstance("RSA").generatePrivate(k);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream in1, in2, in3;
in1 = new ByteArrayInputStream(X509_FOO);
in2 = new ByteArrayInputStream(X509_INTERMEDIATE_CA);
in3 = new ByteArrayInputStream(X509_ROOT_CA);
X509Certificate[] chain = new X509Certificate[3];
chain[0] = (X509Certificate) cf.generateCertificate(in1);
chain[1] = (X509Certificate) cf.generateCertificate(in2);
chain[2] = (X509Certificate) cf.generateCertificate(in3);
ks.setKeyEntry("RSA_KEY", pk, pwd, chain);
ks.setCertificateEntry("CERT", chain[2]); // Let's trust ourselves. :-)
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmfactory.init(ks, pwd);
KeyManager[] keymanagers = kmfactory.getKeyManagers();
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(ks);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(keymanagers, trustmanagers, null);
LocalTestServer server = new LocalTestServer(null, null, null, sslcontext);
server.registerDefaultHandlers();
server.start();
try {
TestX509HostnameVerifier hostnameVerifier = new TestX509HostnameVerifier();
SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext);
socketFactory.setHostnameVerifier(hostnameVerifier);
Scheme https = new Scheme("https", socketFactory, 443);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getConnectionManager().getSchemeRegistry().register(https);
HttpHost target = new HttpHost(
LocalTestServer.TEST_SERVER_ADDR.getHostName(),
server.getServicePort(),
"https");
HttpGet httpget = new HttpGet("/random/100");
HttpResponse response = httpclient.execute(target, httpget);
assertEquals(200, response.getStatusLine().getStatusCode());
assertTrue(hostnameVerifier.isFired());
} finally {
server.stop();
}
}
|
#vulnerable code
public void testCreateSocket() throws Exception {
HttpParams params = new BasicHttpParams();
String password = "changeit";
char[] pwd = password.toCharArray();
RSAPrivateCrtKeySpec k;
k = new RSAPrivateCrtKeySpec(new BigInteger(RSA_PUBLIC_MODULUS, 16),
new BigInteger(RSA_PUBLIC_EXPONENT, 10),
new BigInteger(RSA_PRIVATE_EXPONENT, 16),
new BigInteger(RSA_PRIME1, 16),
new BigInteger(RSA_PRIME2, 16),
new BigInteger(RSA_EXPONENT1, 16),
new BigInteger(RSA_EXPONENT2, 16),
new BigInteger(RSA_COEFFICIENT, 16));
PrivateKey pk = KeyFactory.getInstance("RSA").generatePrivate(k);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream in1, in2, in3;
in1 = new ByteArrayInputStream(X509_FOO);
in2 = new ByteArrayInputStream(X509_INTERMEDIATE_CA);
in3 = new ByteArrayInputStream(X509_ROOT_CA);
X509Certificate[] chain = new X509Certificate[3];
chain[0] = (X509Certificate) cf.generateCertificate(in1);
chain[1] = (X509Certificate) cf.generateCertificate(in2);
chain[2] = (X509Certificate) cf.generateCertificate(in3);
ks.setKeyEntry("RSA_KEY", pk, pwd, chain);
ks.setCertificateEntry("CERT", chain[2]); // Let's trust ourselves. :-)
File tempFile = File.createTempFile("junit", "jks");
try {
String path = tempFile.getCanonicalPath();
tempFile.deleteOnExit();
FileOutputStream fOut = new FileOutputStream(tempFile);
ks.store(fOut, pwd);
fOut.close();
System.setProperty("javax.net.ssl.keyStore", path);
System.setProperty("javax.net.ssl.keyStorePassword", password);
System.setProperty("javax.net.ssl.trustStore", path);
System.setProperty("javax.net.ssl.trustStorePassword", password);
ServerSocketFactory server = SSLServerSocketFactory.getDefault();
// Let the operating system just choose an available port:
ServerSocket serverSocket = server.createServerSocket(0);
serverSocket.setSoTimeout(30000);
int port = serverSocket.getLocalPort();
// System.out.println("\nlistening on port: " + port);
SSLSocketFactory ssf = SSLSocketFactory.getSocketFactory();
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// Test 1 - createSocket()
IOException[] e = new IOException[1];
boolean[] success = new boolean[1];
listen(serverSocket, e, success);
Socket s = ssf.connectSocket(null, "localhost", port,
null, 0, params);
exerciseSocket(s, e, success);
// Test 2 - createSocket( Socket ), where we upgrade a plain socket
// to SSL.
success[0] = false;
listen(serverSocket, e, success);
s = new Socket("localhost", port);
s = ssf.createSocket(s, "localhost", port, true);
exerciseSocket(s, e, success);
}
finally {
tempFile.delete();
}
}
#location 69
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
if (!(conn instanceof BasicPooledConnAdapter)) {
throw new IllegalArgumentException
("Connection class mismatch, " +
"connection not obtained from this manager.");
}
BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn;
if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) {
throw new IllegalArgumentException
("Connection not obtained from this manager.");
}
synchronized (hca) {
BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry();
if (entry == null) {
return;
}
try {
// make sure that the response has been read completely
if (hca.isOpen() && !hca.isMarkedReusable()) {
// In MTHCM, there would be a call to
// SimpleHttpConnectionManager.finishLastResponse(conn);
// Consuming the response is handled outside in 4.0.
// make sure this connection will not be re-used
// Shut down rather than close, we might have gotten here
// because of a shutdown trigger.
// Shutdown of the adapter also clears the tracked route.
hca.shutdown();
}
} catch (IOException iox) {
if (log.isDebugEnabled())
log.debug("Exception shutting down released connection.",
iox);
} finally {
boolean reusable = hca.isMarkedReusable();
if (log.isDebugEnabled()) {
if (reusable) {
log.debug("Released connection is reusable.");
} else {
log.debug("Released connection is not reusable.");
}
}
hca.detach();
pool.freeEntry(entry, reusable, validDuration, timeUnit);
}
}
}
|
#vulnerable code
public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
if (!(conn instanceof BasicPooledConnAdapter)) {
throw new IllegalArgumentException
("Connection class mismatch, " +
"connection not obtained from this manager.");
}
BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn;
if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) {
throw new IllegalArgumentException
("Connection not obtained from this manager.");
}
try {
// make sure that the response has been read completely
if (hca.isOpen() && !hca.isMarkedReusable()) {
// In MTHCM, there would be a call to
// SimpleHttpConnectionManager.finishLastResponse(conn);
// Consuming the response is handled outside in 4.0.
// make sure this connection will not be re-used
// Shut down rather than close, we might have gotten here
// because of a shutdown trigger.
// Shutdown of the adapter also clears the tracked route.
hca.shutdown();
}
} catch (IOException iox) {
//@@@ log as warning? let pass?
if (log.isDebugEnabled())
log.debug("Exception shutting down released connection.",
iox);
} finally {
BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry();
boolean reusable = hca.isMarkedReusable();
if (log.isDebugEnabled()) {
if (reusable) {
log.debug("Released connection is reusable.");
} else {
log.debug("Released connection is not reusable.");
}
}
hca.detach();
if (entry != null) {
pool.freeEntry(entry, reusable, validDuration, timeUnit);
}
}
}
#location 37
#vulnerability type INTERFACE_NOT_THREAD_SAFE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void releaseConnection(final ManagedClientConnection conn, long keepalive, TimeUnit tunit) {
if (!(conn instanceof ManagedClientConnectionImpl)) {
throw new IllegalArgumentException("Connection class mismatch, " +
"connection not obtained from this manager");
}
ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn;
synchronized (managedConn) {
if (this.log.isDebugEnabled()) {
this.log.debug("Releasing connection " + conn);
}
if (managedConn.getPoolEntry() == null) {
return; // already released
}
ClientConnectionManager manager = managedConn.getManager();
if (manager != null && manager != this) {
throw new IllegalStateException("Connection not obtained from this manager");
}
synchronized (this) {
if (this.shutdown) {
shutdownConnection(managedConn);
return;
}
try {
if (managedConn.isOpen() && !managedConn.isMarkedReusable()) {
shutdownConnection(managedConn);
}
this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
if (this.log.isDebugEnabled()) {
String s;
if (keepalive > 0) {
s = "for " + keepalive + " " + tunit;
} else {
s = "indefinitely";
}
this.log.debug("Connection can be kept alive " + s);
}
} finally {
managedConn.detach();
this.conn = null;
if (this.poolEntry.isClosed()) {
this.poolEntry = null;
}
}
}
}
}
|
#vulnerable code
public void releaseConnection(final ManagedClientConnection conn, long keepalive, TimeUnit tunit) {
assertNotShutdown();
if (!(conn instanceof ManagedClientConnectionImpl)) {
throw new IllegalArgumentException("Connection class mismatch, " +
"connection not obtained from this manager");
}
if (this.log.isDebugEnabled()) {
this.log.debug("Releasing connection " + conn);
}
ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn;
synchronized (managedConn) {
if (managedConn.getPoolEntry() == null) {
return; // already released
}
ClientConnectionManager manager = managedConn.getManager();
if (manager != null && manager != this) {
throw new IllegalStateException("Connection not obtained from this manager");
}
synchronized (this) {
try {
if (managedConn.isOpen() && !managedConn.isMarkedReusable()) {
try {
managedConn.shutdown();
} catch (IOException iox) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O exception shutting down released connection", iox);
}
}
}
this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
if (this.log.isDebugEnabled()) {
String s;
if (keepalive > 0) {
s = "for " + keepalive + " " + tunit;
} else {
s = "indefinitely";
}
this.log.debug("Connection can be kept alive " + s);
}
} finally {
managedConn.detach();
this.conn = null;
if (this.poolEntry.isClosed()) {
this.poolEntry = null;
}
}
}
}
}
#location 8
#vulnerability type INTERFACE_NOT_THREAD_SAFE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
InputStream decorate(final InputStream wrapped) throws IOException {
return new DeflateInputStream(wrapped);
}
|
#vulnerable code
@Override
InputStream decorate(final InputStream wrapped) throws IOException {
/*
* A zlib stream will have a header.
*
* CMF | FLG [| DICTID ] | ...compressed data | ADLER32 |
*
* * CMF is one byte.
*
* * FLG is one byte.
*
* * DICTID is four bytes, and only present if FLG.FDICT is set.
*
* Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950,
* section 2.2. http://tools.ietf.org/html/rfc1950#page-4
*
* We need to see if it looks like a proper zlib stream, or whether it is just a deflate
* stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers
* implement deflate Content-Encoding using deflate streams, rather than zlib streams.
*
* We could start looking at the bytes, but to be honest, someone else has already read
* the RFCs and implemented that for us. So we'll just use the JDK libraries and exception
* handling to do this. If that proves slow, then we could potentially change this to check
* the first byte - does it look like a CMF? What about the second byte - does it look like
* a FLG, etc.
*/
/* We read a small buffer to sniff the content. */
final byte[] peeked = new byte[6];
final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length);
final int headerLength = pushback.read(peeked);
if (headerLength == -1) {
throw new IOException("Unable to read the response");
}
/* We try to read the first uncompressed byte. */
final byte[] dummy = new byte[1];
final Inflater inf = new Inflater();
try {
int n;
while ((n = inf.inflate(dummy)) == 0) {
if (inf.finished()) {
/* Not expecting this, so fail loudly. */
throw new IOException("Unable to read the response");
}
if (inf.needsDictionary()) {
/* Need dictionary - then it must be zlib stream with DICTID part? */
break;
}
if (inf.needsInput()) {
inf.setInput(peeked);
}
}
if (n == -1) {
throw new IOException("Unable to read the response");
}
/*
* We read something without a problem, so it's a valid zlib stream. Just need to reset
* and return an unused InputStream now.
*/
pushback.unread(peeked, 0, headerLength);
return new DeflateStream(pushback, new Inflater());
} catch (final DataFormatException e) {
/* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try
* again. */
pushback.unread(peeked, 0, headerLength);
return new DeflateStream(pushback, new Inflater(true));
} finally {
inf.end();
}
}
#location 81
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testBasicPoolEntry() {
HttpRoute route = new HttpRoute(TARGET);
ClientConnectionOperator ccop =
new DefaultClientConnectionOperator(supportedSchemes);
BasicPoolEntry bpe = null;
try {
bpe = new BasicPoolEntry(null, null, null);
fail("null operator not detected");
} catch (NullPointerException npx) {
// expected
} catch (IllegalArgumentException iax) {
// would be preferred
}
try {
bpe = new BasicPoolEntry(ccop, null, null);
fail("null route not detected");
} catch (IllegalArgumentException iax) {
// expected
}
bpe = new BasicPoolEntry(ccop, route, null);
assertEquals ("wrong route", route, bpe.getPlannedRoute());
assertNotNull("missing ref", bpe.getWeakRef());
assertEquals("bad weak ref", bpe, bpe.getWeakRef().get());
assertEquals("bad ref route", route, bpe.getWeakRef().getRoute());
}
|
#vulnerable code
public void testBasicPoolEntry() {
HttpRoute route = new HttpRoute(TARGET);
ClientConnectionOperator ccop =
new DefaultClientConnectionOperator(supportedSchemes);
BasicPoolEntry bpe = null;
try {
bpe = new BasicPoolEntry(null, null, null);
fail("null operator not detected");
} catch (NullPointerException npx) {
// expected
} catch (IllegalArgumentException iax) {
// would be preferred
}
try {
bpe = new BasicPoolEntry(ccop, null, null);
fail("null route not detected");
} catch (IllegalArgumentException iax) {
// expected
}
bpe = new BasicPoolEntry(ccop, route, null);
assertEquals ("wrong operator", ccop, bpe.getOperator());
assertEquals ("wrong route", route, bpe.getPlannedRoute());
assertNotNull("missing ref", bpe.getWeakRef());
assertEquals("bad weak ref", bpe, bpe.getWeakRef().get());
assertEquals("bad ref route", route, bpe.getWeakRef().getRoute());
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized void generate(final StringBuilder buffer) {
this.count++;
int rndnum = this.rnd.nextInt();
buffer.append(System.currentTimeMillis());
buffer.append('.');
Formatter formatter = new Formatter(buffer, Locale.US);
formatter.format("%1$016x-%2$08x", this.count, rndnum);
formatter.close();
buffer.append('.');
buffer.append(this.hostname);
}
|
#vulnerable code
public synchronized void generate(final StringBuilder buffer) {
this.count++;
int rndnum = this.rnd.nextInt();
buffer.append(System.currentTimeMillis());
buffer.append('.');
Formatter formatter = new Formatter(buffer, Locale.US);
formatter.format("%1$016x-%2$08x", this.count, rndnum);
buffer.append('.');
buffer.append(this.hostname);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
if (!(conn instanceof BasicPooledConnAdapter)) {
throw new IllegalArgumentException
("Connection class mismatch, " +
"connection not obtained from this manager.");
}
BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn;
if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) {
throw new IllegalArgumentException
("Connection not obtained from this manager.");
}
synchronized (hca) {
BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry();
if (entry == null) {
return;
}
try {
// make sure that the response has been read completely
if (hca.isOpen() && !hca.isMarkedReusable()) {
// In MTHCM, there would be a call to
// SimpleHttpConnectionManager.finishLastResponse(conn);
// Consuming the response is handled outside in 4.0.
// make sure this connection will not be re-used
// Shut down rather than close, we might have gotten here
// because of a shutdown trigger.
// Shutdown of the adapter also clears the tracked route.
hca.shutdown();
}
} catch (IOException iox) {
if (log.isDebugEnabled())
log.debug("Exception shutting down released connection.",
iox);
} finally {
boolean reusable = hca.isMarkedReusable();
if (log.isDebugEnabled()) {
if (reusable) {
log.debug("Released connection is reusable.");
} else {
log.debug("Released connection is not reusable.");
}
}
hca.detach();
pool.freeEntry(entry, reusable, validDuration, timeUnit);
}
}
}
|
#vulnerable code
public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
if (!(conn instanceof BasicPooledConnAdapter)) {
throw new IllegalArgumentException
("Connection class mismatch, " +
"connection not obtained from this manager.");
}
BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn;
if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) {
throw new IllegalArgumentException
("Connection not obtained from this manager.");
}
try {
// make sure that the response has been read completely
if (hca.isOpen() && !hca.isMarkedReusable()) {
// In MTHCM, there would be a call to
// SimpleHttpConnectionManager.finishLastResponse(conn);
// Consuming the response is handled outside in 4.0.
// make sure this connection will not be re-used
// Shut down rather than close, we might have gotten here
// because of a shutdown trigger.
// Shutdown of the adapter also clears the tracked route.
hca.shutdown();
}
} catch (IOException iox) {
//@@@ log as warning? let pass?
if (log.isDebugEnabled())
log.debug("Exception shutting down released connection.",
iox);
} finally {
BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry();
boolean reusable = hca.isMarkedReusable();
if (log.isDebugEnabled()) {
if (reusable) {
log.debug("Released connection is reusable.");
} else {
log.debug("Released connection is not reusable.");
}
}
hca.detach();
if (entry != null) {
pool.freeEntry(entry, reusable, validDuration, timeUnit);
}
}
}
#location 44
#vulnerability type INTERFACE_NOT_THREAD_SAFE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
throws IOException {
// default response context
setResponseStatus(context, CacheResponseStatus.CACHE_MISS);
String via = generateViaHeader(request);
if (clientRequestsOurOptions(request)) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
return new OptionsHttp11Response();
}
HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(
request, context);
if (fatalErrorResponse != null) return fatalErrorResponse;
request = requestCompliance.makeRequestCompliant(request);
request.addHeader("Via",via);
flushEntriesInvalidatedByRequest(target, request);
if (!cacheableRequestPolicy.isServableFromCache(request)) {
return callBackend(target, request, context);
}
HttpCacheEntry entry = satisfyFromCache(target, request);
if (entry == null) {
return handleCacheMiss(target, request, context);
}
return handleCacheHit(target, request, context, entry);
}
|
#vulnerable code
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
throws IOException {
// default response context
setResponseStatus(context, CacheResponseStatus.CACHE_MISS);
String via = generateViaHeader(request);
if (clientRequestsOurOptions(request)) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
return new OptionsHttp11Response();
}
HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(
request, context);
if (fatalErrorResponse != null) return fatalErrorResponse;
request = requestCompliance.makeRequestCompliant(request);
request.addHeader("Via",via);
flushEntriesInvalidatedByRequest(target, request);
if (!cacheableRequestPolicy.isServableFromCache(request)) {
return callBackend(target, request, context);
}
HttpCacheEntry entry = satisfyFromCache(target, request);
if (entry == null) {
return handleCacheMiss(target, request, context);
}
return handleCacheHit(target, request, context, entry);
}
#location 24
#vulnerability type INTERFACE_NOT_THREAD_SAFE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.