Mask Passwords with Logback?

SingleShot picture SingleShot · Jan 5, 2011 · Viewed 11.8k times · Source

We currently generically log all XML documents coming in and going out of our system, and some of them contain passwords in the clear. We would like to be able to configure the logback logger/appender that is doing this to do some pattern matching or similar and if it detects a password is present to replace it (with asterisks most likely). Note we don't want to filter out the log entry, we want to mask a portion of it. I would appreciate advice on how this would be done with logback. Thanks.

Answer

Ceki picture Ceki · Jan 7, 2011

The logback version 0.9.27 introduced replacement capability. Replacements support regular expressions. For example, if the logged message was "userid=alice, pswd='my secret'", and the output pattern was

  "%d [%t] $logger - %msg%n",

you just modify the pattern to

 "%d [%t] $logger - %replace(%msg){"pswd='.*'", "pswd='xxx'"}%n"

Note that the above makes use of option quoting.

The previous log message would be output as "userid=alice, pswd='xxx'"

For blazing performance, you could also mark the log statement as CONFIDENTIAL and instruct %replace to perform replacement only for log statements marked as CONFIDENTIAL. Example,

 Marker confidential = MarkerFactory.getMarker("CONFIDENTIAL");
 logger.info(confidential, "userid={}, password='{}'", userid, password);

Unfortunately, the current version of logback does not yet support conditional replacements (based on markers or otherwise). However, you could easily write your own replacement code by extending ReplacingCompositeConverter. Shout on the logback-user mailing list if you need further assistance.