Form validation on the server - java

This example shows how to validate the entered data on the form:
Validating Form Input
And is it correct to do validation on the Server?
I thought the validation should be done by frontend.

Those are not mutually exclusive.
The following things are general lessons and don't just apply to Java but to all programming in general:
The server side is way more important. Never trust user input. Never. The only reason to validate in the form/frontend/client is to make it easier for the user to send you proper input.
Update:
Don't confuse "don't trust user input" with "don't trust anyone". Trusting user input is effectively putting out a wildcard check out there signed in your name.
While including code you found is just trusting exactly the code you included. Or to go with the money metaphor again: a fixed amount. Of course you should in my opinion do at least some backgroundd check. But most shady individuals bank on impulse. So they don't put much work in a clever disguise or even building rputation. So usually you can trust established libs to some degree.
You still always need to verify the data on the server-side. Because the client could be manipulated. And that does not even require the malicious intent of the user. Or even the user's knowledge at all. See the man in the middle attacks for example. A third party might manipulate the data on the way to the server.

Related

resource injection issue at creating new url(resource);

In my project, the resource injection issue is coming at creating a new URL(resource) (fortiy static scan).
how to fix this?
String username = "james";
String resource = "https://someWebsite.com/api"+username;
URL url = new URL(resource); //here it is giving resource injection issue in fortify scan
System.setProperty("https.proxySet", "true");
System.setProperty("https.proxyHost", "11.09.11.111");
System.setProperty("https.proxyPort", "90");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
Immediately I see this line:
String resource = "https://someWebsite.com/api"+username;
I know we're in trouble.
Why? I prompted you with a comment because you need to ask yourself "what am I doing here?"
Your initial reaction will probably be, "I'm concatenating the username to the URI string. This is a REST-based web service, so what's the big deal?"
This is getting flagged because you haven't conducted--in order of importance:
Output escaping on the user-controlled parameter
Input encoding on the user-controlled parameter.
What did avgvstvs do here though? Why is he talking output when this is clearly input?
As a programmer you have a responsibility that they never taught you about in school. When working on an application you have to understand the data flow of your variables you use. You need to separate all inputs into 2 categories:
Stuff WE (the server) controls
Stuff the user (the enemy) controls
You need to think about users whose intent to use your system is evil; this isn't to make you think that all users are the enemy--though some veterans here might argue with that--but that when you're writing secure code, you need to think about how an adversary will abuse your code.
Once you understand that external context, this should start to look more clear for you now.
Any user of your website can hit "f12" and call up tools that allow them to easily bypass any client-side protections that might exist: Any input from any user should be treated as potentially malicious. The main defenses against abuse are what I stated above: escaping for the correct context, and validating input.
Before any value should be used, it should be validated. As currently written, I can impersonate any user registered with that API url. Several input checks make sense here:
Is the user in question authenticated?
Does the user in question actually exist in the system?
Is the user authorized to use the resources indicated at this URI?
Does the user have a valid session?
What byte encoding is being used by my programming platform, and does the input conform to this?
Are we protecting from the user attempting to use multiple or mixed encodings both at the byte level as well as the interperter levels that we will potentially use later?
Some of these questions are probably already answered by the construction and use of your web framework, but I'd suggest you understand how your framework protects the application for all of these questions. With experience, 1, 3, and 4 are almost always managed by other parts of the application, but until you know that, always ask those questions.
Why output encoding/escaping? Isn't this input?
When you decide to concatenate the username to the URI, and then proceed to make a request, ask yourself, "what am I really doing here?"
Obviously the intent is to take the username, concatenate it to the value that will be used...
Any time you use a variable--you need ask yourself all of those questions over again, plus one more:
What interpreter am I handing this value off to after I validate it?
In this case, you're passing the value into a data context that indicates it will be used in a URI. That means that the data will have to be properly encoded and escaped for use in the URI so that we don't introduce errors and possibly further vulnerabilities downstream in our stack.
To resolve this finding:
Answer all 7 questions for the username variable, then select the appropriate methods available to you from your application stack. It's true that you tagged esapi, but esapi can't help with all 7 questions here for you, just the input validation and the output encoding... which your application's security framework might already make available to you.

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.

JSON: Reject server requests from third parties

