BAEL-4946 added in code for java deserialization vulnerabilities article

This commit is contained in:
Liam Garvie 2021-05-13 20:48:03 +01:00
parent 5c03fa6f4e
commit 8b115f4c8a
3 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,28 @@
package com.baeldung.deserialization.vulnerabilities;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
public class BadThing implements Serializable {
private static final long serialVersionUID = 0L;
Object looselyDefinedThing;
String methodName;
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
try {
Method method = looselyDefinedThing.getClass().getMethod(methodName);
method.invoke(looselyDefinedThing);
} catch (Exception e) {
// handle error...
}
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.deserialization.vulnerabilities;
import java.io.IOException;
import java.io.Serializable;
public class MyCustomAttackObject implements Serializable {
public static void methodThatTriggersAttack() {
try {
Runtime.getRuntime().exec("echo \"Oh, no! I've been hacked\"");
} catch (IOException e) {
// handle error...
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.deserialization.vulnerabilities;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class BadThingTest {
@Test
public void testCodeExecution() throws Exception {
BadThing bt = new BadThing();
bt.looselyDefinedThing = new MyCustomAttackObject();
bt.methodName = "methodThatTriggersAttack";
byte[] serializedObject = serialize(bt);
try (InputStream bis = new ByteArrayInputStream(serializedObject);
ObjectInputStream ois = new ObjectInputStream(bis)) {
ois.readObject(); // malicious code is run
}
}
private static byte[] serialize(Object object) throws Exception {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(object);
oos.flush();
return bos.toByteArray();
}
}
}