Response Header validation in java - java

I am passing directly a user defined parameter in my response header. Which I have learned is not a good idea since that way user can manipulate header and it can lead to Cross site scripting attacks and other kind of multiple attacks.
https://www.fortify.com/vulncat/en/vulncat/python/header_manipulation.html
What I am doing for preventing this is validate the user input for "http response splitting" by replacing "\r" and "\n" characters with empty string "". Is this enough or I have to check for other characters also. Any pointers would be of great help.
This is my code.
if(response != null)
{
newResponse = response.replaceAll("[\r\n]", "");
}
Is this enough for preventing this kind of attack or I should also validate for other characters.

A whitelist is much safer than a blacklist. Whether you can use a whitelist depends on how much you know about the user defined parameter.
More here:
http://cwe.mitre.org/data/definitions/113.html

The information you give is insufficient for a proper answer. We would need to know what you do with the parameter value in order to tell whether your actions are good enough or not and what kind of an environment your code runs in. A short, 100% correct (but pretty useless) answer would be "no."
Security is not implemented by following simple bullets taken outside of their original context. You took it from Python context and placed it directly to Java context. You must understand your environment and what your code does completely. There is no silver bullet.

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.

XSS prevention, minimal implementation

In our project in order to prevent XSS we added filter (HttpServletFilter) that simply escapes all occurrences of "<" and ">" in Json (wrapping user input) like:
json = json.replace("<", "<").replace(">", ">");
Question is: Is above enough to guarantee that XSS will never happen?
Or (in other words) can you provide example of user input that will cause XSS like behavior in our system?
Update: thanks to some useful answers, I understand that XSS still possible in case user input is used as source for href attribute or directly in javascript.
E.g. in case where triangle brackets already present on the their place around potential user input appearance.
But we never use user input data this way.
Any other suggestions?
Short answer: No, it's not enough
Please go read the OWASP XSS Prevention Cheat Sheet which explains the different contexts where XSS can occur.
No, you can not be sure. For example (from here):
<a href="{{anURL}}">
XSS Attack:
anURL = "javascript:alert(1)"
or
<script>var aPage = {{aVar}};</script>
XSS Attack:
aVar = "1;alert(1)"
You also could find some material from Microsoft or a sample implementation how to do it better on Github. A more detailled answered you may find on security.stackexchange.com.
Unfortunately It's not enough to escape triangle brackets. For example your site probably has some JavaScript code which deals with user input data. Someone could insert something malicious in a user input field and it would be executed directly by your JavaScript code. The malicious data would not need to contain triangle brackets because it is being injected straight into the JavaScript.
This old article is a good starting point. https://support.microsoft.com/en-us/kb/252985

Preventing xss attack in java web app while saving actual values in database

In a Recent scan of our java based web application through AppScan it was found that the application was prone to XSS attacks.
I did my research and found that a ServletFilter was probably the easiest way to protect the application.
I introduced the filter where I extended HttpServletRequestWrapper (because java does not allow request param to be changed, there is no request.setParam method). I introduced a sanitize method there and here is what it does
result = ESAPI.encoder().canonicalize( input);
// Avoid null characters
result = result.replaceAll("\0", "");
// Clean out HTML
result = Jsoup.clean( result, Whitelist.none() );
Post this change, it was good, I tested for XSS vulnerabilites myself and most of them were fixed. But this posed another problem. Suppose I have a form to create a product, and in product name a user enters something like
<script>alert('somethingStupid')</script>
Now Ideally I should be able to save this to database, but still be protected from XSS attack. Not sure what to do in my filter or anywhere else to achieve this.
HTML-injection is an output-stage issue, caused by forgetting to encode text when injecting it into a context where characters are special. ESAPI offers encoders for various contexts, as discussed by #Zakaria. If you use these consistently, each in the correct context, you have fixed injection-related XSS issues.
If you are using purely JSTL tags like <c:out> for your templating, these will also HTML-escape by default. In general, it is best to generate HTML using a templating system that works HTML-escaping out for you automatically, because otherwise you are likely to forget to manually encodeForHTML occasionally.
(Aside: on project where I am compelled to use the mostly-terrible owasp-esapi-java library, my preference is for encodeForXML over the HTML encoders, as it produces output that is safe for HTML content and quoted attribute values whilst not needlessly attempting to produce entity references for non-ASCII characters. I would typically try to avoid injecting into JavaScript string literals; it is typically easier and more maintainable to inject run-time content into HTML data- attributes and read them from separate JavaScript DOM code.)
Trying to filter out HTML at the input stage is a lamentably still-popular but completely misguided approach. It prevents you from entering HTML-like input when you need to—as you have found out, with the <script> example. Indeed, if StackOverflow used such an input filter we would not be able to have this conversation.
What's more, it's not resilient: there are many ways to smuggle potential injections past input filters. To make a filter effective you'd have to consider blocking pretty much all punctuation, which is generally not considered acceptable. Plus, any data that gets into your application by means other than request parameters won't be vetted.
Input validation is great for enforcing business rules on the formats of particular input fields, and can be used to filter out input that you never want, like control characters. But it's the wrong place to be worrying about escaping or removing HTML. The time to do that is when you're creating HTML.
Cross Site Scripting (XSS) is a security issue which occurs when there is no mechanism of validating user input so the result will be an exploitable javascript code generally.
3 types of XSS are known : Reflexive XSS, DOM-based XSS and Persistant XSS.
In your case and since you're using OWASP ESAPI, canonicalizing inputs is not enough, sure it's a good way to defense against Untrusted URL in a SRC or HREF attribute but it's not enough.
You should Follow thess Rules : Source ( XSS (Cross Site Scripting) Prevention Cheat Sheet of OWASP ) (here are some rules for further reading follow the link) :
1- HTML Escape Before Inserting Untrusted Data into HTML Element Content: see the example :
String safe = ESAPI.encoder().encodeForHTML( request.getParameter( "input" ) );
2- Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes :
String safe = ESAPI.encoder().encodeForHTMLAttribute( request.getParameter( "input" ) );
3- JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values:
String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( "input" ) );

