Tuesday, April 29, 2014

concurrent log4j

Log4j is the logging implementation on most JavaEE app-servers out there, so that's a good advert for its concurrency abilities.
Having said that, I have seen Log4j 1.2 deadlock under high load conditions. A bit of investigation highlighted some scarily bad synchronization in the source code. Apparently, this was fixed in Log4j 1.3, although development on this has slowed or stopped altogether - I get the feeling much of the source was unsalvageable.
However, if you're free to choose, then you should consider Logback instead, the spiritual successor to Log4j. It's a ground-up redesign, and is probably a better option for you.

Production settings file for log4j?

Log4j 1.2 is vulnerable to deadlocks when toString() produces nested logging.
It also has performance-killing lock synchronization issues under heavy concurrent load. Like Category callAppenders synchronization causes java.lang.Thread.State: BLOCKED and Move org.apache.log4j.Category to reentrant read/write locks.
One caveat is to always constrain root category level to at least INFO or higher. This would prevent logging calls from acquiring unnecessary locks mentioned in the above issues. Just limiting appender threshold is not sufficient as it is taken into account later. See explanation with publish/subscribe analogy. Nested categories of interest can be individually given lower priorities if needed.

Wednesday, April 23, 2014

Avoid XSS and allow some html tags with JavaScript

In order to prevent Application from XSS attacks I usually use following rules:
  1. Determine the level of security for your application.
    There are several tools that can protect your application as for me better security is provided by OWASPtools: ESAPI or AntySami.
    Note:Using Sanitization does not guarantee filtering of all malicious code, so tools can be more or less secure.
  2. Understand whether you need to perform sanitization on client, server or both sides. In most cases it's enough to do this on server side.
  3. Understand whether you need to preserve html tags (and what tags you need to preserve) or not. As it was stated previously not allowing html tags is more secure solution.
Based on this you can find a proper decision.
1. Personally for server code sanitization I used jSoup. As for me it's pretty good tool to do this.
Usually In order to check input vulnerability I am using following vector:
';alert(String.fromCharCode(88,83,83))//\';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//-->
">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
  1. In case you need prevent XSS on client side you can use following tools:
    a) JSSANItazer seems a bit outdated
    b) Dust - maintained by twitter; 
These tools easily can allow you to sanitize your input and mainly is answer for your question.
Server side tools mentioned above.
Regarding 3rd point. In case you don't need to handle html tags you can easily use ESAPI on server side andESAPI4JS on client side. As I understand it doesn't work for you.
When I read your task I understood that you are storing email message therefore In your case it's required to sanitize input on server side (using one of tools) and it's as per you to add it or not on client side. You need only decide whether add another sanitization on UI side or render your "preview page" on server.

Tuesday, April 22, 2014

How to access a file under WEB-INF folder in java class

ServletContext.getResourceAsStream() will load a file from a given path relative to the root of the WAR file. Something like:
ServletContext ctx;
InputStream configStream = ctx.getResourceAsStream("/WEB-INF/config.properties");
The major issue here is that you need access to the servlet context to be able to do this. You have that in a servlet or a filter, but not in a non-web component further back in the application. You have a few options:
  • Make the servlet context available from the web layer to the service layer, via an application-scoped variable, or injection, or some other way
  • Put the resource-loading code in the web layer, and expose that to the service layer
  • Load the configuration in the web layer, and pass it on to the service layer

Monday, April 21, 2014

Best regex to catch XSS (Cross-site Scripting) attack (in Java)?

Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily.
For example, see this list of obfuscated XSS attacks. Are you prepared to tailor a regex to prevent this real world attack on Yahoo and Hotmail on IE6/7/8?
<HTML><BODY>
xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time">
import namespace="t" implementation="#default#time2">
<t:set attributeName="innerHTML" to="XSS<SCRIPT DEFER>alert("XSS")</SCRIPT>">
</BODY></HTML>
How about this attack that works on IE6?
<TABLE BACKGROUND="javascript:alert('XSS')">
How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on that page adeptly notes:
The problem with it, is that the html must be clean. There are cases where you can pass in hacked html, and it won't match it, in which case it'll return the hacked html string as it won't match anything to replace. This isn't strictly whitelisting.
I would suggest a purpose built tool like AntiSamy. It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the configurable whitelist. The major difference is the ability to gracefully handle malformed HTML.
The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call:
public String toSafeHtml(String html) throws ScanException, PolicyException {

    Policy policy = Policy.getInstance(POLICY_FILE);
    AntiSamy antiSamy = new AntiSamy();
    CleanResults cleanResults = antiSamy.scan(html, policy);
    return cleanResults.getCleanHTML().trim();
}
http://stackoverflow.com/questions/24723/best-regex-to-catch-xss-cross-site-scripting-attack-in-java

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not duringprocessing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib tag or fn:escapeXml function for this. E.g.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>
and
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">
That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).
If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp; instead of & so that the enduser would literally see & instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

Thursday, April 17, 2014

A cycle was detected in the build path of project xxx - Build Path Problem

Mark Circular dependcies as "Warning" in Eclipse tool to avoid "A CYCLE WAS DETECTED IN THE BUILD PATH" error. In Eclipse got to :-> Windows -> Prefereneces -> Java-> Compiler -> Buliding -> Circular Depencies
Thanks

Tuesday, April 15, 2014

jQuery, simple polling example

function doPoll(){
    $.post('ajax/test.html', function(data) {
        alert(data);  // process results here
        setTimeout(doPoll,5000);
    });
}
http://stackoverflow.com/questions/6835835/jquery-simple-polling-example

Friday, April 11, 2014

MVC - Postback on clicking a radio button

If you had radio buttons like:
 type="radio" name="sex" value="male" /> Male
 />
 type="radio" name="sex" value="female" /> Female
You could add script (assuming you can use jQuery) on the page like:
Assuming you have an action method in the same controller as the one that generated your view:
public class YourController : Controller
{
    public ActionResult sex(string sex)
    {
        // do something awesome
        return Json(new { someValue = "testing!" });
    }
}
share|improve this answer

http://stackoverflow.com/questions/6916322/mvc-postback-on-clicking-a-radio-button