Hamilton Lin Hamilton Lin - 1 year ago 104
Java Question

Regular Expression Qusetion(about search key word)

I use Eclipse to develop my web project,and use HP fortify scan my JAVA source code.
The report show that I have 7200 A1 Inject issue(Log forging).

the sample code show logger.info will cause log forging

public void storedProcedure(HttpServletResponse response,
@RequestParam("idn") String idn,
@RequestParam("agentNo")String agentNo){
logger.info("call idn :" + idn + ",agentNo="+agentNo); // log forging

And then,I find a solution use Spring framework HtmlUtil to escape
but too many code Scattered anywhere.
I want to change to logger for

logger.info("call idn :" + HtmlUtil.htmlEscape(idn)
",agentNo=" + HtmlUtil.htmlEscape(agentNo));

How can I use regular expression to find the line start with logger.info and find all the "+" variables replace

Answer Source

If you really need less code then I'd suggest you to do a helper

public static String[] htmlEscape(final String... args) {
     return Arrays.stream(args)

And use it this way

if (logger.isInfoEnabled()) {
    logger.info("call  idn:{}, agentNo={}", htmlEscape(idn, agentNo));

Note a call to isInfoEnabled. It prevents you from doing unnecessary arguments escaping if INFO loglevel is disabled. You can reduce this cpu overhead by a bit increased memory usage by using this tricky way to make it htmlEscape lazy evaluated

public static Object[] lazyHtmlEscape(final String... args) {
     return Arrays.stream(args)
                  .map(arg -> new Object {
                      public String toString() {
                          // here argument will be escaped only if
                          // toString method will be called
                          // (that happens if loglevel is enabled)
                          return HtmlUtil.htmlEscape(e);
logger.info("call  idn:{}, agentNo={}", lazyHtmlEscape(idn, agentNo));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download