Prevent exposure of sensitive data against PCI standards - response.getWriter().write(xml.toString())

I am fixing code against the code audit report. It says "PREVENT EXPOSURE OF SENSITIVE DATA" against the line having the syntax response.getWriter().write(xml.toString()). The whole code is below.
String alertId = request.getParameter("alertId") != null ? request.getParameter("alertId") : "";
String desc=AAAA.getBBBB(Long.parseLong(AAAA.getCCCC(alertId)));
StringBuffer xml = new StringBuffer();
xml.append("<?xml version=\"1.0\"?>");
xml.append("<parent>");
xml.append("<child>");
xml.append("<alertDesc>");
xml.append(desc);
xml.append("</alertDesc>");
xml.append("</child>");
xml.append("</parent>");
response.getWriter().write(xml.toString()); // ISSUE IN THIS LINE
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
I have done sufficient home work and can fix it for the XSS attack and used ESAPI for the same. But dont know how to fix this one. Please give suggestions
The report has the below message against the reported issue.
"Leakage of toString() result ("xml") via web page"
after the day long r&d i found that the sax parser can help me in this case. it is actually a memory leakage at the StringBuffer.toString() syntax, due to which sensitive data is getting exposed and lost. but i dont know how to implement that. also at some place i found the use of StringBuilder() class instead of StringBuffer() class. Can anybody help me or give their valuable suggestions.
Thanks in advance.
Also I have the same issue for another type of the code. it is below.
StringBuffer content = (StringBuffer)file.get("content");
response.setContentLength((int)content.length());
response.getWriter().write(content.toString());
Again i dont know how to fix this one. THE issue is same leakage of sensitive data been reported by the tool.
As I have told in my comment, I do not thing that the comment has something to do with the code itself but with the exposure of sensitive data. I have read the PCI-DSS document and I don't remember it says anything about how something it should be coded (regardless good practices). You can take a look to all PCI documentation available by yourself. It is a hard task, a better approach would be to try to find out what the consultant meant.
It is really difficult to fix something when you don't know where the problem is.
The content.toString() needs to be properly validated. use ESAPI to validate it strictly. writing directly to response is really vulnerable and if if the data is output from a method having request as input then its twice vulnerable. major security issue.

expand Tiny url in java

I want to write a code in java that takes a url identify whether it is tiny url or not. if yes then it will identify the url is malicious or not. if not malicious print the url...
Please can any body help me....
You can use HttpClient to detect whether the URL is redirected to another location. After that it's a simple case of:
if (!isMalicious(redirectTargetURL))
{
System.out.println(redirectTargetURL);
}
The isMalicious(...) implementation is left as an excercise for the reader.
If you trust google to implement isMalicious(...) then they have done so with their Safe Browsing API.
So 2 main things you want:
Identify if it's a tinyurl
Identify if the URL is malicious
The answer to part 1 is easy. Just check if the URL belongs to the domain 'tinyurl.com'. Should be straightforward to either test raw URL string, or the host part returned by the getHost() method of a java.net.URL object.
Part 2 is more difficult to code up from scratch...
First you will need your code to figure out where the tinyurl redirects to.
The next bit really depends on how you want to define 'malicious'. Detecting deceptive URLs will require a bit of work (e.g. finding the difference between something like www.stackoverflow.com and www.stack0verf10w.com), or comparing the target URL with a malicous URL list (there's sites that publish them). There's also checking for multiple redirects, popups, and the list of criteria could go on and on.

Categories

Resources