HttpServletRequest attributes and parms getting "lost"? with 1.6 JavaEE spec? - java

Our code - which has not changed, is behaving differently in JavaEE1.4 than it did in 1.6 with respect to HttpServletRequest attributes and parameters. However this different behavior is not (always) consistent. We are also using BEA Weblogic 10 (vs. version 8, where it still works).
For example:
In some cases when we do a "request.setAttribute(name, value)" and later on do a "request.getAttribute(name)" - there seems so be no such "name" at all in the request - as if we've never set it. I have run this through our Eclipse debugger in both 8v3 and Ja11 and I do see this attribute in 8v3 but cannot find it in Ja11, which is consistent with how the code is behaving.
Our code consistently fails in in at least one case, where the values of "name" and "value" are both defined as "public final static String;"
I have coded around this one particular instance line by getting the information I need via "request.getPathInfo" instead, however I SUSPECT the same or similar problem is occurring elsewhere in our code - but in one other such instance it is so entirely SPORADIC that I have been unable to recreate it while in debug mode (or even in putting Sysout statements) and therefore cannot trap the line that is the problem. In another instance, also one I can't definitively trap - I believe that it's the request.getParameter(name) that is not returning anything even though that "name" does exist on the jsp form, with data.
(Note that I am somewhat simplifying what our code actually looks like as we have an entire RequestContext class which mplementsSerializable and encapsulates all the relevant data and methods for one request cycle of an HttpServlet - ie HttpServletRequest, HttpServletResponse, HttpSession, HttpServlet
Anyway I have heard that the Java Servlet spec has had some changes in 1.6 - but does it somewhere explicity state what those differences are or do I literally have to pull up the 1.4 spec next to it and do my own compare???
I am admittedly not well versed in dealing with HttpServeltRequest, but this code has been working FINE for YEARS - have a hard time believing something so basic/common as get/setAttribute and getParameter would have changed...

Servlets are not thread-safe and do not get recreated per request. All requests are being served by one and the same servlet object. Are you storing variables in public static final fields of the servlet class?

Related

TAINTED_SOURCE - os_command_sink

Further to Tainted_source JAVA, I want to add more information regarding the error os_command_sink I am getting.
Below is the section of code that's entry point of data from front end and marks parameter as tainted_souce
Now when the DTO - CssEmailWithAttachment is sent to static method of CommandUtils, it reports os_command_sink issue. Below is the code for the method
I tried various ways to sanitize the source in controller method - referenceDataExport i.e. using allowlist, using #Pattern annotation but coverity reports os_command_sink all the times.
I understand the reason as any data coming from http is marked as tainted by default. And the code is using the data to construct an OS command hence the issue is reported.
Coverity provides below information regarding the issue
So I tried strict validation of entityType that it should be one of the known values only but that also doesn't remove the issue.
Is there anyway this can be resolved?
Thanks
The main issue is that the code, as it currently stands, is insecure. To summarize the Coverity report:
entityType comes from an HTTP parameter, hence is under attacker control.
entityType is concatenated into tagline.
tagline is passed as the body and subject of CdsEmailWithAttachment. (You haven't included the constructor of that class, so this is partially speculation on my part.)
The subject and body are concatenated into an sh command line. Consequently, anyone who can invoke your HTTP service can execute arbitrary command lines on your server backend!
There is an attempt at validation in sendEmailWithAttachment, where certain shell metacharacters are filtered out. However, the filtering is incomplete (missing at least single and double quote) and is not applied to the subject.
So, your first task here is to fix the vulnerability. The Coverity tool has correctly reported that there is a problem, but making Coverity happy is not the goal, and even if it stops reporting after you make a change, that does not necessarily mean the vulnerability is fixed.
There are at least two straightforward ways I see to fix this code:
Use a whitelist filter on entityType, rejecting the request if the value is not among a fixed list of safe strings. You mentioned trying the #Pattern annotation, and that could work if used correctly. Be sure to test that your filter works and provides a sensible error message.
Instead of invoking mailx via sh, invoke it directly using ProcessBuilder. This way you can safely transport arbitrary data into mailx without the risks of a shell command line.
Personally, I would do both of these. It appears that entityType is meant to be one of a fixed set of values, so should be validated regardless of any vulnerability potential; and using sh is both risky from a security perspective and makes controlling the underlying process difficult (e.g., implementing a timeout).
Whatever you decide to do, test the fix. In fact, I recommend first (before changing the code) demonstrating that the code is vulnerable by constructing an exploit, as that will be needed later to test any fix, and is a valuable exercise in its own right. When you think you have fixed the problem, write more tests to really be sure. Think like an attacker; be devious!
Finally, I suspect you may be inexperienced at dealing with potential security vulnerabilities (I apologize if I'm mistaken). If so, please understand that code security is very important, and getting it right is difficult. If you have the option, I recommend consulting with someone in your organization who has more experience with this topic. Do not rely only on Coverity.

Why use enums when it creates dependency across teams?

I know enums are used when we are expecting only a set of values to be passed. We don't want the caller to pass anything other than the well defined set.
And this works very well inside a project. Because you know what you've to pass.
But consider 2 projects, I am using the models of 1st project in 2nd.
Second project has a method like this.
public void updateRefundMode(RefundMode refundMode)
enum RefundMode("CASH","CARD","GIFT_VOUCHER")
Now, I realise RefundMode can be PHONEPE also, So If I start passing this to 1st project, it would fail at their end (Unable to desirialize enum PHONEPE). Although I've added this enum at my end.
Which is fine, because If my first project doesn't know about the "PHONEPE", then it doesn't know how to handle it, so he has to update the models too.
But my problem is, Let's imagine a complex Object am trying to pass, which also takes this RefundMode, when I pass a new RefundMode just this field should be become null or ignored at their end right ? Rather than not accepting the whole object, and breaking the entire flow/request.
Is there a way I can specify jackson (jsonproperties) to just ignore that field if an unknown value is being passed. Curious to know.. (Although In that case, I am breaking the rule of ENUM) So, why not keep a String which solves all the problem ?
It's all about contracts.
When you are in a client/server situation, being a mobile app and a web server, or a Java library (jar) and another Java project, you have to keep the contracts in mind.
As you observed, a change in contracts need to be propagated to both parties: the client and the server (supplier).
One way of working with this is to use versioning. You may say: "Version 1: those are the refund modes.". Then the mobile app may call the web server by specifying the contract version in the URL: /api/v1/refund?mode=CASH
When the contract needs to be changed, you need to consider what to do with the clients. In the case of mobile apps, the users might not have updated their app to the latest version, so their app may still be calling /api/v1 (and not supporting new refund modes). In that case, you may want to support both /api/v1 and /api/v2 (with the new refund mode) in your web server.
As your example shows, it is not always possible to transparently adapt one contract version to another (in your example, there is no good equivalent to PHONEPE in the original enum). If you have to deal with contract updates, I suggest explicitly writing code to them (you can use dedicated JSON schemas, classes and services) instead of trying to bridge the gaps. Think of what would happen with a third, fourth version.
Edit: to answer your last question, you can ignore unknown fields in JSON by following this answer (with the caveats explained above): https://stackoverflow.com/a/59307683/2223027
Edit 2: in general, using Enums is a form of strong typing. Sure, you could use Strings, or even bits, but then it would be easier to make mistakes, like using GiftVoucher instead of GIFT_VOUCHER.

Spring view safety

Is it possible to define the type of the view commands in Spring? As it is right now, it is dangerous for us to change anything in our command classes. Properties on these classes may be used by the view (path="myDto.persons[0].name"), but if anything in the command class changes, the view will only fail runtime.
All other parts of our MVC stack is tested, so we can safely do refactorings when needed. The only problem is with the view, as the paths are "just strings", and we cannot in any reasonable way search and replace everywhere we use the specific command.
It would be a great help if there was some way to tell Spring what type the command actually is, so it could be validated when we do precompilation of our .jsp's. An added bonus would also be completion when editing the view, but I guess that is more of an IDE issue.
So, do any of you know how and if this is possible?
It might be possible to add type safety to your views if you completely redesign your JSP files (in a very ugly way if I may say so myself).
Servlets offer you type safety since that's Java code. If you refactor your classes and miss something, the compiler will immediately tell you you missed it. But JSPs replace servlets as a view technology offering a much more dynamic/rapid development pace (no more endless out.write instructions opening tags, closing them, escaping quotes etc).
EL expressions, as you noticed, are basically strings which later get evaluated and fail at runtime if something is off. Even if you precompile the JSPs, it would still fail because ELs remains as strings in the generated servlet. They are either passed as such to tags and they evaluate it themselves, or if using a JSP 2.x version, the servlet container itself wraps the expression in an evaluation call before passing it as a value.
Basically for a version less than JSP 2, for a tag like:
<my:tag value="${bean.someProp}" />
You get a result like:
myTagInstance.setValue("${bean.someProp}");
in the servlet.
The tag itself will do the evaluation of that string, at runtime.
For JSP 2 you don't get any better, the evaluation still occurs at runtime but the servlet container takes this burden away from the tag, generating a code like:
myTagInstance.setValue((SomePropTypeCastHere) ProprietaryServletContainerEvaluationUtil.evaluate("${bean.someProp}"));
If the content of the object itself isn't the expected one when evaluation occurs, you get weird results or errors.
The only way (I know) to enforce static typing in a JSP is to bring Java code back in the JSP (the thing EL was invented to eliminate). That is why I said at the begging that you have to change your JSP in an ugly way.
If all your tags can use <rtexprvalue>true</rtexprvalue> values, you can use scriptlets to enforce type safety.
A tag like:
<my:tag value="<%=bean.getSomeProp()%>" />
now gets converted to this:
myTagInstance.setValue(bean.getSomeProp());
If the someProp property was renamed, deleted, changed type or whatever, the compiler can tell you about it. The IDE itself should be able to tell you, you don't even need to precompile the JSPs.
If I'm not mistaken, the Spring tags support runtime expressions so this should work... if you are willing to mess up your JSPs that is!
As for the IDE support for completion, you have that for scriptlets but not for EL. That's because for EL it's the same discussion, it happens at runtime. How is the IDE to know what's in context (page, request, session etc) when the JSP is executed, and know that when you are developing the JSP?

GetPropertyAction vs System.getProperty in obtaining system variables

I have been using quite a lot of
System.getProperty("property")
in order to obtain environmental information. However, it seems to me that Sun prefers the following :
(String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("property"));
The strange thing is that this code involves a cast and as a result should be slightly slower than the
System.getProperty
implementation, that only uses a security manager and then instantly fetches the property from the instance variable props. My question is why did Sun chose to use the second method to obtain most environmental variables in their code internally, while
System.getProperty
seems like the faster way to go?
Both methods have a different meaning, and thus the right one has to be used depending on what the current code needs to do.
The code System.getProperty("property") says "Give me the value of the property, if the current security context allows me to read it."
The code that uses doPrivileged says "Give me the value of the property, if the current class (where this line of code is in) is allowed to read it."
The difference comes into play, when the protection domain of the current class is different from the currently active security context.
For example, consider a framework which executes the code of a plugin, which is untrusted. So the framework uses a SecurityManager to restrict the actions of the untrusted plugin code. But of course the plugin may call some methods of the framework, and suppose that one of these methods needs to read a property. Now as the method is called from untrusted restricted code, it is itself restricted and thus reading the property would fail. But of course the framework trusts itself and wants itself to be able to read that property, even in the case that somewhere in the call stack is untrusted code. That's when you need to use doPrivileged. It basically says "no matter what is up there in the call stack, I am a piece of framework code, and I am allowed to do whatever the framework code is allowed to do". So reading the property using the second method succeeds.
Of course one needs to be careful when using doPrivileged in order to not let the (untrusted) calling code do to much. If, for example, the framework code offers the following method to the plugin:
public String getProp(String key) {
return (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(key));
}
this would completely invalidate the policy that the untrusted code is not allowed to read system properties, because it can just use your method.
So use this method only when you know it is safe to do it, and only when you need it (which is, when you want your code to be able to do more than some other code should be able to do directly). Inside a normal application (which usually runs with no SecurityManager or the same security context for all code), there is no difference and the first method should be used.
I would recommend to stick with System.getProperty() since sun.security.action.GetPropertyAction seems to be proprietary to SUN and will not work on all Java VM implementations. Even the compiler warns you about it as:
warning: sun.security.action.GetPropertyAction is Sun proprietary API and may be removed in a future release
To understand what it actually means see this answer.
The reason to use a class like sun.security.action.GetPropertyAction is to avoid loading several, basically identical classes.
If you wrote:
(String) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<java.lang.String>() {
String run() {
System.getProperty("property");
}
}
);
Each time you wanted to get a system property, you would load a new class for each getProperty call. Each class takes system resources and lives as long as the containing ClassLoader (forever for the bootclassloader).
Check out the javap output for more details:
javap -c -v -p sun.security.action.GetPropertyAction

Possible to specify access to isAttribute vs getAttribute in JSP EL?

Our Topic object has BOTH isChannel and getChannel public methods. The object graph is too complex to change this. Channel has an Integer type.
We are migrating from one application server to Tomcat. When using this expression ${topic.channel.type}, in JSPs our current app server finds the getChannel method. However, Tomcat finds the isChannel method and we get errors since the return type is a Boolean, not a Channel. Is there a way to tell Tomcat to prefer getters over boolean public methods?
For now I'm just going to write a helper function or expose a new method, but I have a feeling I'm going to come across this quite a bit during the migration.
Unfortunately, you can't force a method call like that.
I have checked the Javabeans and EL specifications, but nowhere is specified what the preferred method is when both isXXX() and getXXX() methods are present. However, I do agree that it makes more sense to prefer the getXXX() one in this particular case. This should also be programmatically possible. I think it's worth the effort to report this as an issue against the Tomcat EL implementation.
In theory, this should be more of a JavaBeans issue than an EL implementation issue. One thing you might try is to find out how the java.beans.Introspector views your Topic class. One way to do that would be to run this code I wrote a while back for the Struts wiki. Depending on the complexity of your class, it might make sense to create an explicit java.beans.BeanInfo class to force the channel property to always be exposed as an Integer.

Categories

Resources