background

As we all know, the game account and password are extremely important for players. If the account password is leaked, props, gold coins, clothing and so on in the game will change hands in a minute. Some big R players have game accounts worth tens of millions. In a game trading platform, there has been a case of self-theft: personnel use the server log view authority, out of a number of sellers of the game account and password, and then sold to the third party, tens of thousands of profits (fortunately found early, so timely stop loss).

In actual business, sensitive data such as user passwords, ID cards and mobile phone numbers should not be stored in clear text, let alone output to logs in clear text, so that people can easily obtain these information.

Implementation scheme

Use Logback to implement configurable log desensitization

1. Customize PatternLayout and add a Mask to Converter:

public class MaskPatternLayout extends PatternLayout { static { defaultConverterMap.put("mask",MaskMessageConverter.class.getName()); }}Copy the code

2. Customize MaskMessageConverter to do actual desensitization:

public class MaskMessageConverter extends MessageConverter { private static Map<String, Masker> maskRules = new HashMap<>(); static { maskRules.put("password",new PasswordMasker()); } public String convert(ILoggingEvent event) { String msg = event.getFormattedMessage(); Set<Entry<String, Masker>> entries = maskRules.entrySet(); for(Entry<String, Masker> entrie:entries){ String key = entrie.getKey(); Masker masker = entrie.getValue(); int index = -1; do{ index = msg.indexOf(key, index + 1); if(index ! = -1){ if(StringKeyWordUtil.isWordChar(msg, key, index)){ continue; } int valueStart = StringKeyWordUtil.getValueStartIndex(msg, index + key.length()); if(valueStart==-1){ continue; } int valueEnd = StringKeyWordUtil.getValueEndIndex(msg, valueStart); String subStr = msg.substring(valueStart, valueEnd); if(StringUtils.isNotEmpty(subStr)){ subStr = masker.handle(subStr); msg = msg.substring(0,valueStart) + subStr + msg.substring(valueEnd); } } }while(index ! = 1); } return msg; }}Copy the code

3. In logback. XML, specify layout for the logs that need desensitization as the custom desensitization PatternLayout above:

<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <! - desensitization configuration - > < layout class = "com.aligames.com mon. Log. MaskPatternLayout" > < pattern > % mask % n < / pattern > < / layout > < / encoder >Copy the code