i intend to use JSON to implement a client server communication. My goal is for a Java-server to receive data via HTTP-Post from an Iphone-app.
I'm concerned about the fact of how I can be sure, that the data the Java-server receives only come from the Iphone-app? It may be possible that somebody else is catching the Java-Server URL and send rigged data?
Do I have a chance to recognize that? SSL encrypts transferred data only, but doesn’t solve the problem, i think.
kind regards
stormsam
You could send a token that is hardcoded into your application. Everything that comes without this valid toke should be rejected. Or you can use .htaccess and specify a user and password within your app.
You could use public key encryption, with users having their own keys and you keeping track of who are the legitimate users. This is the most reliable scheme I can think of. That, or giving each user a username and password. However, it's probably a lot more trouble than it's worth, and still doesn't protect against users that have registered with you but are still malicious.
Embedding a token in your application and then sending it with requests, as Cyprian suggests, is probably the easiest scheme and would probably work pretty well, but might be relatively easy to reverse engineer.
A somewhat better solution might be to program into your app a function that transforms any given input into an output; then, your server responds to a request by giving the app a piece of data to transform, and checks the result. A client that passes the test gets a session token which allows it to proceed. This does require an extra round-trip for authentication, though. And it's still not immune to being reverse engineered, since all the information needed to do so is stored in the app that's present on the user's machine.
Assuming you can reasonably protect your iOS app from being dissambled, you could use "signed requests" like the Facebook API (and probably others):
You'll need a shared secret on both client and server (e.g. a random string/byte array). The iOS app then hashes all request parameters plus the shared secret and appends the hash as additional request parameter, e.g. myserver.com/ws?item=123&cat=456 becomes myserver.com/ws?item=123&cat=456&hash=1ab53c7845f7a. Upon receiving a request, the server then recomputes the hash from the regular parameters and the shared secret and compares it to the value sig parameter. If both are equal, the request is considered valid (assuming integrity of your iOS app).
An advantage of this method is that it doesn't require additional round trips to fetch any one-time/CSRF-prevention tokens and does not require encrypting requests and responses (as long as you only care about the integrity of requests, not confidentiality).
You might have to take a look at this. It may give you some directions.

Protecting Sections of Source Code [duplicate]

