ESAPI encoding issue - esapi

We are trying to use ESAPI in our web app. We have following function in servlet.
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader(SearchConstants.CACHE_CONTROL_HEADER,
SearchConstants.MAX_AGE_ZERO);
response.setHeader(SearchConstants.CACHE_CONTROL_HEADER,
SearchConstants.NO_CACHE);
response.setDateHeader(SearchConstants.EXPIRES_HEADER, 0);
response.setHeader(SearchConstants.PRAGMA_HEADER, "no cache");
result = processRequest(request, response);
if (SearchConstants.XSLT_ERROR_MSG.equals(result)) {
LOGGER.error("XSLT ERROR FOR QUERY STRING: "
+ request.getQueryString());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} else if (SearchConstants.SEARCH_PAGE_MISSING_MSG.equals(result)) {
LOGGER.error("NOT FOUND ERROR FOR QUERY STRING: "
+ request.getQueryString());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
final PrintWriter out = response.getWriter();
out.println(result); // this works
// out.println(ESAPI.encoder().encodeForHTML(result));
}
}
In above code if I use out.println(ESAPI.encoder().encodeForHTML(result));, this actually prints html as text on browser. i.e. it's showing like simple text <html> other contents.. </html>, instead of rendering html page. result is nothing but html contents which needs to get rendred on client.
We are doing something wrong over here. Please provide some pointers. How we can achieve encoding over here?

The Solution for your problem is not encoding but to rendere Safe HTMl.. below is the solution
import org.owasp.validator.html.*; // Import AntiSamy
String POLICY_FILE_LOCATION = "antisamy-1.4.1.xml"; // Path to policy file
String dirtyInput = "<div><script>alert(1);</script></div>"; // Your HTML RESPONSE
Policy policy = Policy.getInstance(POLICY_FILE_LOCATION); // Create Policy object
AntiSamy as = new AntiSamy(); // Create AntiSamy object
CleanResults cr = as.scan(dirtyInput, policy, AntiSamy.SAX); // Scan dirtyInput
System.out.println(cr.getCleanHTML()); // Do something with your clean output!
Before you write this code ensure that you have following: antisamy.jar.
This jar needs below dependent jars:
xercesImpl.jar
batik.jar
nekohtml.jar
You will also need policy.xml file.

Sorry, I don't have time to go into details, and it appears that you already have a decent answer.
There is a way to do this in ESAPI. I suggest that calling Validator.getValidSafeHTML() method might be one way to do it. That method actually uses AntiSamy. Looking through the TestValidator.java JUnit tests should show how it's used. Unfortunately, documentation in that area is sorely lacking and it's code that I've had occasion or need to use.
Another way to go if you don't want to use ESAPI is to use the OWASP Java HTML Sanitizer Project. It is faster than AntiSamy, better maintained, and has minimal dependencies (maybe zero).
Hope that helps,
-kevin

Related

Changing jasper report parameters in runtime

I know, but we really need it.
We have a clear division of labor.
They create templates, I fill them in runtime according to some rules.
Can't teach my business to insert something like this and be sure they really did it ok(so can't move any logic to templates):
$P{risk_types}.get($F{risk_type}) ?: "UNDEFINED"
Also can not fill from files hardcoded in some adapter hadwritten by god-knows-who and unchangeable in runtime. It's a web app. Best option is to find a way to replace that file source from adapter to a ByteArrayStream.
SO:
Need to substitute contents of parameters(also default ones) at runtime.
example:
need to set JSON_INPUT_STREAM
Like this unsolved thread.
https://community.jaspersoft.com/questions/516611/changing-parameter-scriptlet
Really hope not to work on xml level, but xml also can't solve my problem as far as I tried.
Thank you!
The easiest and cleanest way we did this(bypassing usage of tons of deprecated documentation and unfinished bugged undocumented static antipatterned new features):
Create context with repository extension
SimpleJasperReportsContext jasperReportsContext = new SimpleJasperReportsContext();
jasperReportsContext.setExtensions(RepositoryService.class, Collections.singletonList(new MyRepositoryService(jasperReportsContext, yourOptionalParams)));
Fill this way(after compile and other usual actions)
JasperPrint print = JasperFillManager.getInstance(jasperReportsContext).fill(compiled, new HashMap<>());
Now your repository must extend default one to be hack-injected(cause of hodgie coded "isAssignableFrom") successfully
public class PrintFormsRepositoryService extends DefaultRepositoryService {
#Override
public InputStream getInputStream(RepositoryContext context, String uri) {
// return here your own good simple poj inputStream even from memory if you found source
// or pass to another repository service(default one probably)
return null;
}
}

Proper format for log4j2.xml RollingFile configuration

I am getting the following exception in my glassfish 4 application that uses log4j2:
SEVERE: ERROR StatusLogger Invalid URL C:/glassfish4/glassfish/domains/domain1/config/log4j2.xml java.net.MalformedURLException: Unknown protocol: c
I have the following section in my log4j2.xml:
<RollingFile name="RollingFile" fileName="C:/glassfish4/glassfish/domains/domain1/logs/ucsvc.log"
filePattern="C:/glassfish4/glassfish/domains/domain1/logs/$${date:yyyy-MM}/ucsvc-%d{MM-dd-yyyy}-%i.log">
I understand that if it's looking for a URL, then "C:/glassfish4/..." is not the correct format.
However, the rolling file part actually works: I see a log file and the rolled log files where I expect them.
If I change to a URL (e.g. file:///C/glassfish4/...) that doesn't work at all.
So should I ignore the exception? (everything seems to be working ok). Or can someone explain the correct format for this section of the configuration?
I have not yet fully determined why it is that the config file works for me as well as the OP, but, I can confirm that changing the path reference to a file:// url solves the problem (ie: gets rid of the error/warning/irritant).
In my IntelliJ Run/Debug configurations, for VM options, I have:
-Dlog4j.configurationFile=file://C:\dev\path\to\log4j2.xml
I can confirm that '\' are translated to '/' so, no worries there.
EDIT:
Okay, the whole thing works because they (the apache guys) try really hard to load the configuration and they do, in fact, load from the file as specified via the c:\... notation. They just throw up a rather misleading exception before continuing to try.
In ConfigurationFactory::getConfiguration:
**source = getInputFromURI(FileUtils.getCorrectedFilePathUri(config));**
} catch (Exception ex) {
// Ignore the error and try as a String.
}
if (source == null) {
final ClassLoader loader = this.getClass().getClassLoader();
**source = getInputFromString(config, loader);**
The first bolded line tries to load from a URL and fails, throwing the exception. The code then continues, pops into getInputFromString:
try {
final URL url = new URL(config);
return new ConfigurationSource(url.openStream(), FileUtils.fileFromURI(url.toURI()));
} catch (final Exception ex) {
final ConfigurationSource source = getInputFromResource(config, loader);
if (source == null) {
try {
**final File file = new File(config);
return new ConfigurationSource(new FileInputStream(file), file);**
Where it tries to load the config again, fails and falls into the catch, tries again, fails and finally succeeds on the bolded lines (dealing with a File).
Okay, the code lines I wanted in emphasize with bold are actually just wrapped in **; guess the site doesn't permit nested tags? Anyway, y'all get the meaning.
It's all a bit of a mess to read, but that's why it works even though you get that nasty-looking (and wholly misleading) exception.
Thanks Jon, i was searching all over.. this helped!
This is on Intellij 13, Tomcat 7.0.56
-Dlog4j.configurationFile=file://C:\Surendra\workspace\cmdb\resources\elasticityLogging.xml
The problem is not the contents of your log4j2.xml file.
The problem is that log4j2 cannot locate your log4j2.xml config file. If you look carefully at the error, the URL that is reported as invalid is C:/glassfish4/glassfish/domains/domain1/config/log4j2.xml: the config file.
I'm not sure why this is. Are you specifying the location of the config file via the system property -Dlog4j.configurationFile=path/to/log4j2.xml?
Still, if the application and logging works then perhaps there is no problem. Strange though. You can get more details about the log4j configuration by configuring <Configuration status="trace"> at the top of your log4j2.xml file. This will print log4j initialization details to the console.

Using Java.util.scanner with GWT

for some reason when I try to use scanner with gwt, i get the following error:
No source code is available for type java.util.Scanner; did you forget to inherit a required module?
I looked around and it seems the "No source code is available for type xxxx" errors are due to not having a Javascript equivalent type for the Java type.
Is scanner not able to be used with GWT?
Here is a snippet of my code:
import java.util.Scanner;
...
public void submit(){
String text = editor.getEditor().getText();
Scanner input = new Scanner(text);
while(input.hasNextLine()){
String line = input.nextLine();
if(line.contains("//")){
cInfo.setDone(false);
cInfo.setCode(text);
return;
}
cInfo.setDone(true);
cInfo.setCode(text);
}
}
}
java.util.Scanner is not part of the GWT JRE Emulation. If you need a detail overview of what is inside the emulation here is the link to the docs:
https://developers.google.com/web-toolkit/doc/latest/RefJreEmulation#Package_java_util
Your code (at least the one in the current version of your question) is probably[*] equivalent to
public void submit() {
String text = editor.getEditor().getText();
if ("".equals(text))
return;
cInfo.setDone(!text.contains("//"));
cInfo.setCode(text);
}
However, I have a feeling that this may not actually be what want to do (or is it?)
If you need to split strings on the client side, I usually recommend the Splitter class in Guava. Most of its methods are GwtCompatible, and (together with CharMatcher, Joiner, ...) it's great to use both on the client and server side of your Java code.
[*] assuming, that setDone and setCode are simple setters without side effects

Enforce Hyphens in .NET MVC 4.0 URL Structure

I'm looking specifically for a way to automatically hyphenate CamelCase actions and views. That is, I'm hoping I don't have to actually rename my views or add decorators to every ActionResult in the site.
So far, I've been using routes.MapRouteLowercase, as shown here. That works pretty well for the lowercase aspect of URL structure, but not hyphens. So I recently started playing with Canonicalize (install via NuGet), but it also doesn't have anything for hyphens yet.
I was trying...
routes.Canonicalize().NoWww().Pattern("([a-z0-9])([A-Z])", "$1-$2").Lowercase().NoTrailingSlash();
My regular expression definitely works the way I want it to as far as restructuring the URL properly, but those URLs aren't identified, of course. The file is still ChangePassword.cshtml, for example, so /account/change-password isn't going to point to that.
BTW, I'm still a bit rusty with .NET MVC. I haven't used it for a couple years and not since v2.0.
This might be a tad bit messy, but if you created a custom HttpHandler and RouteHandler then that should prevent you from having to rename all of your views and actions. Your handler could strip the hyphen from the requested action, which would change "change-password" to changepassword, rendering the ChangePassword action.
The code is shortened for brevity, but the important bits are there.
public void ProcessRequest(HttpContext context)
{
string controllerId = this.requestContext.RouteData.GetRequiredString("controller");
string view = this.requestContext.RouteData.GetRequiredString("action");
view = view.Replace("-", "");
this.requestContext.RouteData.Values["action"] = view;
IController controller = null;
IControllerFactory factory = null;
try
{
factory = ControllerBuilder.Current.GetControllerFactory();
controller = factory.CreateController(this.requestContext, controllerId);
if (controller != null)
{
controller.Execute(this.requestContext);
}
}
finally
{
factory.ReleaseController(controller);
}
}
I don't know if I implemented it the best way or not, that's just more or less taken from the first sample I came across. I tested the code myself so this does render the correct action/view and should do the trick.
I've developed an open source NuGet library for this problem which implicitly converts EveryMvc/Url to every-mvc/url.
Uppercase urls are problematic because cookie paths are case-sensitive, most of the internet is actually case-sensitive while Microsoft technologies treats urls as case-insensitive. (More on my blog post)
NuGet Package: https://www.nuget.org/packages/LowercaseDashedRoute/
To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the "Online" tab type "Lowercase Dashed Route", and it should pop up.
Alternatively, you can run this code in the Package Manager Console:
Install-Package LowercaseDashedRoute
After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:
routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
new DashedRouteHandler()
)
);
That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.
Open Source Project Url: https://github.com/AtaS/lowercase-dashed-route
Have you tried working with the URL Rewrite package? I think it pretty much what you are looking for.
http://www.iis.net/download/urlrewrite
Hanselman has a great example herE:
http://www.hanselman.com/blog/ASPNETMVCAndTheNewIIS7RewriteModule.aspx
Also, why don't you download something like ReSharper or CodeRush, and use it to refactor the Action and Route names? It's REALLY easy, and very safe.
It would time well spent, and much less time overall to fix your routing/action naming conventions with an hour of refactoring than all the hours you've already spent trying to alter the routing conventions to your needs.
Just a thought.
I tried the solution in the accepted answer above: Using the Canonicalize Pattern url strategy, and then also adding a custom IRouteHandler which then returns a custom IHttpHandler. It mostly worked. Here's one caveat I found:
With the typical {controller}/{action}/{id} default route, a controller named CatalogController, and an action method inside it as follows:
ActionResult QuickSelect(string id){ /*do some things, access the 'id' parameter*/ }
I noticed that requests to "/catalog/quick-select/1234" worked perfectly, but requests to /catalog/quick-select?id=1234 were 500'ing because once the action method was called as a result of controller.Execute(), the id parameter was null inside of the action method.
I do not know exactly why this is, but the behavior was as if MVC was not looking at the query string for values during model binding. So something about the ProcessRequest implementation in the accepted answer was screwing up the normal model binding process, or at least the query string value provider.
This is a deal breaker, so I took a look at default MVC IHttpHandler (yay open source!): http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/MvcHandler.cs
I will not pretend that I grok'ed it in its entirety, but clearly, it's doing ALOT more in its implementation of ProcessRequest than what is going on in the accepted answer.
So, if all we really need to do is strip dashes from our incoming route data so that MVC can find our controllers/actions, why do we need to implement a whole stinking IHttpHandler? We don't! Simply rip out the dashes in the GetHttpHandler method of DashedRouteHandler and pass the requestContext along to the out of the box MvcHandler so it can do its 252 lines of magic, and your route handler doesn't have to return a second rate IHttpHandler.
tl:dr; - Here's what I did:
public class DashedRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["action"] = requestContext.RouteData.GetRequiredString("action").Replace("-", "");
requestContext.RouteData.Values["controller"] = requestContext.RouteData.GetRequiredString("controller").Replace("-", "");
return new MvcHandler(requestContext);
}
}

HTML5 Offline GWT APP

I am trying to build a offline gwt app using HTML5 cache manifest and
local storage, but to do that, i need to build the manifest file
listing all the GWT generated files, right?
Can i do this during the compile process or is it better to do this in
a shell script?
This should be done using a Linker, so that your resources are automatically added to the manifest at compile time. I know there exists an HTML5 cache manifest linker, since the GWT team has mentioned it a few times, but I don't know where the source is.
The closest alternative (and probably a good starting point for writing an HTML5 linker) is the Gears offline linker. Gears' offline manifests are pretty similar to HTML5's, so it's probably a matter of changing a few lines to make it work.
There's also an informative video about using GWT linkers to have your app take advantage of HTML5 Web Workers.
I just had to do this other day at work. Like the previous answer says, you just need to add a linker. Here's an example of one that creates a manifest file for the Safari user agent based on a template file.
// Specify the LinkerOrder as Post... this does not replace the regular GWT linker and runs after it.
#LinkerOrder(LinkerOrder.Order.POST)
public class GwtAppCacheLinker extends AbstractLinker {
public String getDescription() {
return "to create an HTML5 application cache manifest JSP template.";
}
public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException {
ArtifactSet newArtifacts = new ArtifactSet(artifacts);
// search through each of the compilation results to find the one for Safari. Then
// generate application cache for that file
for (CompilationResult compilationResult : artifacts.find(CompilationResult.class)) {
// Only emit the safari version
for (SelectionProperty property : context.getProperties()) {
if (property.getName().equals("user.agent")) {
String value = property.tryGetValue();
// we only care about the Safari user agent in this case
if (value != null && value.equals("safari")) {
newArtifacts.add(createCache(logger, context, compilationResult));
break;
}
}
}
}
return newArtifacts;
}
private SyntheticArtifact createCache(TreeLogger logger, LinkerContext context, CompilationResult result)
throws UnableToCompleteException {
try {
logger.log(TreeLogger.Type.INFO, "Using the Safari user agent for the manifest file.");
// load a template JSP file into a string. This contains all of the files that we want in our cache
// manifest and a placeholder for the GWT javascript file, which will replace with the actual file next
String manifest = IOUtils.toString(getClass().getResourceAsStream("cache.template.manifest"));
// replace the placeholder with the real file name
manifest = manifest.replace("$SAFARI_HTML_FILE_CHECKSUM$", result.getStrongName());
// return the Artifact named as the file we want to call it
return emitString(logger, manifest, "cache.manifest.");
} catch (IOException e) {
logger.log(TreeLogger.ERROR, "Couldn't read cache manifest template.", e);
throw new UnableToCompleteException();
}
}
}
Use the gwt2go library's GWT Application Manifest generator to do precisely that. That was easy. :)