Prevent Form spam with the session - java

I've already read most of the questions regarding techniques to prevent form spam, but none of them seem to suggest the use of the browser's session.
We have a form that sends an email to given email address and we didn't like the idea of using "captchas" or Javascript, as we wanted to keep the user journey simple and accessible to those without Javascript.
We would like to use the session object to help prevent form spam. Our webapp is developed on Weblogic Server 10 using Struts.
The solution being, when the form loads, it would set a variable in the session object. Once you click submit, we check if the session for the variable. No variable, redirect to the form. Variable exists send the email.
I would really appreciate any opinions/reasons why this might be a bad idea, so we can evaluate this solution against others.
Many thanks,
Jonathan

There is nothing to prevent a spammer from automating the process of downloading your form (thus generating the cookie) and submitting it. It may impose a slight burden on the spammer, but a trivial one.
As an example, a form can be easily downloaded and submitted, with cookies preserved, using a command-line tool such as cURL. This can then be run from a script repeatedly.

Session objects can, depending on implementation, be relatively heavy in terms of resource usage, as well as somewhat slow. Additionally, the spammer, if they realize how you are blocking them, can simply start a new session every time they hit the form by not sending back the session cookie.
So, because that technique relies on the client to behave nicely, and the expected behavior is fairly easy to prevent, it is possibly less useful than some other ways to solve the problem.

Thank you for your reply cdeszaq, but I'm not sure if you mis-understood my question.
For the form submission to complete successfully, clients will be forced to load the form to set up the session object correctly. Only when the session is in the correct state, will it be possible to send an email.
If the spammer is not sending back the session cookie, then they will not be able to spam my form as they haven't gone to my form page that creates the right session.
I agree that using the session object would create extra resource. Our implementation would simply, (using JSP) call session.setAttribute("formLoaded", true); and in my Struts action I would simply use session.getAttribute("formLoaded"); to check.

I wonder if this might work:
Each time you render page/form, create a random bit of text
Put that text in the session
Include that text as a hidden field in the form
User submits the form
Action compares the hidden text to the value in the session - if there's a match, send the email
Since a hacker wouldn't be able to put any random value in the session, they wouldn't be able to spam. Right?

Related

Which is the best option for uniquely identifying a client state from Ajax to Servlet request?

I'm making an online multiplayer chess game using java servlet in the back-end. In
the front-end I'm using JavaScript, Ajax, Html. Client\Player request is sent through ajax request to the servlet controller. Now, I want to know which is the best option for handling a client request\state. I don't want to use cookies. I know URL rewriting is an option for managing client session. Apart from these, what are the other efficient approach for managing client sessions? Is HttpSession Object is a good option for uniquely identifying client sessions?
HttpSession in turn uses cookie to identify session (JSESSIONID) , it will be automatically setup when session is created
If you really don't want to use cookies , then go for Token Based Authentication , there are lot of tutorials available online, but it need a little more work for token management. This is been used widely now
Update
quick search on token based authentication on google gives this,
https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
http://arjan-tijms.omnifaces.org/2014/11/header-based-stateless-token.html
http://www.javabydefault.com/2014/11/implementing-token-based-authentication.html
yes using sessionId will be good option for you you can get the seesionis by using the following code session.getId()
If you are not concerned about security, you need not worry about 'authentication' mechanisms.
For example, if you just want to differentiate between two clients, you can simply add an extra parameter like clientId in each of your requests.
It can work like this:
Create one global variable in javascript like globalClientId =
null;
At the time of each request, send this as an extra parameter
If globalClientId is null, generate a 16-digit random number and
store it (this will be done only on first time per page)
However, some disadvantages of this method compared to Cookies are:
It works only for one tab
It will be lost if that tab is closed

How to protect registration page from multiple malicious requests?

I allow users to register on my website using a registration form.
Once form is submitted a token will be generated and will be sent by email to user, they need to click on the token link to activate their account.
My question is that if I do it, do the malicious codes can still send multiple emails to my website to register, should I use Captcha to protect the website or there is any other method ?
If all you want is to prevent double submissions, you can generate a unique token for the form that you check on submission. This requires some thought if there are multiple forms per page. Also, a simple method is to just disable the form/button on submission. This is even more effective if the form is submitted via Ajax (so that the action parameter of the form can be absent and thus not easily harvestable).
If you want to prevent automatic submissions (by bots), while Captcha is probably the strongest of the common methods, it is also very user-hostile. Instead, unless you have a reason to believe your site is being specifically targeted, it is usually enough to just use honey-pot fields (invisible fields that a human would never fill but a bot would) and hidden fields that you fill with a known value after a short delay using JS (a bot wouldn't normally execute JS nor take time to type into fields like a human). Simply doing an Ajax submission is also usually enough. I recommend using one or a mixture of these methods before falling back to Captcha.
Captcha is one of the standard methods.
Another way is do not do a direct submit of the form.Use AJAXfied server calls sos that form does not get posted by itself but has some data scrambling of inner fields & delays the submissions.
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
name_value = $form.find( 'input[name="name"]' ).val(),
email_value = $form.find( 'input[name="email"]' ).val(),
phone_value = $form.find( 'input[name="phone"]' ).val(),
message_value = $form.find( 'textarea[name="message"]' ).val();
/* Send the data using post */
var posting = $.post( "contact-form-handler.php", {
name: name_value,
email: email_value,
phone: phone_value,
message: message_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});</script>
I'm no expert in this matter, but the solution seems rather obvious to me:
Everyone uses CAPTCHA. There's simply no other way to protect your server from automated attack. It won't save you from DDoS, but will handle pretty much everything else because CAPTCHA is, well, CAPTCHA.
You do have multiple CAPTCHA solutions available though, so choose one that suits you best.
As Velis mentioned, easiest way is to use Captcha.
Other solutions exist but can be easily beaten if bots are targeted for your website, for example, having an hidden field like "re-enter email" which will be filled by bots, but can be caught on the server side and registration can be rejected.
Certain, complicated methods also exist, like recording mouse clicks or time taken to fill the form, but these require significant JS work and can be overkill until your website becomes a bot target.
Captcha is one plausible solution, but most humans don't like it.
How about instead if you add some intelligence to your system?
Implement a cooldown between emails. Before sending an email, wait one minute. If another email request comes then wait another minute and don't send the first one. (This could be another form of attack but only if this is the only line of defense).
Would a person try to register 30 times in the last minute? No.
Would a person re-register if the last register was successful? No.
You can also combine these with the IP of the registering user: Would a user try to create 10 new account for other users from the same IP in 10 minutes? Unlikely.
If this is a corporate website and you MUST prevent the email spamming, then consider secondary ways of communication. For example, if you have the means, you can request the user to SMS the email address to a specific number, which would create a reset password request.
You could also, upon the user completing the registration, generate a list of numbers that should be used to retrieve the account. Something like: "If your account is lost, it can be retrieved by entering one of these numbers into the RETRIEVE field" And then provide a list of numbers that would be confidential to your company and the customer. The same way Google does it.
Although these mechanisms can become complex, they will be smarter than any captcha; will be easier to adapt, and more comprehensive. On the plus side your users will thank you for not having to read twisted images of numbers and letters.

Is a Servlet "secure" if it checks for a given session attribute in the request handler?

Assume I have a single servlet in a web app, and all users need to be logged in before they can do anything. So in the get and post methods there is an if block to test if the user is logged by trying to extract a session attribute in to process request, and else to redirect to login page if not logged in.
Given this scenario, is there a way an intruder can manipulate the system to gain entry without knowing the password? Assume the password is hard-coded into the servlet. If yes, where would he start?
I would look at http://docs.oracle.com/javaee/5/tutorial/doc/bncbe.html#bncbj and the section linked from that section about specifying authentication mechanisms.
See also (on Stackoverflow) Looking for a simple, secure session design with servlets and JSP and How do servlets work? Instantiation, sessions, shared variables and multithreading
In short, you don't need to do much yourself about checking for a session attribute if you use the mechanisms described on those pages. Your login form can be used in the 'form-login' configuration requiring authentication.
The key of security is around your comment extract a session attribute -- how are you doing this? Are they sending you a query string param? Are they sending you credentials in the method headers?
To #Hogan's point, unless this is over HTTPS the answer is: "No, it is not secure. A man-in-the-middle (MITM) can get the password from your submission and simply re-use it to mask its own nefarious requests".
If the communication IS done over HTTPS, then you should be fine. Having a single hard-coded password is fine, but consider the case where the password gets compromised; now every single client/user/etc. has to change their code.
A better design is to issue clients a key they can send along with their requests that you can use to identify who they are and if a key gets compromise, re-issue a new one to that user/client/etc.
This assumes traffic is over HTTPS
If traffic is not, a lot of this breaks down and you need to look at things like HMAC's. I wrote this article on designing secure APIs -- it should give you a good introduction to how all this nightmare of security works.
If your eyes are rolling into the back of your head and you are thinking "My god, I just wanted a YES/NO", then my recommendation is:
Require all traffic to be over HTTPS
Issue individual passwords to each client so if one gets compromised, every single one isn't compromised.
That should get you pretty far down the road.
Hope that help. This topic is super hairy and I know you didn't want a history lesson and just want to solve this question and move forward. Hope I gave you enough to do that.

HTTP POST: how to ensure it is called only from a previous page?

This is probably quite a simple, newbie question for seasoned Web developers, which I am not, and googling around does not help.
I have a very simple webapp hosted on Heroku, the code of which is here. It has two JSP pages, one index, one with the validation results, nothing fancy. The two JSP pages are here (index.jsp) and here (results.jsp).
The problem is with the validation servlet: it is a POST, and is triggered, when using the app itself, via an input button in index.jsp. But I have tested that it will also work if I call the servlet directly... And I don't want that.
Is there a way to reliably ensure that this servlet may only be called when coming from the index page (and send a 403 otherwise)?
One way I've used is to have the input form on index.jsp include a hidden field which contains an md5 hash which the results.jsp can also calculate. I use the md5 hash of the client machine's IP address concatenated with a shared secret phrase.
I guess for a given client IP address the hash is always going to be the same so you could also salt it with another value (like current time) which is passed in another hidden field for inclusion in the calculation by results.jsp.
You could generate a fingerprint (for example UUID.randomUUID()) when the first page is loaded and save the value in the current session.
When you post the result to the validation servlet you include that fingerprint as a hidden field and check that the fingerprint exists on the session.
There is no way you can be 100% sure of that. Eventualy you can check the referer but it's possible to forge it. You can also set a cookie when loading the index.jsp and check the value in the servlet. But it's also possible for someone to load index.jsp to retrive the cookie and then use it to post on the validation servlet. Same think with an input hidden with a hash.

how to bookmark a dynamically created aspx page?

There is this site wich in the address bar only shows like "http://example.com/examplepage.aspx".
Normally if it would have parameters behind it you probably could just copy that one.
But since it doesn't, how do i bookmark this page.
It doesn't necessarily have to be a bookmark, but at least an easy way to access the page.
(fyi I know basic HTML and Java, maybe it's only possible programmatically).
thnx
Generally dynamic pages (taking in context with the question) are not book mark friendly.
You could probably sniff the incoming request, and create a fake form which you can then submit later.
However there may be situations where there are parameters such as session id which are valid for only small periods of time.
You should read up on sessions. In really simple terms, a session is assigned to users accessing a website. They have an expiry period. IF you stay idle beyond set time (determined by the developer) you will not be able to get in. And every time you log back in, you may be assign a new session.
You would have noticed, that some websites automatically log you in, this is mostly done with the help of cookies. Cookies work in tandem with sessions, they store very basic information, so the next time you come back to a website, it will be able to identify you as a returning user and provide you with access.
Then again, some pages don't use sessions, they might have their own custom way of identifying users.
Bookmarks can be used in dynamic pages, if the code allows you to send GET requests, if they don't have any other extra parameters which will block you.
To Summarize:
Dynamic page not very bookmark friendly.
There may be parameters used to access a webpage which change constantly, which you cannot really save.
You may be able to get into dynamic pages using bookmarks, if they don't use any of the dynamically changing parameters.
Since you know Java, you should probably read up on JSPs/servlets to get an understanding of what happens behind the scenes in dynamic pages.
Hope this answers your questions.

Categories

Resources