This question already has answers here:
Handling passwords used for auth in source code
(7 answers)
Closed 7 years ago.
I'm writing a Java class that connects to a server and reads messages in a given queue.
I would like to protect the username and password, which, right now, appear as plain text in the source code.
What I'm wondering, is, what is a good way to do this? If I encrypt the username and password in a text file, won't I need to store the key, in plain text, in any source code that accesses this file? And then anyone else who decides to use my class will be able to gain access to these fields.
There is no prompt where someone can enter the key, either, as this class will autonomously be used by the system.
EDIT: this will become a java lib file. But those can easily be decompiled and thus are basically the original class files anyway, right? And the people this is being protected from are fellow developers of other systems who will gain access to this lib file.
My End Goal: is to have the username and password strings not appear as plain text anywhere, and for them to be as difficult as possible to crack.
It is not possible to do this. Even if you encrypt the login/password and store it somewhere (may it be your class or an external file) you'd still need to save the encryption key somewhere in plain text. This is actually just marginally better than saving username/password in plain text, in fact I would avoid doing so as it creates a false sense of security.
So I'd suggest that your class takes username/password as a parameter and that the system which is using your class will have to care about protecting the credentials. It could do so by asking an end user to enter the credentials or store them into an external file which is only readable to the operating system user that your process is running as.
Edit: You might also think about using mechanisms such as OAuth which use tokens instead of passwords. Tokens have a limited life time and are tied to a certain purpose so they pose a good alternative to access credentials. So your end users could get an access token with their,say, Windows credentials, which is then used inside your class to call the protected service.
This is a classic authentication issue, except that here, Eve can wear Bob's skin like a suit. Is that stretching the metaphor? I'm not sure.
The short answer is that there is no true answer, because what you want is something that basically violates information theory, in that anything transmittable is copyable and thus anything accessible can be viewed as no-longer-unique. Even if you had a magic box, they could just yank out the magic box with some serious JVM hacking.
The long answer is that there are a few solutions that are almost pretty okay, by making it really quite darn hard. I suggest you read the article linked, acquaint yourself with the ideas behind SRP, the vulnerabilities the spec entails, and try to figure out how to get the right to use and implement it. The problem is still there though. It's that you want a system that ensures Bob can never become a flesh-chariot, or fall to the dark side.
Fundamentally, you're breaking the tenth law. I agree with Kork, there's no solution that really does what you want, because you're trying to solve a social problem with a technical feat, one that is quite nearly provably impossible.
There are a few ways of handling this problem. The challenge as you've noted is associating an account with this automated process. So, here are some of the possibilities (from least secure to more secure):
Encrypt the username and password with a calculated key.
The calculated key is based on something both the client and the server can infer (like machine name and IP address)
Associate an authentication token with the client (OAuth style).
The token is negotiated by a one time user interaction to set up the client
The negotiated token is used for all future requests
The negotiated token is only valid for that client on that machine using that user account (server uses socket info to determine the match)
Use multiple forms of authentication
OAuth style token
Calculated token based on time + secondary id (requires clients and servers to be synched to the same time server)
It is important to note that your security measures should be more restrictive than it is worth to crack. In short, if all the potential bad guy is only going to be able to get your food preferences of the day you might not need to be as vigilent as protecting something more high profile like a bank account. User names and paswords are not the only means of authentication.
It's not clear which code has to know the user name & password. Are these credentials just for the queue being read? If so, only the server code would need to know them. In that case, you could store them in a server file whose permissions allow only the server code to read them. The file permissions would then be enforced by the server operating system, which presuambly is much better at security than most programmers will ever be.
I know this question is long since abandoned, but I want to point out that of course you can do this by requiring typed credentials at runtime but only storing a hash of the password. Of course, it needs to be a really good hash. Use a standard one, don't make up your own. The whole point of a hash is that even if you plain text the hashed result, no one else will be able to come up with a string that yields that hash, even if they know how the hash is computed.
Of course users can try a brute force attack, and since they know the result they want they can run it fast, so you need to use a highly secure password.

Java website protection solutions (especially XSS)

I'm developing a web application, and facing some security problems.
In my app users can send messages and see other's (a bulletin board like app). I'm validating all the form fields that users can send to my app.
There are some very easy fields, like "nick name", that can be 6-10 alpabetical characters, or message sending time, which is sended to the users as a string, and then (when users ask for messages, that are "younger" or "older" than a date) I parse this with SimpleDateFormat (I'm developing in java, but my question is not related to only java).
The big problem is the message field. I can't restrict it to only alphabetical characters (upper or lowercase), because I have to deal with some often use characters like ",',/,{,} etc... (users would not be satisfied if the system didn't allow them to use these stuff)
According to this http://ha.ckers.org/xss.html, there are a lot of ways people can "hack" my site. But I'm wondering, is there any way I can do to prevent that? Not all, because there is no 100% protection, but I'd like a solution that can protect my site.
I'm using servlets on the server side, and jQuery, on the client side. My app is "full" AJAX, so users open 1 JSP, then all the data is downloaded and rendered by jQuery using JSON. (yeah, I know it's not "users-without-javascript" friendly, but it's 2010, right? :-) )
I know front end validation is not enough. I'd like to use 3 layer validation:
- 1. front end, javascript validate the data, then send to the server
- 2. server side, the same validation, if there is anything, that shouldn't be there (because of client side javascript), I BAN the user
- 3. if there is anything that I wasn't able to catch earlier, the rendering process handle and render appropriately
Is there any "out of the box" solution, especially for java? Or other solution that I can use?
To minimize XSS attacks important thing is to encode any field data before putting it back on the page. Like change > to > and so on. This would never allow any malicious code to execute when being added to the page.
I think you are doing lot of right things by white listing the data you expect for different fields. Beyond that for fields which can allow other characters which can be problematic encoding would fix the issue for you.
Further since you are using Ajax it gives you some protection as people cannot override values in URL parameters etc.
Look at the AntiSamy library. It allows you to define rulesets for your application, then run your user input through AntiSamy to clean it per your rules.
The easiest way is to do a simple replacement for the following
< with <
> with >
' with \'
That will solve most database vulnerability.

Categories

Resources