Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Signed-off-by: Ceki Gulcu <ceki@qos.ch>
  • Loading branch information
ceki committed Dec 1, 2023
1 parent 4573294 commit bb09515
Show file tree
Hide file tree
Showing 8 changed files with 275 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package ch.qos.logback.classic.spi;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
Expand All @@ -38,6 +39,7 @@ public class LoggingEventVO implements ILoggingEvent, Serializable {

private static final int NULL_ARGUMENT_ARRAY = -1;
private static final String NULL_ARGUMENT_ARRAY_ELEMENT = "NULL_ARGUMENT_ARRAY_ELEMENT";
private static final int ARGUMENT_ARRAY_DESERIALIZATION_LIMIT = 128;

private String threadName;
private String loggerName;
Expand Down Expand Up @@ -181,6 +183,11 @@ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundE
level = Level.toLevel(levelInt);

int argArrayLen = in.readInt();
// Prevent DOS attacks via large or negative arrays
if (argArrayLen < NULL_ARGUMENT_ARRAY || argArrayLen > ARGUMENT_ARRAY_DESERIALIZATION_LIMIT) {
throw new InvalidObjectException("Argument array length is invalid: " + argArrayLen);
}

if (argArrayLen != NULL_ARGUMENT_ARRAY) {
argumentArray = new String[argArrayLen];
for (int i = 0; i < argArrayLen; i++) {
Expand Down
30 changes: 30 additions & 0 deletions logback-classic/src/test/input/issue/logback-1754.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Logback: the reliable, generic, fast and flexible logging framework.
~ Copyright (C) 1999-2023, QOS.ch. All rights reserved.
~
~ This program and the accompanying materials are dual-licensed under
~ either the terms of the Eclipse Public License v1.0 as published by
~ the Eclipse Foundation
~
~ or (per the licensee's choosing)
~
~ under the terms of the GNU Lesser General Public License version 2.1
~ as published by the Free Software Foundation.
-->

<configuration debug="true">
<appender name="GENERAL" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logback_1754_targetDirectory}/test-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>120</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date{HH:mm:ss.SSS} [%level] %logger{0} [%thread] [%class{3}:%line] : %msg%n</pattern>
</encoder>
<prudent>true</prudent>
</appender>
<root level="debug">
<appender-ref ref="GENERAL" />
</root>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2023, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/

package ch.qos.logback.classic.issue.logback_1754;

import ch.qos.logback.classic.ClassicConstants;
import ch.qos.logback.classic.ClassicTestConstants;
import ch.qos.logback.core.testUtil.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import static ch.qos.logback.classic.util.ContextInitializer.CONFIG_FILE_PROPERTY;

public class LogbackTest {

private static final int THREADS = 16;

private void runTest() {

int diff = RandomUtil.getPositiveInt();
//System.setProperty("logback.statusListenerClass", "sysout");
System.setProperty(CONFIG_FILE_PROPERTY, ClassicTestConstants.INPUT_PREFIX+"issue/logback-1754.xml");
System.setProperty("logback_1754_targetDirectory", ClassicTestConstants.OUTPUT_DIR_PREFIX+"safeWrite_"+diff);

CountDownLatch latch = new CountDownLatch(THREADS);
List<Thread> threads = new ArrayList<Thread>(THREADS);
for (int i = 0; i < THREADS; i++) {
LoggerThread thread = new LoggerThread(latch, "message from thread " + i);
thread.start();
threads.add(thread);
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}

public static void main(String... args) {
new LogbackTest().runTest();
}

private static final class LoggerThread extends Thread {
private static final Logger LOG = LoggerFactory.getLogger(LoggerThread.class);
private final CountDownLatch latch;
private final String message;

LoggerThread(CountDownLatch latch, String message) {
setDaemon(false);
this.latch = latch;
this.message = message;
}

@Override
public void run() {
latch.countDown();
LOG.info(message);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
/**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2023, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.core.net;

import ch.qos.logback.core.util.EnvUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -22,10 +39,12 @@ public class HardenedObjectInputStream extends ObjectInputStream {

final List<String> whitelistedClassNames;
final static String[] JAVA_PACKAGES = new String[] { "java.lang", "java.util" };
final private static int DEPTH_LIMIT = 16;
final private static int ARRAY_LIMIT = 10000;

public HardenedObjectInputStream(InputStream in, String[] whilelist) throws IOException {
super(in);

initObjectFilter();
this.whitelistedClassNames = new ArrayList<String>();
if (whilelist != null) {
for (int i = 0; i < whilelist.length; i++) {
Expand All @@ -36,11 +55,43 @@ public HardenedObjectInputStream(InputStream in, String[] whilelist) throws IOEx

public HardenedObjectInputStream(InputStream in, List<String> whitelist) throws IOException {
super(in);

initObjectFilter();
this.whitelistedClassNames = new ArrayList<String>();
this.whitelistedClassNames.addAll(whitelist);
}

private void initObjectFilter() {

// invoke the following code by reflection
// this.setObjectInputFilter(ObjectInputFilter.Config.createFilter(
// "maxarray=" + ARRAY_LIMIT + ";maxdepth=" + DEPTH_LIMIT + ";"
// ));
if(EnvUtil.isJDK9OrHigher()) {
try {
ClassLoader classLoader = this.getClass().getClassLoader();

Class oifClass = classLoader.loadClass("java.io.ObjectInputFilter");
Class oifConfigClass = classLoader.loadClass("java.io.ObjectInputFilter$Config");
Method setObjectInputFilterMethod = this.getClass().getMethod("setObjectInputFilter", oifClass);

Method createFilterMethod = oifConfigClass.getMethod("createFilter", String.class);
Object filter = createFilterMethod.invoke(null, "maxarray=" + ARRAY_LIMIT + ";maxdepth=" + DEPTH_LIMIT + ";");
setObjectInputFilterMethod.invoke(this, filter);
} catch (ClassNotFoundException e) {
// this code should be unreachable
throw new RuntimeException("Failed to initialize object filter", e);
} catch (InvocationTargetException e) {
// this code should be unreachable
throw new RuntimeException("Failed to initialize object filter", e);
} catch (NoSuchMethodException e) {
// this code should be unreachable
throw new RuntimeException("Failed to initialize object filter", e);
} catch (IllegalAccessException e) {
// this code should be unreachable
throw new RuntimeException("Failed to initialize object filter", e);
}
}
}
@Override
protected Class<?> resolveClass(ObjectStreamClass anObjectStreamClass) throws IOException, ClassNotFoundException {

Expand Down
39 changes: 24 additions & 15 deletions logback-core/src/main/java/ch/qos/logback/core/util/EnvUtil.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
* Copyright (C) 1999-2023, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
Expand All @@ -22,22 +22,27 @@
public class EnvUtil {

static private boolean isJDK_N_OrHigher(int n) {
List<String> versionList = new ArrayList<String>();
// this code should work at least until JDK 10 (assuming n parameter is
// always 6 or more)
for (int i = 0; i < 5; i++) {
versionList.add("1." + (n + i));
}

String javaVersion = System.getProperty("java.version");
if (javaVersion == null) {
String javaVersionStr = System.getProperty("java.version", "");
if (javaVersionStr.isEmpty())
return false;

int version = getJDKVersion(javaVersionStr);
return version > 0 && n <= version;
}

static public int getJDKVersion(String javaVersionStr) {
int version = 0;

for (char ch : javaVersionStr.toCharArray()) {
if (Character.isDigit(ch)) {
version = (version * 10) + (ch - 48);
} else if (version == 1) {
version = 0;
} else {
break;
}
}
for (String v : versionList) {
if (javaVersion.startsWith(v))
return true;
}
return false;
return version;
}

static public boolean isJDK5() {
Expand All @@ -52,6 +57,10 @@ static public boolean isJDK7OrHigher() {
return isJDK_N_OrHigher(7);
}

static public boolean isJDK9OrHigher() {
return isJDK_N_OrHigher(9);
}

static public boolean isJaninoAvailable() {
ClassLoader classLoader = EnvUtil.class.getClassLoader();
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package ch.qos.logback.core.net;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Set;

import ch.qos.logback.core.util.EnvUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -54,5 +59,47 @@ private void writeObject(ObjectOutputStream oos, Object o) throws IOException {
oos.flush();
oos.close();
}


@Test
public void denialOfService() throws ClassNotFoundException, IOException {

if(!EnvUtil.isJDK9OrHigher()) {
return;
}

ByteArrayInputStream bis = new ByteArrayInputStream(payload());
inputStream = new HardenedObjectInputStream(bis, whitelist);
try {
inputStream.readObject();
fail("InvalidClassException expected");
} catch(InvalidClassException e) {
}
finally {
inputStream.close();
}
}

private byte[] payload() throws IOException {
Set root = buildEvilHashset();
writeObject(oos, root);
return bos.toByteArray();
}

private Set buildEvilHashset() {
Set root = new HashSet();
Set s1 = root;
Set s2 = new HashSet();
for (int i = 0; i < 100; i++) {
Set t1 = new HashSet();
Set t2 = new HashSet();
t1.add("foo"); // make it not equal to t2
s1.add(t1);
s1.add(t2);
s2.add(t1);
s2.add(t2);
s1 = t1;
s2 = t2;
}
return root;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.Future;
Expand Down
Loading

0 comments on commit bb09515

Please sign in to comment.