Avoiding Parameter Tampering using ParameterNameAware interface (Struts2) - java

I am working on my struts2 application to solve Parameter tampering problem. I heard this can be solved by implementing ParameterNameAware interface in my actions, but I haven't find a best example explaining this condition. Can anyone provide me a good example on how to use ParameterNameAware. Quick answers will be really appreciated.

The wholde idea about this interface is to maintain a list of valid parameter names and there by rejecting any request parameters that are not in this list(whitelist).This is really helpfull in situations where a hacker tries to include unwanted form field values as a hidden variable that are likely to execute in certain situations.For example, include so many form fiels varialbles (>10000 etc) that may create Denial Of serice on server side.
Once you have implemented this, you can immediatly reject any unwanted parameters in the current request scope or you can take a better control of this situation.
Probable implementation :
Implement the ParameterNameAware interface and override its acceptableParameterName method as follows:
public boolean acceptableParameterName(String parameterName) {
boolean allowedParameterName = true ;
if ( parameterName.contains("session") || parameterName.contains("request") ) {
allowedParameterName = false ;
}
return allowedParameterName;
}
You need to implement this interface in your form bean that is having getter and setter methods in it. In this particular example, if the current request contains any form field variable like request or session, then it is a failure scenario.This is just a typical example here. There is a complete documentation in this link
Class ParametersInterceptor

Related

what kind of pattern should I use to solve this problem

I am working on an requirement(Spring mvc architecture, java 8), actually it's kind of fix ,where I have to filter the data on basis on an condition.
I can filter data in DAO layer that is by applying joins in data base query . But the problem is there are lots of method where I am supposed to apply this condition for filtering data.
First I thought :
I should define an instance variable in DAO class and set this variable via method from Action class(this condition data supposed to come from Action to DAO layer). But it seems very odd and general practice doesn't allow it too.
Other I can search all the method and change the parameter which is also not good practice.
I am not sure how to achieve this.
Does anyone have any idea about this?
any pattern or any suitable method.
E.g.
ActionClass{
doSOmething(){
variable condition = object.getCondotion();
variable someData = serviceClass.fetchDataOnCondtion(condition);
}
}
ServiceClass{
fetchDataAOnCondtion(variable condition){
dataObjectDAO.fetchDataAOnCondtion(condition);
}
fetchDataBOnCondtion(variable condition){
dataObjectDAO.fetchDataBOnCondtion(condition);
}
}
someDataObjectDAO{
fetchDataAOnCondtion(condition){};
fetchDataBOnCondtion(condition){};
fetchDataCOnCondtion(condition){};
fetchDataDOnCondtion(condition){};
}
here in DAO class I am using same condition variable in every method on DAO class , but there are a lot method which is quite tedious to change and also I need to change the interface method def too.
please provide some suggestion how can I solve this problem?
thanks in advance !

Is the Sonar rule for Spring '"#RequestMapping" methods should be "public"' accurate?

