简体   繁体   中英

How to regex-replace all occurrences of ${…} by <c:out value=“${…}” />

I have unprotected JSPs which have XSS holes. I need to replace all ${...} strings which are not already inside a <c:out value="${...}" /> tag by a <c:out value="${...}" /> .

For example,

<select>
   <option value="${foo}">label</option>
</select>    
${bar}
<c:out value="${message}" />

needs to be regex-replaced to the following:

<select>
   <option value="<c:out value="${foo}" />">label</option>
</select>    
<c:out value="${bar}" />
<c:out value="${message}" />

It sounds like your starting text has a mixture of <c:out value="${...}" /> and ${...} in it. If that's the case, you could try something like this:

str = str.replaceAll(
             "(?:<c:out\\s+value=\")?\\$\\{([^}]*)\\}(?:\"\\s*/>)?", 
             "<c:out value=\"\\${$1}\" />"
      );

I'm a little rusty on my Java regex syntax, so check that I have the backslashes right. Otherwise, I think that will work.

Regex is not the tool to use when requiring context. However, it would be simple enough to do in two steps by first replacing all instances of <c:out value="${...}" /> to ${...} and then all ${...} to <c:out value="${...}" /> .

Regular expressions

\${[^}]+}
<c:out value="\${[^}]+}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM