Post processing Wicket response (Rhino, jQuery) - javascript

My question is if there is a way to simply post process wicket HTML response?
What I want to do is to apply some DOM transformations to the generated HTML using Rhino (http://www.mozilla.org/rhino/) and jQuery.
Anyone ever thought about it? Any suggestions where to start?
Best,
Maciej Wrzalik
OK, I've got this:
public class MyRequestCycle extends WebRequestCycle {
public MyRequestCycle(WebApplication application, WebRequest request, WebResponse response) {
super(application, request, response);
}
#Override
protected void onEndRequest() {
String responseString = response.toString();
//String newResponseString = process(responseString);
//replace old response content with the newResponseString
super.onEndRequest();
}
}
In method onEndRequest the string responseString contains HTML code that I'm going to alter some way using Rhino, Envjs and jQuery but the question is how can I replace the old response content with the new one?

Envjs emulates the browser environment under Rhino, and specifically allows you to do DOM manipulation server-side using jQuery. I have used it before in my projects, and have had good success. Relevant resources:
http://www.envjs.com/
http://ejohn.org/blog/bringing-the-browser-to-the-server/

If you want the post-processing done on the server, your best bet is likely to implement a Servlet Filter which modifies the response before it goes to the client.
As you're working on the rendered HTML, this has nothing particular to do with Wicket, and could be applied to html generated by any Java framework.

As suggested, a normal Java EE filter would work fine, if there's nothing Wicket-specific that you need for the processing.
But if you want to do it inside Wicket, for some reason or other, I suppose you could create your own RequestCycle implementation (MyRequestCycle extends WebRequestCycle) and do the processing there (perhaps by overriding onEndRequest and/or getWebResponse).
To use a custom RequestCycle, override newRequestCycle in your Application class:
#Override
public RequestCycle newRequestCycle(Request request, Response response) {
return new MyRequestCycle(this, (WebRequest) request, response);
}
I'm using custom a RequestCycle for a couple of things (e.g. this) myself—it's simple and straightforward—but I'm not 100% sure if it fits your needs here. (My Wicket experience is still somewhat limited.)

Related

How to prevent XSS in java web application? [duplicate]

How can I prevent XSS attacks in a JSP/Servlet web application?
XSS can be prevented in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.
For example:
<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>
This will escape characters which may malform the rendered HTML such as <, >, ", ' and & into HTML/XML entities such as <, >, ", &apos; and &.
Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes &amp; instead of & and ultimately the enduser would see & being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.
If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also Markdown or HTML.
The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement instead of Statement. In JPA terms, use Query.
An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.
The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.
On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.
I had great luck with OWASP Anti-Samy and an AspectJ advisor on all my Spring Controllers that blocks XSS from getting in.
public class UserInputSanitizer {
private static Policy policy;
private static AntiSamy antiSamy;
private static AntiSamy getAntiSamy() throws PolicyException {
if (antiSamy == null) {
policy = getPolicy("evocatus-default");
antiSamy = new AntiSamy();
}
return antiSamy;
}
public static String sanitize(String input) {
CleanResults cr;
try {
cr = getAntiSamy().scan(input, policy);
} catch (Exception e) {
throw new RuntimeException(e);
}
return cr.getCleanHTML();
}
private static Policy getPolicy(String name) throws PolicyException {
Policy policy =
Policy.getInstance(Policy.class.getResourceAsStream("/META-INF/antisamy/" + name + ".xml"));
return policy;
}
}
You can get the AspectJ advisor from the this stackoverflow post
I think this is a better approach then c:out particular if you do a lot of javascript.
Managing XSS requires multiple validations, data from the client side.
Input Validations (form validation) on the Server side. There are multiple ways of going about it. You can try JSR 303 bean validation(hibernate validator), or ESAPI Input Validation framework. Though I've not tried it myself (yet), there is an annotation that checks for safe html (#SafeHtml). You could in fact use Hibernate validator with Spring MVC for bean validations -> Ref
Escaping URL requests - For all your HTTP requests, use some sort of XSS filter. I've used the following for our web app and it takes care of cleaning up the HTTP URL request - http://www.servletsuite.com/servlets/xssflt.htm
Escaping data/html returned to the client (look above at #BalusC explanation).
I would suggest regularly testing for vulnerabilities using an automated tool, and fixing whatever it finds. It's a lot easier to suggest a library to help with a specific vulnerability then for all XSS attacks in general.
Skipfish is an open source tool from Google that I've been investigating: it finds quite a lot of stuff, and seems worth using.
There is no easy, out of the box solution against XSS. The OWASP ESAPI API has some support for the escaping that is very usefull, and they have tag libraries.
My approach was to basically to extend the stuts 2 tags in following ways.
Modify s:property tag so it can take extra attributes stating what sort of escaping is required (escapeHtmlAttribute="true" etc.). This involves creating a new Property and PropertyTag classes. The Property class uses OWASP ESAPI api for the escaping.
Change freemarker templates to use the new version of s:property and set the escaping.
If you didn't want to modify the classes in step 1, another approach would be to import the ESAPI tags into the freemarker templates and escape as needed. Then if you need to use a s:property tag in your JSP, wrap it with and ESAPI tag.
I have written a more detailed explanation here.
http://www.nutshellsoftware.org/software/securing-struts-2-using-esapi-part-1-securing-outputs/
I agree escaping inputs is not ideal.
My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.
If you want to automatically escape all JSP variables without having to explicitly wrap each variable, you can use an EL resolver as detailed here with full source and an example (JSP 2.0 or newer), and discussed in more detail here:
For example, by using the above mentioned EL resolver, your JSP code will remain like so, but each variable will be automatically escaped by the resolver
...
<c:forEach items="${orders}" var="item">
<p>${item.name}</p>
<p>${item.price}</p>
<p>${item.description}</p>
</c:forEach>
...
If you want to force escaping by default in Spring, you could consider this as well, but it doesn't escape EL expressions, just tag output, I think:
http://forum.springsource.org/showthread.php?61418-Spring-cross-site-scripting&p=205646#post205646
Note: Another approach to EL escaping that uses XSL transformations to preprocess JSP files can be found here:
http://therning.org/niklas/2007/09/preprocessing-jsp-files-to-automatically-escape-el-expressions/
If you want to make sure that your $ operator does not suffer from XSS hack you can implement ServletContextListener and do some checks there.
The complete solution at: http://pukkaone.github.io/2011/01/03/jsp-cross-site-scripting-elresolver.html
#WebListener
public class EscapeXmlELResolverListener implements ServletContextListener {
private static final Logger LOG = LoggerFactory.getLogger(EscapeXmlELResolverListener.class);
#Override
public void contextInitialized(ServletContextEvent event) {
LOG.info("EscapeXmlELResolverListener initialized ...");
JspFactory.getDefaultFactory()
.getJspApplicationContext(event.getServletContext())
.addELResolver(new EscapeXmlELResolver());
}
#Override
public void contextDestroyed(ServletContextEvent event) {
LOG.info("EscapeXmlELResolverListener destroyed");
}
/**
* {#link ELResolver} which escapes XML in String values.
*/
public class EscapeXmlELResolver extends ELResolver {
private ThreadLocal<Boolean> excludeMe = new ThreadLocal<Boolean>() {
#Override
protected Boolean initialValue() {
return Boolean.FALSE;
}
};
#Override
public Object getValue(ELContext context, Object base, Object property) {
try {
if (excludeMe.get()) {
return null;
}
// This resolver is in the original resolver chain. To prevent
// infinite recursion, set a flag to prevent this resolver from
// invoking the original resolver chain again when its turn in the
// chain comes around.
excludeMe.set(Boolean.TRUE);
Object value = context.getELResolver().getValue(
context, base, property);
if (value instanceof String) {
value = StringEscapeUtils.escapeHtml4((String) value);
}
return value;
} finally {
excludeMe.remove();
}
}
#Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return null;
}
#Override
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base){
return null;
}
#Override
public Class<?> getType(ELContext context, Object base, Object property) {
return null;
}
#Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return true;
}
#Override
public void setValue(ELContext context, Object base, Object property, Object value){
throw new UnsupportedOperationException();
}
}
}
Again: This only guards the $. Please also see other answers.
<%# page import="org.apache.commons.lang.StringEscapeUtils" %>
String str=request.getParameter("urlParam");
String safeOuput = StringEscapeUtils.escapeXml(str);

