output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
private void setAttrType(@NotNull Type targetType, @NotNull Type v) {
if (targetType.isUnknownType()) {
Analyzer.self.putProblem(this, "Can't set attribute for UnknownType");
return;
}
targetType.table.insert(attr.id, attr, v, ATTRIBUTE);
} | #vulnerable code
private void setAttrType(@NotNull Type targetType, @NotNull Type v) {
if (targetType.isUnknownType()) {
Analyzer.self.putProblem(this, "Can't set attribute for UnknownType");
return;
}
// new attr, mark the type as "mutated"
if (targetType.table.lookupAttr(attr.id) == null ||
!targetType.table.lookupAttrType(attr.id).equals(v))
{
targetType.setMutated(true);
}
targetType.table.insert(attr.id, attr, v, ATTRIBUTE);
}
#location 8
#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 void restrictNumType(Compare compare, Scope s1, Scope s2) {
List<Node> ops = compare.ops;
if (ops.size() > 0 && ops.get(0) instanceof Op) {
Op op = ((Op) ops.get(0));
String opname = op.name;
if (op.isNumberComparisonOp()) {
Node left = compare.left;
Node right = compare.comparators.get(0);
if (!left.isName()) {
Node tmp = right;
right = left;
left = tmp;
opname = Op.invert(opname);
}
if (left.isName()) {
Name leftName = left.asName();
Type leftType = left.resolve(s1);
Type rightType = right.resolve(s1);
NumType trueType = Analyzer.self.builtins.BaseNum;
NumType falseType = Analyzer.self.builtins.BaseNum;
if (opname.equals("<") || opname.equals("<=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newUpper = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setUpper(newUpper.getUpper());
falseType = new NumType(leftType.asNumType());
falseType.setLower(newUpper.getUpper());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else if (opname.equals(">") || opname.equals(">=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newLower = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setLower(newLower.getLower());
falseType = new NumType(leftType.asNumType());
falseType.setUpper(newLower.getLower());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
}
Node loc;
List<Binding> bs = s1.lookup(leftName.id);
if (bs != null && bs.size() > 0) {
loc = bs.get(0).getNode();
} else {
loc = leftName;
}
s1.update(leftName.id, new Binding(leftName.id, loc, trueType, Binding.Kind.SCOPE));
s2.update(leftName.id, new Binding(leftName.id, loc, falseType, Binding.Kind.SCOPE));
}
}
}
} | #vulnerable code
public void restrictNumType(Compare compare, Scope s1, Scope s2) {
List<Node> ops = compare.ops;
if (ops.size() > 0 && ops.get(0) instanceof Op) {
String opname = ((Op) ops.get(0)).name;
Node left = compare.left;
Node right = compare.comparators.get(0);
if (!left.isName()) {
Node tmp = right;
right = left;
left = tmp;
opname = Op.invert(opname);
}
if (left.isName()) {
Name leftName = left.asName();
Type leftType = left.resolve(s1);
Type rightType = right.resolve(s1);
NumType trueType = Analyzer.self.builtins.BaseNum;
NumType falseType = Analyzer.self.builtins.BaseNum;
if (opname.equals("<") || opname.equals("<=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newUpper = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setUpper(newUpper.getUpper());
falseType = new NumType(leftType.asNumType());
falseType.setLower(newUpper.getUpper());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else if (opname.equals(">") || opname.equals(">=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newLower = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setLower(newLower.getLower());
falseType = new NumType(leftType.asNumType());
falseType.setUpper(newLower.getLower());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else {
trueType = leftType.asNumType();
}
Binding b = s1.lookup(leftName.id).get(0);
s1.update(leftName.id, new Binding(leftName.id, b.getNode(), trueType, Binding.Kind.SCOPE));
s2.update(leftName.id, new Binding(leftName.id, b.getNode(), falseType, Binding.Kind.SCOPE));
}
}
}
#location 46
#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
@NotNull
@Override
public Type transform(State s) {
Type ltype = transformExpr(left, s);
Type rtype;
// boolean operations
if (op == Op.And) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS1());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() && rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() || rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State falseState = State.merge(ltype.asBool().getS2(), rtype.asBool().getS2());
return new BoolType(rtype.asBool().getS1(), falseState);
} else {
return Analyzer.self.builtins.BaseBool;
}
}
if (op == Op.Or) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS2());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() || rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() && rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State trueState = State.merge(ltype.asBool().getS1(), rtype.asBool().getS1());
return new BoolType(trueState, rtype.asBool().getS2());
} else {
return Analyzer.self.builtins.BaseBool;
}
}
rtype = transformExpr(right, s);
if (ltype.isUnknownType() || rtype.isUnknownType()) {
return Analyzer.self.builtins.unknown;
}
// Don't do specific things about string types at the moment
if (ltype == Analyzer.self.builtins.BaseStr && rtype == Analyzer.self.builtins.BaseStr) {
return Analyzer.self.builtins.BaseStr;
}
// try to figure out actual result
if (ltype.isIntType() && rtype.isIntType()) {
IntType leftNum = ltype.asIntType();
IntType rightNum = rtype.asIntType();
if (op == Op.Add) {
return IntType.add(leftNum, rightNum);
}
if (op == Op.Sub) {
return IntType.sub(leftNum, rightNum);
}
if (op == Op.Mul) {
return IntType.mul(leftNum, rightNum);
}
if (op == Op.Div) {
return IntType.div(leftNum, rightNum);
}
// comparison
if (op == Op.Lt || op == Op.Gt) {
Node leftNode = left;
IntType trueType, falseType;
Op op1 = op;
if (!left.isName()) {
leftNode = right;
IntType tmpNum = rightNum;
rightNum = leftNum;
leftNum = tmpNum;
op1 = Op.invert(op1);
}
if (op1 == Op.Lt) {
if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l < r, then l's upper bound is r's upper bound
trueType = new IntType(leftNum);
trueType.setUpper(rightNum.getUpper());
// false branch: if l > r, then l's lower bound is r's lower bound
falseType = new IntType(leftNum);
falseType.setLower(rightNum.getLower());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
if (op1 == Op.Gt) {
if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// undecided, need to transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l > r, then l's lower bound is r's lower bound
trueType = new IntType(leftNum);
trueType.setLower(rightNum.getLower());
// false branch: if l < r, then l's upper bound is r's upper bound
falseType = new IntType(leftNum);
falseType.setUpper(rightNum.getUpper());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
}
}
Analyzer.self.putProblem(this, "operator " + op + " cannot be applied on operands " + ltype + " and " + rtype);
return ltype;
} | #vulnerable code
@NotNull
@Override
public Type transform(State s) {
Type ltype = transformExpr(left, s);
Type rtype;
// boolean operations
if (op == Op.And) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS1());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() && rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() || rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State falseState = State.merge(ltype.asBool().getS2(), rtype.asBool().getS2());
return new BoolType(rtype.asBool().getS1(), falseState);
} else {
return Analyzer.self.builtins.BaseBool;
}
}
if (op == Op.Or) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS2());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() || rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() && rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State trueState = State.merge(ltype.asBool().getS1(), rtype.asBool().getS1());
return new BoolType(trueState, rtype.asBool().getS2());
} else {
return Analyzer.self.builtins.BaseBool;
}
}
rtype = transformExpr(right, s);
if (ltype.isUnknownType() || rtype.isUnknownType()) {
return Analyzer.self.builtins.unknown;
}
// Don't do specific things about string types at the moment
if (ltype == Analyzer.self.builtins.BaseStr && rtype == Analyzer.self.builtins.BaseStr) {
return Analyzer.self.builtins.BaseStr;
}
// try to figure out actual result
if (ltype.isNumType() && rtype.isNumType()) {
NumType leftNum = ltype.asNumType();
NumType rightNum = rtype.asNumType();
if (op == Op.Add) {
return NumType.add(leftNum, rightNum);
}
if (op == Op.Sub) {
return NumType.sub(leftNum, rightNum);
}
if (op == Op.Mul) {
return NumType.mul(leftNum, rightNum);
}
if (op == Op.Div) {
return NumType.div(leftNum, rightNum);
}
// comparison
if (op == Op.Lt || op == Op.Gt) {
Node leftNode = left;
NumType trueType, falseType;
Op op1 = op;
if (!left.isName()) {
leftNode = right;
NumType tmpNum = rightNum;
rightNum = leftNum;
leftNum = tmpNum;
op1 = Op.invert(op1);
}
if (op1 == Op.Lt) {
if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l < r, then l's upper bound is r's upper bound
trueType = new NumType(leftNum);
trueType.setUpper(rightNum.getUpper());
// false branch: if l > r, then l's lower bound is r's lower bound
falseType = new NumType(leftNum);
falseType.setLower(rightNum.getLower());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
if (op1 == Op.Gt) {
if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// undecided, need to transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l > r, then l's lower bound is r's lower bound
trueType = new NumType(leftNum);
trueType.setLower(rightNum.getLower());
// false branch: if l < r, then l's upper bound is r's upper bound
falseType = new NumType(leftNum);
falseType.setUpper(rightNum.getUpper());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
}
}
Analyzer.self.putProblem(this, "operator " + op + " cannot be applied on operands " + ltype + " and " + rtype);
return ltype;
}
#location 115
#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 buildFunctionType() {
Scope t = BaseFunction.getTable();
for (String s : list("func_doc", "__doc__", "func_name", "__name__", "__module__")) {
t.update(s, new Url(DATAMODEL_URL), BaseStr, ATTRIBUTE);
}
Binding b = synthetic(t, "func_closure", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
b.markReadOnly();
synthetic(t, "func_code", new Url(DATAMODEL_URL), unknown(), ATTRIBUTE);
synthetic(t, "func_defaults", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
synthetic(t, "func_globals", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
synthetic(t, "func_dict", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
// Assume any function can become a method, for simplicity.
for (String s : list("__func__", "im_func")) {
synthetic(t, s, new Url(DATAMODEL_URL), new FunType(), METHOD);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String loadData() {
try (BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
this.loaded = true;
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
} | #vulnerable code
public String loadData() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
this.loaded = true;
br.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws 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 renameMailbox(MailFolder existingFolder, String newName) {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
} | #vulnerable code
@Override
public void renameMailbox(MailFolder existingFolder, String newName) throws FolderException {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
}
#location 27
#vulnerability type NULL_DEREFERENCE | 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
@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);
}
}
}
} | #vulnerable code
@Override
public void run() {
try {
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);
}
}
}
} finally {
quit();
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | 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
@Override
public long appendMessage(MimeMessage message,
Flags flags,
Date receivedDate) {
final long uid = nextUid.getAndIncrement();
try {
message.setFlags(flags, true);
message.setFlag(Flags.Flag.RECENT, true);
} catch (MessagingException e) {
throw new IllegalStateException("Can not set flags", e);
}
StoredMessage storedMessage = new StoredMessage(message,
receivedDate, uid);
int newMsn;
synchronized (mailMessages) {
mailMessages.add(storedMessage);
newMsn = mailMessages.size();
}
// Notify all the listeners of the new message
synchronized (_mailboxListeners) {
for (FolderListener _mailboxListener : _mailboxListeners) {
_mailboxListener.added(newMsn);
}
}
return uid;
} | #vulnerable code
@Override
public long appendMessage(MimeMessage message,
Flags flags,
Date receivedDate) {
long uid = nextUid;
nextUid++;
try {
message.setFlags(flags, true);
message.setFlag(Flags.Flag.RECENT, true);
} catch (MessagingException e) {
throw new IllegalStateException("Can not set flags", e);
}
StoredMessage storedMessage = new StoredMessage(message,
receivedDate, uid);
int newMsn;
synchronized (mailMessages) {
mailMessages.add(storedMessage);
newMsn = mailMessages.size();
}
// Notify all the listeners of the new message
synchronized (_mailboxListeners) {
for (FolderListener _mailboxListener : _mailboxListeners) {
_mailboxListener.added(newMsn);
}
}
return uid;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void 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
@Override
public void renameMailbox(MailFolder existingFolder, String newName) {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
} | #vulnerable code
@Override
public void renameMailbox(MailFolder existingFolder, String newName) throws FolderException {
HierarchicalFolder toRename = (HierarchicalFolder) existingFolder;
HierarchicalFolder parent = toRename.getParent();
int idx = newName.lastIndexOf(ImapConstants.HIERARCHY_DELIMITER_CHAR);
String newFolderName;
String newFolderPathWithoutName;
if (idx > 0) {
newFolderName = newName.substring(idx + 1);
newFolderPathWithoutName = newName.substring(0, idx);
} else {
newFolderName = newName;
newFolderPathWithoutName = "";
}
if (parent.getName().equals(newFolderPathWithoutName)) {
// Simple rename
toRename.setName(newFolderName);
} else {
// Hierarchy change
parent.removeChild(toRename);
HierarchicalFolder userFolder = getInboxOrUserRootFolder(toRename);
String[] path = newName.split('\\' + ImapConstants.HIERARCHY_DELIMITER);
HierarchicalFolder newParent = userFolder;
for (int i = 0; i < path.length - 1; i++) {
newParent = newParent.getChild(path[i]);
}
toRename.moveToNewParent(newParent);
toRename.setName(newFolderName);
}
}
#location 29
#vulnerability type NULL_DEREFERENCE | 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 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 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static int getLineCount(String str) {
if (null == str || str.isEmpty()) {
return 0;
}
int count = 1;
for (char c : str.toCharArray()) {
if ('\n' == c) {
count++;
}
}
return count;
} | #vulnerable code
public static int getLineCount(String str) {
LineNumberReader reader = new LineNumberReader(new StringReader(str));
try {
reader.skip(Long.MAX_VALUE);
return reader.getLineNumber();
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
// Ignore but warn
log.warn("Can not close reader", e);
}
}
}
#location 10
#vulnerability type RESOURCE_LEAK | 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
private void authPlain(Pop3Connection conn, Pop3State state, String[] args) {
// https://tools.ietf.org/html/rfc4616
String initialResponse;
if (args.length == 2 || args.length == 3 && "=".equals(args[2])) { // Continuation?
conn.println(CONTINUATION);
try {
initialResponse = conn.readLine();
} catch (IOException e) {
conn.println("-ERR Invalid syntax, expected continuation with iniital-response");
return;
}
} else if (args.length == 3) {
initialResponse = args[2];
} else {
conn.println("-ERR Invalid syntax, expected initial-response : AUTH PLAIN [initial-response]");
return;
}
// authorization-id\0authentication-id\0passwd
final SaslMessage saslMessage;
try {
saslMessage = SaslMessage.parse(EncodingUtil.decodeBase64(initialResponse));
} catch(IllegalArgumentException ex) { // Invalid Base64
log.error("Expected base64 encoding but got <"+initialResponse+">", ex); /* GreenMail is just a test server */
conn.println("-ERR Authentication failed, expected base64 encoding : " + ex.getMessage() );
return;
}
GreenMailUser user;
try {
user = state.getUser(saslMessage.getAuthcid());
state.setUser(user);
} catch (UserException e) {
log.error("Can not get user <" + saslMessage.getAuthcid() + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage() /* GreenMail is just a test server */);
return;
}
try {
state.authenticate(saslMessage.getPasswd());
conn.println("+OK");
} catch (UserException e) {
log.error("Can not authenticate using user <" + user.getLogin() + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage());
} catch (FolderException e) {
log.error("Can not authenticate using user " + user + ", internal error", e);
conn.println("-ERR Authentication failed, internal error: " + e.getMessage());
}
} | #vulnerable code
private void authPlain(Pop3Connection conn, Pop3State state, String[] args) {
// https://tools.ietf.org/html/rfc4616
String initialResponse;
if (args.length == 2 || args.length == 3 && "=".equals(args[2])) { // Continuation?
conn.println(CONTINUATION);
try {
initialResponse = conn.readLine();
} catch (IOException e) {
conn.println("-ERR Invalid syntax, expected continuation with iniital-response");
return;
}
} else if (args.length == 3) {
initialResponse = args[2];
} else {
conn.println("-ERR Invalid syntax, expected initial-response : AUTH PLAIN [initial-response]");
return;
}
// authorization-id\0authentication-id\0passwd
final BASE64DecoderStream stream = new BASE64DecoderStream(
new ByteArrayInputStream(initialResponse.getBytes(StandardCharsets.UTF_8)));
readTillNullChar(stream); // authorizationId Not used
String authenticationId = readTillNullChar(stream);
GreenMailUser user;
try {
user = state.getUser(authenticationId);
state.setUser(user);
} catch (UserException e) {
log.error("Can not get user <" + authenticationId + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage() /* GreenMail is just a test server */);
return;
}
try {
state.authenticate(readTillNullChar(stream));
conn.println("+OK");
} catch (UserException e) {
log.error("Can not authenticate using user <" + user.getLogin() + ">", e);
conn.println("-ERR Authentication failed: " + e.getMessage());
} catch (FolderException e) {
log.error("Can not authenticate using user " + user + ", internal error", e);
conn.println("-ERR Authentication failed, internal error: " + e.getMessage());
}
}
#location 36
#vulnerability type RESOURCE_LEAK | 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 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 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 11
#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
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 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 3
#vulnerability type RESOURCE_LEAK | 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
@Override
public void soService(ServiceDataFlowEvent event) {
//获取数据上下文对象
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
String paramIn = dataFlowContext.getReqData();
Assert.isJsonObject(paramIn,"用户注册请求参数有误,不是有效的json格式 "+paramIn);
Assert.jsonObjectHaveKey(paramIn,"username","用户登录,未包含username节点,请检查" + paramIn);
Assert.jsonObjectHaveKey(paramIn,"passwd","用户登录,未包含passwd节点,请检查" + paramIn);
RestTemplate restTemplate = super.getRestTemplate();
ResponseEntity responseEntity= null;
JSONObject paramInJson = JSONObject.parseObject(paramIn);
//根据AppId 查询 是否有登录的服务,查询登录地址调用
AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
if(appService == null){
responseEntity = new ResponseEntity<String>("当前没有权限访问"+ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN,HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String requestUrl = appService.getUrl() + "?userCode="+paramInJson.getString("username");
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(),ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
try{
responseEntity = restTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, String.class);
}catch (HttpStatusCodeException e){ //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
responseEntity = new ResponseEntity<String>("请求登录查询异常,"+e.getResponseBodyAsString(),e.getStatusCode());
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String resultBody = responseEntity.getBody().toString();
Assert.isJsonObject(resultBody,"调用登录查询异常,返回报文有误,不是有效的json格式 "+resultBody);
JSONObject resultInfo = JSONObject.parseObject(resultBody);
if(!resultInfo.containsKey("user") || !resultInfo.getJSONObject("user").containsKey("userPwd")
|| !resultInfo.getJSONObject("user").containsKey("userId")){
responseEntity = new ResponseEntity<String>("用户或密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
JSONObject userInfo = resultInfo.getJSONObject("user");
String userPwd = userInfo.getString("userPwd");
if(!userPwd.equals(paramInJson.getString("passwd"))){
responseEntity = new ResponseEntity<String>("密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
try {
Map userMap = new HashMap();
userMap.put(CommonConstant.LOGIN_USER_ID,userInfo.getString("userId"));
String token = AuthenticationFactory.createAndSaveToken(userMap);
userInfo.remove("userPwd");
userInfo.put("token",token);
responseEntity = new ResponseEntity<String>(userInfo.toJSONString(), HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
}catch (Exception e){
logger.error("登录异常:",e);
throw new SMOException(ResponseConstant.RESULT_CODE_INNER_ERROR,"系统内部错误,请联系管理员");
}
} | #vulnerable code
@Override
public void soService(ServiceDataFlowEvent event) {
//获取数据上下文对象
DataFlowContext dataFlowContext = event.getDataFlowContext();
AppService service = event.getAppService();
String paramIn = dataFlowContext.getReqData();
Assert.isJsonObject(paramIn,"用户注册请求参数有误,不是有效的json格式 "+paramIn);
Assert.jsonObjectHaveKey(paramIn,"username","用户登录,未包含username节点,请检查" + paramIn);
Assert.jsonObjectHaveKey(paramIn,"passwd","用户登录,未包含passwd节点,请检查" + paramIn);
RestTemplate restTemplate = super.getRestTemplate();
ResponseEntity responseEntity= null;
JSONObject paramInJson = JSONObject.parseObject(paramIn);
//根据AppId 查询 是否有登录的服务,查询登录地址调用
AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
String requestUrl = appService.getUrl() + "?userCode="+paramInJson.getString("username");
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(),ServiceCodeConstant.SERVICE_CODE_QUERY_USER_LOGIN);
HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
try{
responseEntity = restTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, String.class);
}catch (HttpStatusCodeException e){ //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
responseEntity = new ResponseEntity<String>("请求登录查询异常,"+e.getResponseBodyAsString(),e.getStatusCode());
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
String resultBody = responseEntity.getBody().toString();
Assert.isJsonObject(resultBody,"调用登录查询异常,返回报文有误,不是有效的json格式 "+resultBody);
JSONObject resultInfo = JSONObject.parseObject(resultBody);
if(!resultInfo.containsKey("user") || !resultInfo.getJSONObject("user").containsKey("userPwd")
|| !resultInfo.getJSONObject("user").containsKey("userId")){
responseEntity = new ResponseEntity<String>("用户或密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
JSONObject userInfo = resultInfo.getJSONObject("user");
String userPwd = userInfo.getString("userPwd");
if(!userPwd.equals(paramInJson.getString("passwd"))){
responseEntity = new ResponseEntity<String>("密码错误", HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return ;
}
try {
Map userMap = new HashMap();
userMap.put(CommonConstant.LOGIN_USER_ID,userInfo.getString("userId"));
String token = AuthenticationFactory.createAndSaveToken(userMap);
userInfo.remove("userPwd");
userInfo.put("token",token);
responseEntity = new ResponseEntity<String>(userInfo.toJSONString(), HttpStatus.OK);
dataFlowContext.setResponseEntity(responseEntity);
}catch (Exception e){
logger.error("登录异常:",e);
throw new SMOException(ResponseConstant.RESULT_CODE_INNER_ERROR,"系统内部错误,请联系管理员");
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | 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
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
try {
File file = new File("/home/hc/img/"+ UUID.randomUUID().toString()+".jpg");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
out.write(fileImg);
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
//String context = new BASE64Encoder().encode(fileImg);
String context = Base64Convert.byteToBase64(fileImg);
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
} | #vulnerable code
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
try {
File file = new File("/home/hc/img/"+ UUID.randomUUID().toString()+".jpg");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
out.write(fileImg);
}catch (Exception e){
e.printStackTrace();
}
//String context = new BASE64Encoder().encode(fileImg);
String context = Base64Convert.byteToBase64(fileImg);
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
//JSONObject outParam = null;
ResponseEntity<String> responseEntity = null;
Map<String, String> reqHeader = context.getRequestHeaders();
String communityId = reqHeader.get("communityId");
String machineCode = reqHeader.get("machinecode");
HttpHeaders headers = new HttpHeaders();
for (String key : reqHeader.keySet()) {
if (key.toLowerCase().equals("content-length")) {
continue;
}
headers.add(key, reqHeader.get(key));
}
//根据设备编码查询 设备信息
MachineDto machineDto = new MachineDto();
machineDto.setMachineCode(machineCode);
machineDto.setCommunityId(communityId);
List<MachineDto> machineDtos = machineInnerServiceSMOImpl.queryMachines(machineDto);
if (machineDtos == null || machineDtos.size() < 1) {
responseEntity = MachineResDataVo.getResData(MachineResDataVo.CODE_ERROR,"该设备【" + machineCode + "】未在该小区【" + communityId + "】注册");
context.setResponseEntity(responseEntity);
return;
}
//设备方向
String direction = machineDtos.get(0).getDirection();
//进入
if (MACHINE_DIRECTION_IN.equals(direction)) {
dealCarIn(event, context, reqJson, machineDtos.get(0), communityId);
} else {
dealCarOut(event, context, reqJson, machineDtos.get(0), communityId);
}
} | #vulnerable code
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
JSONObject outParam = null;
ResponseEntity<String> responseEntity = null;
Map<String, String> reqHeader = context.getRequestHeaders();
String communityId = reqHeader.get("communityId");
String machineCode = reqHeader.get("machinecode");
HttpHeaders headers = new HttpHeaders();
for (String key : reqHeader.keySet()) {
if (key.toLowerCase().equals("content-length")) {
continue;
}
headers.add(key, reqHeader.get(key));
}
//根据设备编码查询 设备信息
MachineDto machineDto = new MachineDto();
machineDto.setMachineCode(machineCode);
machineDto.setCommunityId(communityId);
List<MachineDto> machineDtos = machineInnerServiceSMOImpl.queryMachines(machineDto);
if (machineDtos == null || machineDtos.size() < 1) {
outParam.put("code", -1);
outParam.put("message", "该设备【" + machineCode + "】未在该小区【" + communityId + "】注册");
responseEntity = new ResponseEntity<>(outParam.toJSONString(), headers, HttpStatus.OK);
context.setResponseEntity(responseEntity);
return;
}
//设备方向
String direction = machineDtos.get(0).getDirection();
//进入
if (MACHINE_DIRECTION_IN.equals(direction)) {
dealCarIn(event, context, reqJson, machineDtos.get(0), communityId);
} else {
dealCarOut(event, context, reqJson, machineDtos.get(0), communityId);
}
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private JSONObject builderStaffInfo(JSONObject paramObj, DataFlowContext dataFlowContext) {
UserDto userDto = new UserDto();
userDto.setStatusCd("0");
userDto.setUserId(paramObj.getString("userId"));
List<UserDto> userDtos = userInnerServiceSMOImpl.getUserHasPwd(userDto);
Assert.listOnlyOne(userDtos, "数据错误查询到多条用户信息或单条");
JSONObject userInfo = JSONObject.parseObject(JSONObject.toJSONString(userDtos.get(0)));
if (!paramObj.getString("oldPwd").equals(userDtos.get(0).getPassword())) {
throw new IllegalArgumentException("原始密码错误");
}
userInfo.putAll(paramObj);
userInfo.put("password", paramObj.getString("newPwd"));
return userInfo;
} | #vulnerable code
private JSONObject builderStaffInfo(JSONObject paramObj, DataFlowContext dataFlowContext) {
//首先根据员工ID查询员工信息,根据员工信息修改相应的数据
ResponseEntity responseEntity = null;
AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_USERINFO);
if (appService == null) {
throw new ListenerExecuteException(1999, "当前没有权限访问" + ServiceCodeConstant.SERVICE_CODE_QUERY_USER_USERINFO);
}
String requestUrl = appService.getUrl() + "?userId=" + paramObj.getString("userId");
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(), ServiceCodeConstant.SERVICE_CODE_QUERY_USER_USERINFO);
dataFlowContext.getRequestHeaders().put("REQUEST_URL", requestUrl);
HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
doRequest(dataFlowContext, appService, httpEntity);
responseEntity = dataFlowContext.getResponseEntity();
if (responseEntity.getStatusCode() != HttpStatus.OK) {
dataFlowContext.setResponseEntity(responseEntity);
}
JSONObject userInfo = JSONObject.parseObject(responseEntity.getBody().toString());
if (!paramObj.getString("oldPwd").equals(userInfo.getString("password"))) {
throw new IllegalArgumentException("原始密码错误");
}
userInfo.putAll(paramObj);
userInfo.put("password", paramObj.getString("newPwd"));
return userInfo;
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static List<com.java110.entity.order.Business> getSynchronousBusinesses(IOrderDataFlowContext dataFlow){
List<com.java110.entity.order.Business> syschronousBusinesses = new ArrayList<com.java110.entity.order.Business>();
for(com.java110.entity.order.Business business :dataFlow.getBusinessList()){
if(CommonConstant.ORDER_INVOKE_METHOD_SYNCHRONOUS.equals(business.getInvokeModel()) || StringUtil.isEmpty(business.getInvokeModel())){
syschronousBusinesses.add(business);
}
}
if(syschronousBusinesses.size() > 0) {
Collections.sort(syschronousBusinesses);
}
return syschronousBusinesses;
} | #vulnerable code
public static List<com.java110.entity.order.Business> getSynchronousBusinesses(IOrderDataFlowContext dataFlow){
AppService service = null;
AppRoute route = null;
List<com.java110.entity.order.Business> syschronousBusinesses = new ArrayList<com.java110.entity.order.Business>();
for(com.java110.entity.order.Business business :dataFlow.getBusinessList()){
if(CommonConstant.ORDER_INVOKE_METHOD_SYNCHRONOUS.equals(business.getInvokeModel()) || StringUtil.isEmpty(business.getInvokeModel())){
business.setSeq(service.getSeq());
syschronousBusinesses.add(business);
}
}
if(syschronousBusinesses.size() > 0) {
Collections.sort(syschronousBusinesses);
}
return syschronousBusinesses;
}
#location 8
#vulnerability type NULL_DEREFERENCE | 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
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 Object call(String method, Object[] params) throws XMLRPCException {
return new Caller().call(method, params);
} | #vulnerable code
public Object call(String method, Object[] params) throws XMLRPCException {
try {
Call c = createCall(method, params);
URLConnection conn = this.url.openConnection();
if(!(conn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("The URL is not for a http connection.");
}
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod(HTTP_POST);
http.setDoOutput(true);
http.setDoInput(true);
// Set the request parameters
for(Map.Entry<String,String> param : httpParameters.entrySet()) {
http.setRequestProperty(param.getKey(), param.getValue());
}
OutputStreamWriter stream = new OutputStreamWriter(http.getOutputStream());
stream.write(c.getXML());
stream.flush();
stream.close();
InputStream istream = http.getInputStream();
if(http.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new XMLRPCException("The status code of the http response must be 200.");
}
// Check for strict parameters
if(isFlagSet(FLAGS_STRICT)) {
if(!http.getContentType().startsWith(TYPE_XML)) {
throw new XMLRPCException("The Content-Type of the response must be text/xml.");
}
}
return responseParser.parse(istream);
} catch (IOException ex) {
throw new XMLRPCException(ex);
}
}
#location 41
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object call(String method, Object[] params) throws XMLRPCException {
return new Caller().call(method, params);
} | #vulnerable code
public Object call(String method, Object[] params) throws XMLRPCException {
try {
Call c = createCall(method, params);
URLConnection conn = this.url.openConnection();
if(!(conn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("The URL is not for a http connection.");
}
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod(HTTP_POST);
http.setDoOutput(true);
http.setDoInput(true);
// Set the request parameters
for(Map.Entry<String,String> param : httpParameters.entrySet()) {
http.setRequestProperty(param.getKey(), param.getValue());
}
OutputStreamWriter stream = new OutputStreamWriter(http.getOutputStream());
stream.write(c.getXML());
stream.flush();
stream.close();
InputStream istream = http.getInputStream();
if(http.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new XMLRPCException("The status code of the http response must be 200.");
}
// Check for strict parameters
if(isFlagSet(FLAGS_STRICT)) {
if(!http.getContentType().startsWith(TYPE_XML)) {
throw new XMLRPCException("The Content-Type of the response must be text/xml.");
}
}
return responseParser.parse(istream);
} catch (IOException ex) {
throw new XMLRPCException(ex);
}
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canParseMilliseconds() throws Exception {
Date ms500 = (Date) new DateTimeSerializer(false).deserialize("1985-03-04T12:21:36.5");
assertEquals(500, ms500.getTime() - new Date(85, 2, 4, 12, 21, 36).getTime());
} | #vulnerable code
@Test
public void canParseMilliseconds() throws Exception {
Date ms500 = (Date) new DateTimeSerializer().deserialize("1985-03-04T12:21:36.5");
assertEquals(500, ms500.getTime() - new Date(85, 2, 4, 12, 21, 36).getTime());
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object call(String method, Object[] params) throws XMLRPCException {
return new Caller().call(method, params);
} | #vulnerable code
public Object call(String method, Object[] params) throws XMLRPCException {
try {
Call c = createCall(method, params);
URLConnection conn = this.url.openConnection();
if(!(conn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("The URL is not for a http connection.");
}
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod(HTTP_POST);
http.setDoOutput(true);
http.setDoInput(true);
// Set the request parameters
for(Map.Entry<String,String> param : httpParameters.entrySet()) {
http.setRequestProperty(param.getKey(), param.getValue());
}
OutputStreamWriter stream = new OutputStreamWriter(http.getOutputStream());
stream.write(c.getXML());
stream.flush();
stream.close();
InputStream istream = http.getInputStream();
if(http.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new XMLRPCException("The status code of the http response must be 200.");
}
// Check for strict parameters
if(isFlagSet(FLAGS_STRICT)) {
if(!http.getContentType().startsWith(TYPE_XML)) {
throw new XMLRPCException("The Content-Type of the response must be text/xml.");
}
}
return responseParser.parse(istream);
} catch (IOException ex) {
throw new XMLRPCException(ex);
}
}
#location 41
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int launch() throws Throwable {
int returnCode = -1;
Thread t = Thread.currentThread();
String currentThreadName = t.getName();
t.setName("Executing "+ env.displayName());
before();
try {
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
Class<?> c = bootstrap.hasClass(RUNNER_CLASS_NAME)? Class.forName(RUNNER_CLASS_NAME) : getRunnerClassFromJar();
returnCode = (int)c.getMethod("run", Bootstrap.class).invoke(c.newInstance(), bootstrap);
} finally {
after();
t.setName(currentThreadName);
}
return returnCode;
} | #vulnerable code
public int launch() throws Throwable {
int returnCode = -1;
Thread t = Thread.currentThread();
String currentThreadName = t.getName();
t.setName("Executing "+ env.displayName());
before();
try {
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
ClassLoader cl = new ClassLoaderBuilder(jenkins.getPluginManager().uberClassLoader)
.collectJars(new File(bootstrap.appRepo, "io/jenkins/jenkinsfile-runner/payload"))
.make();
Class<?> c = cl.loadClass("io.jenkins.jenkinsfile.runner.Runner");
returnCode = (int)c.getMethod("run", Bootstrap.class).invoke(c.newInstance(), bootstrap);
} finally {
after();
t.setName(currentThreadName);
}
return returnCode;
}
#location 14
#vulnerability type RESOURCE_LEAK | 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 31
#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
@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
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 IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
} | #vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
}
#location 35
#vulnerability type CHECKERS_PRINTF_ARGS | 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
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 52
#vulnerability type RESOURCE_LEAK | 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
@Test
public void testReRegisterHost() throws Exception {
// Register the host & add some fake data to its status & config dirs
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1));
zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1));
final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1));
// ... and then re-register it
final String newId = UUID.randomUUID().toString();
ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId);
// Verify that the host-id was updated
assertEquals(newId, new String(zkClient.getData(idPath)));
// Verify that /status/hosts/<host>/jobs exists and is EMPTY
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)),
contains(Paths.statusHostJobs(HOSTNAME)));
// Verify that re-registering didn't change the nodes in /config/hosts/<host>/jobs
assertEquals(
jobConfigStat,
zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1))
);
} | #vulnerable code
@Test
public void testReRegisterHost() throws Exception {
ZooKeeperTestingServerManager testingServerManager = null;
try {
testingServerManager = new ZooKeeperTestingServerManager();
testingServerManager.awaitUp(5, TimeUnit.SECONDS);
final ZooKeeperClient zkClient = new DefaultZooKeeperClient(
testingServerManager.curatorWithSuperAuth());
// Register the host & add some fake data to its status & config dirs
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1));
zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1));
final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1));
// ... and then re-register it
final String newId = UUID.randomUUID().toString();
ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId);
// Verify that the host-id was updated
assertEquals(newId, new String(zkClient.getData(idPath)));
// Verify that /status/hosts/<host>/jobs exists and is EMPTY
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)),
contains(Paths.statusHostJobs(HOSTNAME)));
// Verify that re-registering didn't change the nodes in /config/hosts/<host>/jobs
assertEquals(
jobConfigStat,
zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1))
);
} finally {
if (testingServerManager != null) {
testingServerManager.close();
}
}
}
#location 26
#vulnerability type NULL_DEREFERENCE | 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
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
} | #vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws IOException, ExecutionException, InterruptedException {
final boolean yes = options.getBoolean(yesArg.getDest());
final boolean force = options.getBoolean(forceArg.getDest());
if (force) {
log.warn("If you are using '--force' to skip the interactive prompt, " +
"note that we have deprecated it. Please use '--yes'.");
}
if (!yes && !force) {
out.printf("This will remove the job %s%n", jobId);
final boolean confirmed = Utils.userConfirmed(out, stdin);
if (!confirmed) {
return 1;
}
}
if (!json) {
out.printf("Removing job %s%n", jobId);
}
int code = 0;
final String token = options.getString(tokenArg.getDest());
final JobDeleteResponse response = client.deleteJob(jobId, token).get();
if (!json) {
out.printf("%s: ", jobId);
}
if (response.getStatus() == JobDeleteResponse.Status.OK) {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(response.toJsonString());
} else {
out.printf("failed: %s%n", response);
}
code = 1;
}
return code;
}
#location 35
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
} | #vulnerable code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 14
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Builder builder(final String profile) {
return builder(profile, System.getenv());
} | #vulnerable code
public static Builder builder(final String profile) {
return new Builder(profile);
}
#location 2
#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 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
@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
protected ZooKeeperTestManager zooKeeperTestManager() {
return new ZooKeeperTestingServerManager();
} | #vulnerable code
protected ZooKeeperTestManager zooKeeperTestManager() {
return new ZooKeeperTestingServerManager(zooKeeperNamespace);
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.print(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
} | #vulnerable code
public static int setGoalOnHosts(final HeliosClient client, final PrintStream out,
final boolean json, final List<String> hosts,
final Deployment deployment, final String token)
throws InterruptedException, ExecutionException {
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 14
#vulnerability type CHECKERS_PRINTF_ARGS | 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
@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 46
#vulnerability type RESOURCE_LEAK | 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
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
@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
@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
@Test
public void test() throws Exception {
startDefaultMaster();
final Range<Integer> portRange = temporaryPorts.localPortRange("agent1", 2);
final AgentMain agent1 = startDefaultAgent(testHost(), "--port-range=" +
portRange.lowerEndpoint() + ":" +
portRange.upperEndpoint());
try (final DefaultDockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri())) {
final HeliosClient client = defaultClient();
awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES);
final Map<String, PortMapping> ports1 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort1));
final ImmutableMap<String, PortMapping> expectedMapping1 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint()),
"bar", PortMapping.of(4712, externalPort1));
final Map<String, PortMapping> ports2 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort2));
final ImmutableMap<String, PortMapping> expectedMapping2 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint() + 1),
"bar", PortMapping.of(4712, externalPort2));
final JobId jobId1 = createJob(testJobName + 1, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports1);
assertNotNull(jobId1);
deployJob(jobId1, testHost());
final TaskStatus firstTaskStatus1 = awaitJobState(client, testHost(), jobId1, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
final JobId jobId2 = createJob(testJobName + 2, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports2);
assertNotNull(jobId2);
deployJob(jobId2, testHost());
final TaskStatus firstTaskStatus2 = awaitJobState(client, testHost(), jobId2, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
assertEquals(expectedMapping1, firstTaskStatus1.getPorts());
assertEquals(expectedMapping2, firstTaskStatus2.getPorts());
// TODO (dano): the supervisor should report the allocated ports at all times
// Verify that port allocation is kept across container restarts
dockerClient.killContainer(firstTaskStatus1.getContainerId());
final TaskStatus restartedTaskStatus1 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId1);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus1.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping1, restartedTaskStatus1.getPorts());
// Verify that port allocation is kept across agent restarts
agent1.stopAsync().awaitTerminated();
dockerClient.killContainer(firstTaskStatus2.getContainerId());
startDefaultAgent(testHost());
final TaskStatus restartedTaskStatus2 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId2);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus2.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping2, restartedTaskStatus2.getPorts());
}
} | #vulnerable code
@Test
public void test() throws Exception {
startDefaultMaster();
final Range<Integer> portRange = temporaryPorts.localPortRange("agent1", 2);
final AgentMain agent1 = startDefaultAgent(testHost(), "--port-range=" +
portRange.lowerEndpoint() + ":" +
portRange.upperEndpoint());
final DockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri());
final HeliosClient client = defaultClient();
awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES);
final Map<String, PortMapping> ports1 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort1));
final ImmutableMap<String, PortMapping> expectedMapping1 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint()),
"bar", PortMapping.of(4712, externalPort1));
final Map<String, PortMapping> ports2 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort2));
final ImmutableMap<String, PortMapping> expectedMapping2 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint() + 1),
"bar", PortMapping.of(4712, externalPort2));
final JobId jobId1 = createJob(testJobName + 1, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports1);
assertNotNull(jobId1);
deployJob(jobId1, testHost());
final TaskStatus firstTaskStatus1 = awaitJobState(client, testHost(), jobId1, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
final JobId jobId2 = createJob(testJobName + 2, testJobVersion, "busybox", IDLE_COMMAND,
EMPTY_ENV, ports2);
assertNotNull(jobId2);
deployJob(jobId2, testHost());
final TaskStatus firstTaskStatus2 = awaitJobState(client, testHost(), jobId2, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
assertEquals(expectedMapping1, firstTaskStatus1.getPorts());
assertEquals(expectedMapping2, firstTaskStatus2.getPorts());
// TODO (dano): the supervisor should report the allocated ports at all times
// Verify that port allocation is kept across container restarts
dockerClient.killContainer(firstTaskStatus1.getContainerId());
final TaskStatus restartedTaskStatus1 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId1);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus1.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping1, restartedTaskStatus1.getPorts());
// Verify that port allocation is kept across agent restarts
agent1.stopAsync().awaitTerminated();
dockerClient.killContainer(firstTaskStatus2.getContainerId());
startDefaultAgent(testHost());
final TaskStatus restartedTaskStatus2 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId2);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus2.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping2, restartedTaskStatus2.getPorts());
}
#location 64
#vulnerability type RESOURCE_LEAK | 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
@Override
public boolean deleteLogic(@NotEmpty List<Integer> ids) {
BladeUser user = SecureUtil.getUser();
T entity = BeanUtil.newInstance(modelClass);
entity.setUpdateUser(Objects.requireNonNull(user).getUserId());
entity.setUpdateTime(LocalDateTime.now());
return super.removeByIds(ids);
} | #vulnerable code
@Override
public boolean deleteLogic(@NotEmpty List<Integer> ids) {
BladeUser user = SecureUtil.getUser();
T entity = BeanUtil.newInstance(modelClass);
entity.setUpdateUser(user.getUserId());
entity.setUpdateTime(LocalDateTime.now());
return super.update(entity, Wrappers.<T>update().lambda().in(T::getId, ids)) && super.removeByIds(ids);
}
#location 5
#vulnerability type NULL_DEREFERENCE | 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
@Override
public boolean save(T entity) {
BladeUser user = SecureUtil.getUser();
if (user != null) {
entity.setCreateUser(user.getUserId());
entity.setUpdateUser(user.getUserId());
}
LocalDateTime now = LocalDateTime.now();
entity.setCreateTime(now);
entity.setUpdateTime(now);
if (entity.getStatus() == null) {
entity.setStatus(BladeConstant.DB_STATUS_NORMAL);
}
entity.setIsDeleted(BladeConstant.DB_NOT_DELETED);
return super.save(entity);
} | #vulnerable code
@Override
public boolean save(T entity) {
BladeUser user = SecureUtil.getUser();
LocalDateTime now = LocalDateTime.now();
entity.setCreateUser(Objects.requireNonNull(user).getUserId());
entity.setCreateTime(now);
entity.setUpdateUser(user.getUserId());
entity.setUpdateTime(now);
entity.setStatus(BladeConstant.DB_STATUS_NORMAL);
entity.setIsDeleted(BladeConstant.DB_NOT_DELETED);
return super.save(entity);
}
#location 7
#vulnerability type NULL_DEREFERENCE | 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<UserCounts> counts(String source, String accessToken, List<String> uids) {
if (uids == null || uids.size() > 100) {
throw new SocialException("需要获取数据的用户UID,必须且最多不超过100个");
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addParameter(params, "uids", StringUtils.join(uids, ","));
String result = weibo.post("https://api.weibo.com/2/users/domain_show.json", params);
return Result.parse(result, UserCounts.class);
} | #vulnerable code
public Result<UserCounts> counts(String source, String accessToken, List<String> uids) {
if (uids == null || uids.size() > 100) {
throw new SocialException("需要获取数据的用户UID,必须且最多不超过100个");
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addNotNullParameter(params, "source", source);
weibo.addNotNullParameter(params, "access_token", accessToken);
weibo.addParameter(params, "uids", StringUtils.join(uids, ","));
String result = weibo.post("https://api.weibo.com/2/users/domain_show.json", params);
return Result.perse(result, UserCounts.class);
}
#location 11
#vulnerability type NULL_DEREFERENCE | 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) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "client_id", clientId);
weibo.addParameter(params, "client_secret", clientSecret);
weibo.addParameter(params, "grant_type", grantType);
if ("authorization_code".equals(grantType)) {
weibo.addParameter(params, "code", code);
weibo.addParameter(params, "redirect_uri", redirectUri);
}
String result = weibo.post("https://api.weibo.com/oauth2/access_token", params);
return Result.parse(result, AccessToken.class);
} | #vulnerable code
public Result<AccessToken> accessToken(String clientId, String clientSecret, String grantType,
String code, String redirectUri) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
weibo.addParameter(params, "client_id", clientId);
weibo.addParameter(params, "client_secret", clientSecret);
weibo.addParameter(params, "grant_type", grantType);
if ("authorization_code".equals(grantType)) {
weibo.addParameter(params, "code", code);
weibo.addParameter(params, "redirect_uri", redirectUri);
}
String result = weibo.post("https://api.weibo.com/oauth2/access_token", params);
return Result.perse(result, AccessToken.class);
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Result<AccessToken> refreshAccessToken(String clientId, String clientSecret,
String grantType, String refreshToken, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "refresh_token", refreshToken);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params);
return parseAccessTokenResult(result);
} | #vulnerable code
public Result<AccessToken> refreshAccessToken(String clientId, String clientSecret,
String grantType, String refreshToken, Boolean wap) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
connect.addParameter(params, "client_id", clientId);
connect.addParameter(params, "client_secret", clientSecret);
connect.addParameter(params, "grant_type", grantType);
connect.addParameter(params, "refresh_token", refreshToken);
String url = "https://graph.qq.com/oauth2.0/token";
if (Boolean.TRUE.equals(wap)) {
url = "https://graph.z.qq.com/moc2/token";
}
String result = connect.get(url, params);
String[] results = result.split("\\&");
JSONObject jsonObject = new JSONObject();
for (String param : results) {
String[] keyValue = param.split("\\=");
jsonObject.put(keyValue[0], keyValue.length > 0 ? keyValue[1] : null);
}
String errorCode = jsonObject.optString("code", null);
if (errorCode != null) {
jsonObject.put("ret", errorCode);// To match Error.parse()
}
return Result.parse(jsonObject, AccessToken.class);
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.