The code example below is vulnerable to Log4Shell
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Example {
private static final Logger logger = LogManager.getLogger(Example.class);
public static void main(String[] args) {
String user = args[0];
String password = args[1];
logger.info("User " + user + " logged in successfully");
}
}
The Logger class from the Log4j library is used to log information about a user's login attempt. The logger.info method takes a string argument that is constructed by concatenating the user variable with a fixed string. This code is vulnerable to Log4Shell because if an attacker can control the value of the user variable, they can inject malicious code that will be executed by the Log4j library. An attacker might exploit this vulnerability:
java -jar Example.jar "$(gopher://127.0.0.1:12345/_Log4j_JNDI)"
To fix this vulnerability, you can update your Log4j version to a non-vulnerable version (version 2.15.0 or later). Alternatively, you can disable JNDI lookups in Log4j by adding the following system property to your application's startup script:
-Dlog4j2.formatMsgNoLookups=true
This prevents Log4j from performing JNDI lookups when formatting log messages. Here is an updated version of the example code that is not vulnerable to Log4Shell:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Example {
private static final Logger logger = LogManager.getLogger(Example.class);
public static void main(String[] args) {
String user = args[0];
String password = args[1];
logger.info("User {} logged in successfully", user);
}
}