Should I secure div with inputs against CSRF - asp.net

I'd like to clear out am not a security expert neither i am an ethical or black hat hacker or what so ever related to the security field what i know is that when creating webpages with forms a measurement is taken to protect forms from Cross Site Request Forgery "CSRF" but in some scenarios a div element containing input elements and button or clickable divs can be used to do the exact job.
usually when coding the form it will be protected against CSRF in ASP.NET using
#Html.Antiforgerytoken()
Inside the form declaration in razor page
The question is : is it useful or will it work to perform same procedure with a given div that contains inputs and button that will perform an AJAX call or not ?

Yes, the client side solution does not matter at all. CSRF is a server-side vulnerability, any call to a server that changes server state (data, basically, but also things like login, privilege level changes, etc.) is vulnerable to CSRF if not protected.
In AJAX requests, you have to send the token yourself. Using jQuery, you can use $.ajaxSetup() and the beforeSend hook to capture any state-chaning request and add the token automatically (this applies to POSTs in general, but it can be PUT, DELETE, even GET if the application uses GETs to change stuff). The benefit of using beforeSend is that you only have to do it once and don't need to remember it anymore. The token in this case can be generate in the page with #Html.AntiforgeryToken() as usually, javascript can take it from there.
A slightly special case is when you send json data (the content-type for the request is application/json and it's not www-url-encoded). The standard attribute [ValidateAntiForgeryToken] cannot take the token from json (and it also cannot take it from a request header, should you decide that's the best option to pass it). In this case, you can implement a custom validation attribute, but that's easy, you only have to implement where to get the token from, for the actual validation you can still use the standard AntiForgery.Validate() method.

Related

JSF page forward - slow CSS [duplicate]