There's a sonar rule for Spring that states: "#RequestMapping" methods should be "public"
And gives these examples:
#RequestMapping("/greet", method = GET)
private String greet(String greetee) { // Noncompliant
#RequestMapping("/greet", method = GET)
public String greet(String greetee) { // Compliant
These are the reasons given:
marking a sensitive method private may seem like a good way to control how such code is called. Unfortunately, not all Spring frameworks ignore visibility in this way. For instance, if you've tried to control web access to your sensitive, private, #RequestMapping method by marking it #Secured ... it will still be called, whether or not the user is authorized to access it. That's because AOP proxies are not applied to non-public methods."
This seems reasonable for private methods, but does it really hold true for default (package-protected) visibility?
i.e.
#RequestMapping("/greet", method = GET)
String greet(String greetee) {
Source: https://rules.sonarsource.com/java/type/Vulnerability/RSPEC-3751
edit: just to clarify, I'm not asking if a #RequestMapping method has to be public, it doesn't. See spring-restbucks for an example
I'm asking if declaring the method as package-private rather than public is really a vulnerability, as suggested by Sonar.
edit 2: I created a project here to try to demonstrate it: https://github.com/barrycommins/boot2-security
The tests show that the #PreAuthorize rules are applied to the controller method, even though it is package private.
Whether that should be the case, and whether it's reliable, I'm not sure.
From what I can see, it seems like the comments and the existing answer are trying to address the details, when that isn't really your question.
I'm going to make some assumptions, because I haven't investigated the details of this issue. I'm just going to read into this what I see here.
In my opinion, the key thing the error message is trying to convey is that you shouldn't label something non-public if it actually isn't. I think this is debatable, but that is what the error message is saying, again, in my opinion.
The entire point of adding a #RequestMapping annotation is to prepare that method for being called from outside the service. In fact, it implies that the method is ONLY called from outside the service. If you declare that method as package private, that presents a confusing intent.
On the other hand, I can now see an argument to mark methods with #RequestMapping as "private". If the method will truly only ever be called from outside the service, and not from any application code (excluding framework code), how else could you express that except with "private"?

Find a Decorator of a particular type when using the Decorator Pattern?

I'm building an app that needs to use multiple types of similar sensors. Since the sensors could also have different behaviours, or combinations of behaviours, I decided to use the decorator pattern.
In short, I have a hierarchy that looks like this:
So any of the concrete ISensorDecorator classes can decorate (wrap) any of the concrete IMeasureSensor classes, but since a concrete ISensorDecorator also is a concrete IMeasureSensor, they can wrap each other. So for example
IMeasureSensor sensor = new FilteredSensorDecorator(
new CalibratedSensorDecorator(
new AccelerometerSensor()
)
);
is a valid statement that declares a filtered and calibrated accelerometer sensor.
Now let's say I have a method called setCalibration() in CalibratedSensorDecorator. Obviously I can't call
sensor.setCalibration();
because IMeasureSensor doesn't have a setCalibration() method. And trying to use
((CalibratedSensorDecorator)sensor).setCalibration()
won't work either, since sensor is a FilteredSensorDecorator.
How can I get to the CalibratedSensorDecorator in this particular case, and more generally to any specific decorator in any "chain" of decorators? I don't want to store them as separate variables, I want to do it dynamically.
Since its a design question, there won't be any right answer, you need to make choice which could be good or not that good.
You shouldn't add a method for particular class since it will violate the Liskov substitution principle
Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
You can initialize the calibration in constructor CalibratedSensorDecorator and use it while executing your required function.
If that doesn't meet your requirement, then may be CalibratedSensorDecorator doesn't belong in your sensor hierarchy. Consider separating it and use Strategy pattern to decide which one to use.
Edit 1:
what I understand it doesn't say that you shouldn't add methods to subtypes?
Yes, you are right. It doesn't prohibit from adding methods but if the methods are changing the state of an Object, then it should be re-considered. All these patterns are just the guidelines which can be tweaked as per our needs.
To explain my rationale:
Imagine you have create the setCalibration() on CalibratedSensorDecorator. You have following way to expose CalibratedSensorDecorator to either internal developer or to external developer. You have created a Factory which just returns IMeasureSensor as follows:
public IMeasureSensor getCalibratedSensor(){
...
}
Now the user of your API simply gets this and is happy that his/her current code is working. But realizes that he/she missed to setCalibration() which was found after hours of debugging. Moreover he/she has to write the type checking and type casting code to make use of this feature, which might not be great for clean code.
You should try to keep your classes as immutable as possible so that the debugging and maintenance are at ease. There is no harm in recreating the object since the older will be garbage collected.
Again its just my suggestion, its your decision to carefully consider what's best for your use-case. You can still go ahead with your new approach to create the method if its mandatory and ensure proper documentation has been made to make user understand the usage.
While the answer by Sagar discusses some (valid) reasons for considering using another approach than the decorator pattern, I came up with a working solution for the actual problem of finding the correct decorator.
/**
* Walks the decorator hierarchy recursively from the outside in (excluding the final
* IMeasureSensor which is not a ISensorDecorator), and returns the decorator of the given class.
* If none can be found, null is returned.
*/
IMeasureSensor findDecorator(IMeasureSensor sensor, Class decoratorClass){
if( ISensorDecorator.class.isAssignableFrom(sensor.getClass()) ){
return (sensor.getClass() == decoratorClass)
? sensor
: findDecorator(((ISensorDecorator) sensor).getDecoratee(), decoratorClass);
}
else
return null;
}
The method ISensorDecorator.getDecoratee() simply returns the "decoratee", i.e. the IMeasureSensor that the decorator decorates.
public IMeasureSensor getDecoratee(){
return mMeasureSensor;
}
You can then use findDecorator() to find a (the outermost) decorator of a given type like this:
IMeasureSensor sensor;
...
CalibratedSensorDecorator s = (CalibratedSensorDecorator) findDecorator(sensor, CalibratedSensorDecorator.class);

Can we return any class object to Interceptor from action class

Can we return any object type to an interceptor from action class methods instead of returning a string, then return a string from the interceptor to identify the required result?
Technically, yes, if you bypass the "invoke" mechanism. Should you? Likely not.
The cleaner, canonical S2 approach would be to expose a property to your interceptor, defined by an interface the action implements. For example, you might call it Revisionable or RevisionAware and expose a pair composed of before and after references.
In your interceptor you'd check for that interface, in pseudocode:
if (action instanceof Revisionable) {
return processRevisionablePair();
}
You might include a method in the interface that handles action- or model-specific revisions that returns an appropriate result, or if it's the same across the application, you could wrap up the functionality in the interceptor and have "modified" and/or "unmodified" results, etc.
Action methods that return something other than a string deviates from framework expectations, leading to multiple ways to handle different actions, multiple ways to test, and so on. Yuck. Keep things consistent, and avoid a layer of documentation and differentiation that isn't really necessary.
Lastly, to return a result based on the action method return value, you need to implement a PreResultListener that will provide the result name. Results have already been rendered after invoke returns as per the docs.
You can return instance of Result interface directly from your action.

How should I design the method signature for the following scenario

If you have a method where the input parameter might be the output.
Let's say that we have a save method that generates an autogenerated id that the client might be interested to use after the call to save().
Person
id (autogenerated)
name
... (other fields)
Should you design the method signature like this:
1.
public void save(Person person);
The client call:
personService.save(person);
System.out.println(person.getId());
2.
public Person save(Person person);
The client call:
person = personService.save(person);
System.out.println(person.getId());
We know that in a method call that receives an object the reference to that object is passed so any changes made to the object will be perceived by others as long as they have the same reference. But in the case of remote calls serialization/deserialization occurs so my object reference is a different reference from the remote service object. So even though changes are made there the client won't notice the difference.
At this time I know that the method is not going to be a remote call so I could design it using the first signature. But what if in the future this changes and needs to be called as a remote call.
So my question is:
Should I design my API thinking that the API might be called in the future as a remote call and don't use the object parameter as a way to return a value to the client (2) or should I design my API according to my actual situation which the sevice is not remote (1)?
Thank you
It's OK to do both; have save() return the new ID and have a getId() method. Returning a value from a "setter" (a method that changes state) has lots of precedents - the java Collections API does it all the time, eg Map.remove(Object) returns a boolean.
Fluent Interface
There's another pattern you might want to consider, the Fluent Interface pattern. With a fluent API, you return the object (ie this) from every method you would otherwise return void. This lets the caller "chain up" method calls. With a fluent interface, your code would look like this:
public Person save() {
// do your save stuff
return this;
}
If you want the ID after a save, you'd code this:
save().getId();
Simple! This pattern has been used in lots of existing java code too, notably hibernate as in this java fluent code example
I would recommend using fluent, if nothing else to get the practice using it
Why not do both? Use the second signature, modify person locally, and for the time being, just return a reference to that same person. This way, changing it in the future for whatever needs arise won't change the API, and current users can still use your first approach.
That being said, in general, I am uncomfortable with methods that change their parameters unless that is their sole purpose and they are named and documented to indicate this. From the standpoint of "what is the method doing, and what new information do I get from it," I would probably opt for a signature like:
public ID save(Person);
I would recommend using the first approach since objects are seldom used in isolation. The Person object is usually referenced by other entities such as Employee. If you create a new instance, you're invalidating the whole object graph and believe me, you don't want to mess around with deep copying.
As for the possibility of future RPC's, whatever you'll be using to accomplish this, it will most likely be able to update the ID field after the operation commits.
#CPerkins - Objects are passed by "reference value" to be absolutely correct ;)

Categories

Resources