How to make Singleton Class secure
I have a Singleton class which I instantiate using reflection by a call to a public getInstance method that return the object from a private constructor. I have to use reflection as I dont have any other options since my class instantiation is decided on runtime. How will I secure other form instantiating the same class again by using reflection on my private constructor? Any ideas?
put a static boolean in the class ; pass it to 'true' once an instance is created, and if the boolean is set to true (next instanciations) throw some instanciationexception
That wont work under reflection. I access a private constructor likethis private A(){// Some code}using reflection on the class!!
> That wont work under reflection. I access a private
> constructor like
> this
> private A(){
>// Some code
>
> using reflection on the class!!
I think the previous poster intended to put the check in the private constructor, in which case he probably is right...
package mypackage;
class A {
private static A singleton=null;
private String name;
private boolean instantiated=false;
private A(String name) {
if(!instantiated){
singleton=new A("Hello");
instantiated=true;
}
}
public static A getInstance(){
if(singleton==null){
return singleton=new A("Hello");
}else{
return singleton;
}
}
}
I Suppose this is the actual piece of code that he said, but this code will loop infinitely!!!
Although if someone is going to the bother of getting hold of a private constructor and refletively invoking it, there's nothing to stop them getting hold of the boolean flag and modifying that by reflection, as well.
@OP: Why are you concerned about this? I'm not saying "don't be", but is there really a risk of someone maliciously doing this? It's not something that would be done by mistake, only by someone very deliberately wanting to do so. Also, I'd be a bit concerned that you can decide at runtime which singleton to instantiate. This implies (but perhaps inaccurately) that there are alternative classes available to the runtime, all of which could potentially be instnatiated. Are they all on the classpath, or just the one configured? If they're all there, they can all be instantiated, thus breaking the singleton-ness of them. Maybe a singleton isn't appropriate here?
Why are you concerned about this? I'm not saying "don't be", but is there really a risk of someone maliciously doing this? It's not something that would be done by mistake, only by someone very deliberately wanting to do so. Also, I'd be a bit concerned that you can decide at runtime which singleton to instantiate. This implies (but perhaps inaccurately) that there are alternative classes available to the runtime, all of which could potentially be instnatiated. Are they all on the classpath, or just the one configured? If they're all there, they can all be instantiated, thus breaking the singleton-ness of them. Maybe a singleton isn't appropriate here?
>> Yes U are right!! I am working on a project that holds a lots of singleton classes that are instantiated using reflection by myself, by invoking the getIntance() method or like methods. I definitely want these classes to be singleton, but I came to know that there are possiblities of breaching the singleton policies using reflection. Or else do I have any better solutions or design patterns that I can use in this place?.
I can get your point, but my problem is not in deciding with singleton class to load in runtime, but creating a another instance of the singleton class I have!!
That's not entirely correct:
private A(String name) {
if(!instantiated){
singleton=new A("Hello");
instantiated=true;
}
}
The constructor is either invoked from getInstance() in order to create the private static instance or using reflection to instantiate another instance. There is no need for the constructor call itself. Since you're already inside a constructor, you're already in the process of creating the instance, no? So if the flag is set, the constructor can throw an exception... What we probably overlooked is that it might be too late already if we're inside the constructor. If you first get a reference to the static member by reflection and then accessing the private constructor by reflection. Isn't the static value overwritten by the time you can throw an exception?
The answer probably is that you cannot cleanly prevent anyone from creating instances using the private constructor...
Which is it? Are you invoking a private constructor or a public getInstance() method? You've said both above!
If you're using a public getInstance() method, all you have to do is add a security manager which denies java.lang.reflect.ReflectPermission "suppressAccessChecks".
If you're using this loophole yourself to get at the private constructor, you've part of the problem ;-)
ejpa at 2007-7-12 17:59:58 >

package mypackage;
class A {
private static A singleton=null;
private String name;
private boolean instantiated=false;
private A(String name) {
this.name=name;
}
public String toString(){
return name;
}
public static A getInstance(){
if(singleton==null){
return singleton=new A("Hello");
}else{
return singleton;
}
}
}
public class Test {
public static void main(String[] args) throws Exception {
Class cl = Class.forName("mypackage.A");
java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
c[0].setAccessible(true);
A anotherA = (A) c[0].newInstance(new Object[]{"Duplicate"});
A normalInstance=A.getInstance();
System.out.println("Normal Loading "+normalInstance);
System.out.println("Using reflection "+anotherA);
}
}
This is just the template of what I am using. Now how will I use the security manager to supress the reflections permissions for my class?
How much do these different implementations of your singleton have in common? What I'm getting at is, is there some common code you could extract out of them all, and make that a singleton in it's own right? Needing to do this sort of hacking is often a sign you're fudging something together, that could be solved more elegantly. We use the Singleton pattern generally when the state of the object needs to exist exactly once. Can you extract that from the disparate objects?
How much do these different implementations of your singleton have in common? What I'm getting at is, is there some common code you could extract out of them all, and make that a singleton in it's own right? Needing to do this sort of hacking is often a sign you're fudging something together, that could be solved more elegantly. We use the Singleton pattern generally when the state of the object needs to exist exactly once. Can you extract that from the disparate objects?
>> The singleton classes that I load do not have anything in common. They are all similar but unique, and independant in their own respect. I will have to decide only on what singleton object I have to load in runtime, based on certain criterion. This is done by reflection, by a call to the public getInstance() method of the respective singleton classes, since I am deciding on runtime. My problem is that can I prevent others from accessing my private constructor from outside the class using reflection, which enables them to create another duplicate object. Can I restrict them to use only my getInstance() method instead? I know this is hacking to access the private members, but I want to know whether there is any way where I can restrict this hacking?
In the above code I dont want these statements to work at any case
java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
c[0].setAccessible(true);
A anotherA = (A) c[0].newInstance(new Object[]{"Duplicate"});
Can I at this point ask, if these singletons all do completely different things, how your code is expected to make use of them?
Can I at this point ask, if these singletons all do completely different things, how your code is expected to make use of them?
>> I have an object I get in runtime which has to processed differently depending on certain checks. The code that actually does these proccessing are actually seperate classes that are singleton. They are made singleton since I have to save the state of these classes that process this object. Right!! One of the Singleton class that has to process the object has to be decided only in runtime!! This Singleton classes are also avaible through the whole project so that others can access them as well. So when they access these classes I want them to make them call only my public getInstance() method and not to hack the code by accessing the private constructors!! Got it?
I reckon you've got design problems. Specifically, what do these classes do? Why do you think they should be singletons? I mean, really. Not just "so that there's only one instance of them", why do you only want one instance of them?
>> I do a lot of work in the back ground, but I will give a quick explain!! I store the time stamp of when these objects received by these singleton class, and when another object is sent to the same singleton class it has to do manipulations based on the previous time stamps.. This one such occasion, but there are many such reasons why they are made singleton. This is the reason I dont want another duplicate object that actually will spoil the whole run!!
> >> I do a lot of work in the back ground, but I will
> give a quick explain!! I store the time stamp of
> when these objects received by these singleton
> class, and when another object is sent to the same
> singleton class it has to do manipulations based on
> the previous time stamps.. This one such occasion,
> but there are many such reasons why they are made
> singleton. This is the reason I dont want another
> duplicate object that actually will spoil the whole
> run!!
Still doesn't explain why they need to be singletons. Can't you just create an instance of the correct class, and pass it the objects?
Unless you are writing something like a code analysis tool I can almost guarantee that your design is flawed and that you should not be using reflection.
YoGeea at 2007-7-21 21:58:26 >

> Can't you just create an instance of the correct
> class, and pass it the objects?
If I do that instance creation everytime I pass a new object how will my new instace hold the time at which it previously processed a message? Wont I loose the state of the processor classes?
> > Can't you just create an instance of the correct
> > class, and pass it the objects?
>
> If I do that instance creation everytime I pass a new
> object how will my new instace hold the time at which
> it previously processed a message? Wont I loose the
> state of the processor classes?
Certainly. But who said you had to create a new instance for each pass? Simply don't do that! Just re-use the same instance, seems to me the singleton here is a waste of time, especially with all this reflective fudging. Just have a managing object that creates an instance of these classes, and works on all your messages with that same instance. Basically, the singleton pattern is used to ensure that there can only ever be one instance of a class, not to ensure that you only use one instance! It's not appropriate here
Thanks for this idea? I will check on the code whether I can make a design change with my code.One more question can I use the java.policy file to stop this hacking if I incase proceed with my existing code.Thanks for the reply...
I can't grasp the need for reflection in this particular case. Calling a getInstance() method that you wrote yourself isn't reflection, it is called a factory method. From all the above, I am led to think that you already have all classes available at compile time. Don't you just create an instance of an object using reflection with a hardcoded classname string instead of calling the getInstance() method or the construnctor?
I follow george: maybe you want 1 instance per run instead of one instance at all?
I know thats a factory pattern but I am actually invoking the getInstance() method using reflection on the Singleton class instance. My requirement is that I need to have only one processor class for the entire project lifecycle, not per run. All I am concerned is whether these singleton classes really solve the purpose they are intended on. The point I like to convey is Singleton patterns are used only when we require one instance to exist through out, Right!! But if some one can actually hack the code to create duplicate instance of Singleton class, by calling the private constructors, then when, and how can we restrict this breach on singleton patterns.
Just have a go through this article if u havent
http://radio.javaranch.com/val/2004/05/18/1084891793000.html
> I know thats a factory pattern but I am actually
> invoking the getInstance() method using reflection on
> the Singleton class instance. My requirement is that
> I need to have only one processor class for the
> entire project lifecycle, not per run. All I am
> concerned is whether these singleton classes really
> solve the purpose they are intended on. The point I
> like to convey is Singleton patterns are used only
> when we require one instance to exist through out,
> Right!! But if some one can actually hack the code to
> create duplicate instance of Singleton class, by
> calling the private constructors, then when, and how
> can we restrict this breach on singleton patterns.
>
> Just have a go through this article if u havent
>
> http://radio.javaranch.com/val/2004/05/18/108489179300
> 0.html
Who are you worried is going to hack this stuff? If you distrust your own colleagues this much, you've got bigger problems than that, and if a third party chooses to hack code to do something untoward with it, that's their own lookout. I honestly can't see what the issue here is
Who are you worried is going to hack this stuff? If you distrust your own colleagues this much, you've got bigger problems than that,
>> You didnot get my point!! I not distrusting my collegues!! I have the project that is already 5 years old, and still I intended it to run for big years. All I want to know is how will I enforce the singleton pattern atall, if there is one in the project? I know I can have my project fully documented to deal with method calls, but I wanted to know whether you guys have come across such situatiion and how U handle it? Because I am thinking of changing the code as nightmare!! I have 100s of packages and have to change all. So I thought this enforcement can become handy if there is one!! I am just in look out for a handy solution rather than a design change. I think I make sense.
> Who are you worried is going to hack this stuff? If
> you distrust your own colleagues this much, you've
> got bigger problems than that,
>
> >> You didnot get my point!! I not distrusting my
> collegues!! I have the project that is already 5
> years old, and still I intended it to run for big
> years. All I want to know is how will I enforce the
> singleton pattern atall, if there is one in the
> project? I know I can have my project fully
> documented to deal with method calls, but I wanted to
> know whether you guys have come across such
> situatiion and how U handle it? Because I am
> thinking of changing the code as nightmare!! I have
> 100s of packages and have to change all. So I thought
> this enforcement can become handy if there is one!!
> I am just in look out for a handy solution rather
> than a design change. I think I make sense.
Solution to what, though? You still haven't really explained that
It's actually becoming less clear what you want to achieve, to be honest. Why are you concerned with preventing people going to some considerable trouble to defeat your singleton? Why is this object a singleton at all? Why do you think awkward uses of reflection will aid maintenance? Why will this singleton hack allow you to change 100s of packages? You're not making sense, to be honest. No offence, but you just aren't. I can't see a single reason why you need a singleton here, and I can't see a single reason why, even if you did, you'd need to go to all this extra trouble to prevent someone hacking it. Nobody is going to bother, why would they? "I know, just for a laugh, lets use some cunning reflection to defeat the singleton-ness of this class. That'd waste a few hours, and produce hideously unexpected results" - isn't going to happen. Even if it did, you can't possibly code defensively against any malicious attack anyone might ever dream up, it simply can't be done
I think you've cottoned on to an inappropriate idea, and can't let go of it. Step back, and write down, in very simple terms, your aims with this code, and what problems you are trying to prevent.
There's nothing to stop you looking for the getInstance() static method with Class.getMethod and executing it.
> One more question can I use the java.policy file to
> stop this hacking if I incase proceed with my
> existing code.
I already answered that in reply #8.
But I agree you have a design problem. I think you need to look up the Factory and Abstract Factory patterns.
ejpa at 2007-7-21 21:58:26 >

Without wanting to be offending: If you look at writing your programs with that much paranoia, then you can actually question the very basics of every single pattern. What if I write a factory but people decide to create their objects by calling the constructor directly? What if I want to use MVC but maybe someone will one day hard code an sql request into my view?
Using a design pattern is only usefull if it is appropriate in the given circumstances and if you use it the way it is intended. There is however no way to really force people to work that way!