LOG4J2-2707: ArrayIndexOutOfBoundsException in UuidUtil, when MAC address is longer than 6 bytes
Refactored static initializer of UuidUtil into a static method, so that a unit test is possible.
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/util/UuidUtil.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/util/UuidUtil.java
index 77d7f9f..fdf950f 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/util/UuidUtil.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/util/UuidUtil.java
@@ -65,6 +65,20 @@
static {
byte[] mac = NetUtils.getMacAddress();
+ LEAST = initialize(mac);
+ }
+
+ /* This class cannot be instantiated */
+ private UuidUtil() {
+ }
+
+ /**
+ * Initializes this class
+ *
+ * @param mac MAC address
+ * @return Least
+ */
+ static long initialize(byte[] mac) {
final Random randomGenerator = new SecureRandom();
if (mac == null || mac.length == 0) {
mac = new byte[6];
@@ -114,12 +128,7 @@
assigned = assigned == null ? Long.toString(rand) : assigned + ',' + Long.toString(rand);
System.setProperty(ASSIGNED_SEQUENCES, assigned);
- LEAST = buf.getLong() | rand << SHIFT_6;
- }
-
-
- /* This class cannot be instantiated */
- private UuidUtil() {
+ return buf.getLong() | rand << SHIFT_6;
}
/**
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java
index 556f765..da6a86e 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java
@@ -64,6 +64,19 @@
}
@Test
+ public void testInitialize() {
+ // Test if no ArrayIndexOutOfBoundsException is thrown for different Mac address lengths
+ for (int i=0; i < 10; i++) {
+ // Create MAC address byte array with i as size
+ byte[] mac = new byte[i];
+ for(int j=0; j < i; j++) {
+ mac[j] = (byte)j;
+ }
+ UuidUtil.initialize(mac);
+ }
+ }
+
+ @Test
public void testThreads() throws Exception {
final Thread[] threads = new Thread[THREADS];
final UUID[] uuids = new UUID[COUNT * THREADS];