URL Routes with Java Servlets

I wanted to know if there is a way to do similar code in java servlet like I do in express.js
In express I can say for example:
app.get('/:name',function(bla bla)){}
the :/name its a parameter in which the url of the get can be
localhost/kevin
localhost/joe
or whatever... This is great because I can take then for example that name (request.params.name) and so something with it. And it is also great because there is no limit(As far as I know) as to how many routes I can create, it just serves as a placeholder.
Is there a way I can do this using Java servlets?? I want to be able to have an html page that when I click a button it goes to localhost/button1 If I click another button it goes to localhost/button2.. and so on.. But also I'm letting the user create buttons dynamically so I don't want to create jsp pages beforehand, I just want the servletto create one..?
Thanks
Almost. With help of a prefix mapping /foo/* and HttpServletRequest#getPathInfo().
#WebServlet("/name/*")
public class NameServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getPathInfo().substring(1);
// ...
}
}
Invoke it as
http://localhost:8080/context/name/kevin
http://localhost:8080/context/name/joe
...
You can optionally map the servlet on /*, but then it will act like a global front controller which isn't necessarily a good idea as you'd have to take static resources like CSS/JS/images and such into account.
In case you actually intend to create a REST service, rather look at JAX-RS instead of "plain vanilla" servlets. It would further reduce boilerplate code. See also a.o. Servlet vs RESTful.

value from javascript is not returning to c# in the application in Visual Web GUI

I have written a java script function in the skin file of the visual web Gui application which returns some value too. Now i am invoking the java script method from code behind.
public void XYZ( string message)
{
this.InvokeMethodWithId("testCall", message);
}
And javascript function is:--
function testCall(strGuid, txt) {
alert("hai Java script fired..");
return txt+ 'returned from JavaScript';
}
I want the value returned from JavaScript in the application. how can i achieve it. Is there in other method to invoke the methods of JavaScript?
I want something like this:--
public void Conect( string message)
{
string returnedvalue = this.InvokeMethodWithId("testCall", message);
}
Javascript is executed on the client so the return won't make it to the server.
A solution could be to use AJAX to send that value to the server. Stack Overflow is full of answers about AJAX.
Here's a good example.
#Amish Kumar,
As noted by other replies already, the client-side and server-side are not directly connected in web programming. The client is always the initiator of every request, and the server-side's "purpose" is to render a response, which will then be returned to the client for processing, in Visual WebGui this is usually some UI update processing. This basically means that your client script will not execute until the server-side has finished rendering the response, and the only way the client can get some message back to the server is to issue another request.
Think about how you need to use the MessageBox in Visual WebGui for instance. In order to receive the "response" from the MessageBox, you need to supply a callback handler in your server-side code, and then your server-side code will have completed creating the response, which is returned to the client. The client updates its UI and on some action to the MessageBox dialog, it sends a new request to the server, which interpretes the action and invokes your callback handler. In the callback handler you use Form.DialogResult to get the user action.
A very basic way to make this work in custom Visual WebGui code could be like the following code on a Form:
private void button1_Click(object sender, EventArgs e)
{
SendClientMessage("This is a test");
}
public void SendClientMessage(string strMessage)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("var objEvent = mobjApp.Events_CreateEvent('{0}', 'MessageEvent');");
sb.AppendLine("mobjApp.Events_SetEventAttribute(objEvent, 'Msg', '{1}');");
sb.AppendLine("mobjApp.Events_RaiseEvents();");
this.InvokeScript(string.Format(sb.ToString(), this.ID, strMessage));
}
protected override void FireEvent(Gizmox.WebGUI.Common.Interfaces.IEvent objEvent)
{
if (objEvent.Type == "MessageEvent")
MessageBox.Show(objEvent["Msg"]);
else
base.FireEvent(objEvent);
}
This code will not work unless you set your Visual WebGui applicaton for no Obscuring. In order for this code to work on an obscured application, you would need to add the JavaScript as an obscured JavaScript resource and it would work fine.
Palli
enter code here

SignalR: Internal Server Error when calling hub method

I've been playing around with SignalR for a few days and I have to say that it's an absolutely phenomenal library. I've managed to get a few things working with it and was astounded at the simplicity, but I recently ran into a small problem.
I'm unable to call a Hub method from JavaScript in the browser. The request returns a 500 error code, and when I look at the error page source, I see this:
[ArgumentNullException: Value cannot be null.
Parameter name: s]
System.IO.StringReader..ctor(String s) +10207225
Newtonsoft.Json.Linq.JObject.Parse(String json) +74
SignalR.Hubs.HubRequestParser.Parse(String data) +78
SignalR.Hubs.HubDispatcher.OnReceivedAsync(IRequest request, String connectionId, String data) +266
SignalR.<>c__DisplayClass6.<ProcessRequestAsync>b__4(String data) +84
SignalR.Transports.ForeverTransport.ProcessSendRequest() +159
SignalR.Transports.ForeverTransport.ProcessRequestCore(ITransportConnection connection) +149
SignalR.Transports.ForeverTransport.ProcessRequest(ITransportConnection connection) +42
SignalR.PersistentConnection.ProcessRequestAsync(HostContext context) +1087
SignalR.Hubs.HubDispatcher.ProcessRequestAsync(HostContext context) +251
SignalR.Hosting.AspNet.AspNetHandler.ProcessRequestAsync(HttpContextBase context) +656
SignalR.Hosting.AspNet.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessReques t(HttpContext context, AsyncCallback cb, Object extraData) +143
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9479007
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +178
My server-side code is:
public class SourceHub : Hub
{
public void RegisterSource(string source)
{
Groups.Add(Context.ConnectionId, source);
}
}
and on the client-side I have:
var SourceHub = $.connection.sourceHub;
$.connection.hub.start().done(function () {
SourceHub.registerSource("test");
});
I've been digging for a while, but I just can't find the source of the problem... could someone please help me out?
Preface: I'm on edobry's team for this project, and I'm the backend guy, so this foray into frontend was new and fascinating to me.
So, after some careful dissection of the code as I stepped through the project, it turns out that the POST data in the request variable was coming up empty. The data was getting sent properly up to the $.ajax call, but never arriving at the server. Some more hunting and I had uncovered something suspicious that edobry and I were then able to discern what was happening.
We're using Ajax for other parts of the page, and the ajax method is called several times, so we had factored out some settings we set on every method call into $.ajaxSetup. One of these was dataType getting set to "text", and contentType to "application/json". It seems that signalR is not overriding global ajax settings properly. I'm not sure if this is a bug or intended behavior, but it should be documented better if that's the case (and if it is, feel free to call us dumb. :))
Your method is called RegisterSource and you call registerSources instead of registerSource in javascript.

Wicket: How to show Javascript dialog when Form.MultiPart(true)

When I try to upload file in Wicket I've got the following exception:
"ERROR org.apache.wicket.RequestCycle.logRuntimeException(RequestCycle.java:1529) - ServletRequest does not contain multipart content. One possible solution is to explicitly call Form.setMultipart(true), Wicket tries its best to auto-detect multipart forms but there are certain situation where it cannot.
java.lang.IllegalStateException: ServletRequest does not contain multipart content. One possible solution is to explicitly call Form.setMultipart(true), Wicket tries its best to auto-detect multipart forms but there are certain situation where it cannot.
at org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest.<init>(MultipartServletWebRequest.java:113)..."
However, when I set form.MultiPart(true) I can't get Javascript dialog by using:
target.appendJavascript("Some Message");
Does somebody know how to use Javascript when Form.Multipart(true)?
Thanks!
If you want to call the alert dialog as a response for an ajax request, you can use the appendJavascript() method (the argument is javascript code, not a simple string, like the code you posted):
target.appendJavaScript("alert('Some message');");
If you want to call the alert when the page loads, you could use a behavior:
add(new AbstractBehavior() { // or Behavior, on Wicket 1.5
#Override
public void renderHead(Component component, IHeaderResponse response) {
response.renderOnLoadJavaScript("alert('Some message');");
}
});
It's also possible use a Label, and render directly to a <script> tag. Just remember to call setEscapeModelStrings(false):
add(new Label("alert", "alert('Some message');").setEscapeModelStrings(false));
and
<script type="text/javascript" wicket:id="alert"></script>

Categories