I am currently learning JSF and was rather amazed and puzzled when I realized that whenever we use <h:form>, the standard behavior of JSF is to always show me the URL of the previous page in the browser, as opposed to the URL of the current page.
I understand that this has to do with the way JSF always posts a form to the same page and then just renders whatever page the controller gives it back to the browser which doesn't know the page location has changed.
It seems like JSF has been around for long enough that there must be a clean, solid way to deal with this. If so, would you mind sharing?
I have found various workarounds, but sadly nothing that seems like a real solid solution.
Simply accept that the URL is misleading.
Append "?faces-redirect=true" to the return value of every bean's action and then
figure out how to replace #RequestScoped with something else (Flash Scopes, CDI conversation, #SessionScoped, ...).
accept to have two HTTP round trips for every user action.
Use some method (e.g. 3rd party library or custom code) to hide the page name in the URL, always using the same generic URL for every page.
If "?faces-redirect=true" is as good as it gets, is there a way do configure an entire application to treat all requests this way?
Indeed, JSF as being a form based application targeted MVC framework submits the POST form to the very same URL as where the page with the <h:form> is been requested form. You can confirm it by looking at the <form action> URL of the generated HTML output. This is in web development terms characterized as postback. A navigation on a postback does by default not cause a new request to the new URL, but instead loads the target page as content of the response. This is indeed confusing when you merely want page-to-page navigation.
Generally, the right approach as to navigation/redirection depends on the business requirements and the idempotence (read: "bookmarkability") of the request (note: for concrete code examples, see the "See also" links below).
If the request is idempotent, just use a GET form/link instead of POST form (i.e. use <a>, <form>, <h:link> or <h:button> instead of <h:form> and <h:commandXxx>).
For example, page-to-page navigation, Google-like search form, etc.
If the request is non-idempotent, just show results conditionally in the same view (i.e. return null or void from action method and make use of e.g. <h:message(s)> and/or rendered).
For example, in-page data entry/edit, multi-step wizard, modal dialog, confirmation form, etc.
If the request is non-idempotent, but the target page is idempotent, just send a redirect after POST (i.e. return outcome with ?faces-redirect=true from action method, or manually invoke ExternalContext#redirect(), or put <redirect/> in legacy XML navigation case).
For example, showing list of all data after successful editing, redirect after login, etc.
Note that pure page-to-page navigation is usually idempotent and this is where many JSF starters fail by abusing command links/buttons for that and then complain afterwards that URLs don't change. Also note that navigation cases are very rarely used in real world applications which are developed with respect to SEO/UX and this is where many JSF tutorials fail by letting the readers believe otherwise.
Also note that using POST is absolutely not "more secure" than GET because the request parameters aren't immediately visible in URL. They are still visible in HTTP request body and still manipulatable. So there's absolutely no reason to prefer POST for idempotent requests for the sake of "security". The real security is in using HTTPS instead of HTTP and checking in business service methods if currently logged-in user is allowed to query entity X, or to manipulate entity X, etc. A decent security framework offers annotations for this.
See also:
What is the difference between redirect and navigation/forward and when to use what?
JSF implicit vs. explicit navigation
What URL to use to link / navigate to other JSF pages
Bookmarkability via View Parameters feature
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
When should I use h:outputLink instead of h:commandLink?
Creating master-detail pages for entities, how to link them and which bean scope to choose
Retaining GET request query string parameters on JSF form submit
Pass an object between #ViewScoped beans without using GET params

handling DELETE in REST

I have the resource uri as /avl/leagues/leagueName. Idea is to delete the league with the provided name in a restfull way. I tried the below but the browsers are always sending a GET instead of the DELETE. Any ideas why? I am using Tomcat on server side.
<form action="/avl/leagues/Cccccc" method="DELETE">
<input type="submit" value="Cancel league">
</form>
HTML forms only officially support GET and POST for submitting.
Typically, people work around that limitation by either sending the request via Ajax, or including a hidden field in the form to tell the server-side code to treat this request as if it were a DELETE rather than a GET. (Of course, the server-side code has to know to look for that field and act accordingly.)
Browsers are not very good restful clients. They basically use POST and GET for forms, and that's all.
The Spring MVC form tag library allows specifying DELETE as the method, IIRC, and will in fact add a hidden field to the form telling the server that, although the method is not really a DELETE (because the browser is not able to send such requests), it should be treated by the server as a DELETE (thanks to a filter). See Using PUT and DELETE methods in Spring MVC for a similar question and its answer.

Proper way to process forms

What is proper way to process forms in http?
on /somepage:
<form method="POST" action="/someaction.html">
<input type="text" name="name">
<input type="submit">
</form>
Let's assume, that user didn't filled in "name". So I should produce some error. How should I do it:
First method
POST /someaction and 302 Redirect to /posterror?error=1
GET /posterror?error=1 and 200 Ok with content about errors and form
Second
POST /someaction and 200 Ok with content about errors and form
Third
POST /someaction, remember in session form errors and 302 Redirect to /posterror
GET /posterror and 200 Ok with content about errors and form
Which one is proper way? Maybe some fourth one?
The correct approach is called post/redirect/get and is described by wikipedia as:
Post/Redirect/Get (PRG) is a common design pattern for web developers
to help avoid certain duplicate form submissions and allow user agents
to behave more intuitively with bookmarks and the refresh button.
The third one. It allows the user to safely hit refresh or bookmark the page. The first one, although similar, would require you to pass the content of form back and forth over the wire, which is inefficient. As slight refinements, you might consider:
Redirect back to the form, not to a separate error page, to give the user a chance to correct their error
Rather than just storing the error data in the session, store it with some unique id, and then include that in the redirect url. That way the user can can have the page open in two browser windows and they won't tread one each other's toes.
Expire the stored error after a set length of time, or when the form is finally correctly submitted.
I would suggest having some sort of validation before the for is sent using javascript.
Then of course you should validate the form input on the server side as well. As for whether to use redirects, I don't know of any de facto standard there.
If you want to follow use the HTTP protocol as it was meant you should probably send a 4xx status code back (e.g. 400 bad request) with an informative message saying what was wrong in the input.
Is utilizing client-side validation out of the equation? Using javascript you can avoid posting the form (and reduce server-side processing) and let the client (user's end: browser) perform the validation. What other validations do you have in mind?
Here's a link to basic validation that you can apply using javascript:
http://www.w3schools.com/js/js_form_validation.asp

jQuery validation for ASP.NET, security issues

I would like to replace asp.net form validation with jQuery validation but not sure is this secure. ASP.NET validation use client side and server side validation to prevent hack post to server by disabling client side JS validation.
If I will use client side jQuery validation then it can be easily compromised, no? Maybe I am missing something?
You should not use ONLY client side validation. It can be easily avoided. People generally use client side validation for the User Experience. That way forms don't have to do a full post to catch mistakes. You want to do server side validation for security purposes.
jQuery validation is exactly the same as client side JS validation. jQuery is javascript framework.
ALWAYS use server side validation, and if you want to improve the user's experience then include your client side validation.
you should always write server-side validation code even if you validate the data on the client, otherwise your site will be unsafe and easily could be hacked. But the reason for writing client-side validation is to avoid the round-trip to the server that would otherwise be required to validate the data. In other words, if the user enters invalid data, it's much more efficient and user-friendly to trap the error before
sending the data to the server, where if the data is invalid you'll have to rebuild the page and maintain the page state as well so that the user can fix the invalid value.
Try using asp.net AJAX plus server control validators as your validation framework for the following reasons:
It's secure because your validation runs in the server side
It's easier to implement because you dont have to write the same code twice, both in the server and in the client (javascript)
Server side code it's by far much easier to maintain than client side code
Your website will look responsive, although you must take care on how to reduce the data traveling in every partial postback. Research on this.
You are tied to the asp.net sintax and your developers will love this too. You won't actually need more.
Recommendations:
focus is lost on every partial postback: the DOM portion of the form submitted inside the update panel is replaced, and the browser does nothing to set the focus for the user. So make sure to set the focus on the proper controls thinking the user is entering data using the TAB keystroke.
if you want to customize the appeareance of your server validator controls with css, try inheriting the main validators: Custom, Regex and requiredField, with your own classes, which basically set and unset the error css class and message you want every server roundtrip (set before rendering). then map those custom classes to the framework's classes in the web.config (use tagmapping), so you alway use the default markup for server side validations. You get this way the best of the two worlds.
Jquery.validate.js
https://github.com/jzaefferer/jquery-validation
You can set this up to run independently of your own client side validation/instead of/or in conjunction with.

Prevent Javascript in URL attacks (asp.net)

I've seen plenty of Cross-Site Scripting attack prevention suggestions, but I'm not asking about Form Input validation. How would I prevent something like this:
javascript:(function(i,j){with(document){for(i=0;i<forms.length;++i){with(forms[i]){for(j=0;j<elements.length;++j){elements[j].disabled=false}}}}})()
from being inserted into the URL? This code would enable all form elements on a page if added to a URL. So if you disabled certain buttons based due to permissions or something then all those buttons would become enabled.
Should I just be parsing the URL and check for the Javascript keyword?
No. You can't, anyway, as it doesn't get sent to the server.
That is just JavaScript executed locally by the user themselves. It should mean nothing to you. The security of your system should never rely on client-side javascript, all your authentication, and so on, should be done server-side.
The key is to not worry much about it client-side. Server-side is where you have to be bullet-proof. Do not assume, for example, that just because you named your form inputs the same as your database column names, that you can just loop through Request.Form and persist all the data you get. You should validate that you only process the inputs you are expecting, and validate them for data type and range, as well as considering the user's permissions to alter a given field.
That way, the user can send whatever they want, you will only process and accept valid data server-side.

Resources