Limit access of a java class to some packages - java

I have a Java class which have some confidential information which I don't want to provide to any unauthorized class.
I want to access this class in some packages (classes from this packages are going to utilize confidential information), So that my secure class should be accessible in these packages.
Is there any way where I can check if caller of method is a authorized class from authorized package or not?
I know public/private/default all things (so please don't ask me to use it), but those are not useful here, because I want a class to be accessible in some packages(not one/same).

I feel that you are going in the wrong direction. It might be a design problem.
The security requirement is your business logic. You should implement your security policy somehow, not rely on the java language level visibility modifier or caller package names. since if you give your jar to someone, he can anyway get access to your "confidencial" class.
And moreover, a class is a type, something abstract. it should not contain "data". well sure sometimes conf information was written as static variable etc. However if some data is sensitive, it should not be written in class. It could be stored in database or encrypted file and so on. Once a request to the sensitive information comes, you check your implemented security policy, if it is allowed to access those data.
just my 2cents

The visibility modifiers in Java are not a security tool, but an OO design tool. Whatever you might do, if someone uses your class, it can access any private members of any class using reflection.
If your objects contain confidential information, leave these objects in your secure server.

You can create an Exception (no need for it to be thrown) and use the getStackTrace() to analize the call stack. I always found it ugly, though.
That said, anything that you put in a client machine is vulnerable to that machine; if you have something really confidential protect it in your server; make it available only as a service.

You can use the proxy pattern, implemented by the Proxy class in Java - it is designed exactly for your purpose.
Here is a how-to.
EDIT : AFAIK, you cannot use the regular Proxy mechanism for static methods, as the proxy and the proxied class must implement a common interface. However, there are more advanced tools, which may help you like javassist. Unfortunately I'm not familiar with it myself.

You might be able to leverage aspectj here. It's theoretically possible to intercept the call to a given classes' methods based on the current flow scope, and have the aspect throw an exception or something. I'm no aspectj expert though, but the "cflow" pointcut qualifier would be your most likely bet. Maybe something like this
! cflow(call(* com.mycom.AllowedClient.*))
I haven't tested this kind of pointcut, but i believe it would work.
You'd probably want compile time weaving in this case though (as opposed to load time weaving).
As a side note, i agree with some of the others that i think this is the wrong approach to take. You protect data. You protected function access based on logged in user permissions. You typically don't protect function calls from other classes.

Guideline 4-2 / EXTEND-2: Limit the accessibility of packages
Containers may hide implementation code by adding to the package.access security property. This property prevents untrusted classes from other class loaders linking and using reflection on the specified package hierarchy. Care must be taken to ensure that packages cannot be accessed by untrusted contexts before this property has been set.
This example code demonstrates how to append to the package.access security property. Note that it is not thread-safe. This code should generally only appear once in a system.
private static final String PACKAGE_ACCESS_KEY = "package.access";
static {
String packageAccess = Security.getProperty(PACKAGE_ACCESS_KEY);
Security.setProperty(PACKAGE_ACCESS_KEY,
(packageAccess == null || packageAccess.trim().isEmpty()
? "" : packageAccess + ",")
+ "xx.example.product.implementation.");
}

Related

How to create layers in an Android library without exposing internal classes to consumer of the library

I'm creating an android library and wanted to organize with layers it something like this.
PublicClassExposedToLibraryConsumer.java
logic.PublicFooLogicInterface1.java
logic.PackagePrivateFooLogicClass1.java
logic.PublicFooLogicInterface2.java
logic.PackagePrivateFooLogicClass2.java
domain.PublicFooDomainInterface1.java
domain.PackagePrivateFooDomainClass1.java
domain.PublicFooDomainInterface2.java
domain.PackagePrivateFooDomainClass2.java
repository.PublicFooRepoInterface1.java
repository.PackagePrivateFooRepoClass1.java
repository.PublicFooRepoInterface2.java
repository.PackagePrivateFooRepoClass2.java
1) I want a number of layers and I want to limit interaction between those layers by using interfaces.
2) I want to only expose PublicClassExposedToLibraryConsumer.java to the consumer of the library. They should not be able to access the other classes and interfaces.
Is this possible? From what I've read in order to make something accessible to something consuming the library it needs to be public and to hide something from the consumer of the library it needs to be not public. By my reading this means that you can't separate layers without exposing something and you can't hide internal classes without being forced to use a completely flat architecture. I find this very hard to believe, I have to be missing something.
You can try with annotations providing specific scope for your desired file to restrict to end-user of your library. Best way to do this in Android is using #RestrictTo support library annotation on class level.
Note : For Fields and Methods of particular entity can be scoped with access-modifiers like private, protected or package-protected etc. *(Just ignore if you already know that)
#RestrictTo : Denotes that the annotated element should only
be accessed from within a specific scope (as defined by
RestrictTo.Scope).

Unit Testable convention for Service "Helper Classes" in DDD pattern

I'm fairly new to Java and joining a project that leverages the DDD pattern (supposedly). I come from a strong python background and am fairly anal about unit test driven design. That said, one of the challenges of moving to Java is the testability of Service layers.
Our REST-like project stack is laid out as follows:
ServiceHandlers which handles request/response, etc and calls specific implementations of IService (eg. DocumentService)
DocumentService - handles auditing, permission checking, etc with methods such as makeOwner(session, user, doc)
Currently, something like DocumentService has repository dependencies injected via guice. In a public method like DocumentService.makeOwner, we want to ensure the session user is an admin as well as check if the target user is already an owner (leveraging the injected repositories). This results in some dupe code - one for both users involved to resolve the user and ensure membership, permissions, etc etc. To eliminate this redundant code, I want make a sort of super simpleisOwner(user, doc) call that I can concisely mock out for various test scenarios (such as throwing the exception when the user can't be resolved, etc). Here is where my googling fails me.
If I put this in the same class as DocumentService, I can't mock it while testing makeOwner in the same class (due to Mockito limitations) even though it somewhat feels like it should go here (option1).
If I put it in a lower class like DocumentHelpers, it feels slightly funny but I can easily mock it out. Also, DocumentHelpers needs the injected repository as well, which is fine with guice. (option 2)
I should add that there are numerous spots of this nature in our infant code base that are untestable currently because methods are non-statically calling helper-like methods in the same *Service class not used by the upper ServiceHandler class. However, at this stage, I can't tell if this is poor design or just fine.
So I ask more experienced Java developers:
Does introducing "Service Helpers" seem like a valid solution?
Is this counter to DDD principals?
If not, is there are more DDD-friendly naming convention for this aside from "Helpers"?
3 bits to add:
My googling has mostly come up with debates over "helpers" as static utility methods for stateless operations like date formatting, which doesn't fit my issue.
I don't want to use PowerMock since it breaks code coverage and is pretty ugly to use.
In python I'd probably call the "Service Helper" layer described above as internal_api, but that seems to have a different meaning in Java, especially since I need the classes to be public to unit test them.
Any guidance is appreciated.
That the user who initiates the action must be an admin looks like an application-level access control concern. DDD doesn't have much of an opinion about how you should do that. For testability and separation of concerns purposes, it might be a better idea to have some kind of separate non-static class than a method in the same service or a static helper though.
Checking that the future owner is already an owner (if I understand correctly) might be a different animal. It could be an invariant in your domain. If so, the preferred way is to rely on an Aggregate to enforce that rule. However, it's not clear from your description whether Document is an aggregate and if it or another aggregate contains the data needed to tell if a user is owner.
Alternatively, you could verify the rule at the Application layer level but it means that your domain model could go inconsistent if the state change is triggered by something else than that Application layer.
As I learn more about DDD, my question doesn't seem to be all that DDD related and more just about general hierarchy of the code structure and interactions of the layers. We ended up going with a separate DocumentServiceHelpers class that could be mocked out. This contains methods like isOwner that we can mock to return true or false as needed to test our DocumentService handling more easily. Thanks to everyone for playing along.

When do we use denyAll in spring security

I am a bit confused as to why someone would use #PreAuthorize("denyAll") for a method. As per the spring security documentation, it always evaluates to false.
If we are not going to allow access to a particular method, what is the point of keeping such a method. Why not comment it out? Or is it that it can still be accessed from within the same class?
I am trying to understand under what scenario such a requirement would arise.
One small clarification that I found in general for deny all was
#DenyAll annotation can be used to restrict business interface access from anyone, logged in or not. The method is still invokable from within the bean class itself.
So the jist is it can be used for a method which is public for some reason or have been exposed (perhaps it implements an interface) but should never be called directly from outside. However they can be called from inside(within the class).
here is the link
One real example that I can give you is (which is quite related with my work). We have 2 business unit with same code base. Now in one unit there is a feature where some mobile reseller can directly call a service which cancels the voucher directly to the operator end but in the other unit we needed to block this due to some business rule. Since we use the same interface in both system so in one system we blocked its usage using denyall
Hope this gives you a clear idea.
I decorate my service classes in this way which requires the individual inner service methods to override the denying class level PreAuth annotation. This ensures that each method in the class will be appropriately secured w/a fallback to denyAll.
I know this is old but I stumbled on it looking for the syntax for #PreAuthorize('denyAll') and thought I'd throw my 2cents in.

How to secure application Java code from user code?

In our app, application loads user module using custom class loader. What would be the best way to protect wild behavior of the user module? We want to prevent:
user code to modify any application code. We have some singletons, and user may access it using e.g. reflection to get some instances and change e.g. some critical configuration; or replace some guard code. Since the classloader is written by me, so I can prevent loading any class that is critical.
user code should access only some folders; if possible. So it behave like unix user :)
The first step is to set a SecurityManager. This is because the Java class library contains global state. You will also need to ensure your code does not use its privileges to expose itself through this state. In addition some global state is not security checked, for instance through "AppContext" and the current thread.
Usually the package.access security property is used to hide internal code within a parent class loader context. This isn't a bad idea if the potentially malicious code is loaded through a non-child class loader.
Note, if you pass an instance of your hidden code, malicious code can use Object.getClass, Class.getMethods, etc., to explore the public interface. Class.getClassLoader is checked, but make sure there aren't other outlets, such as through the thread context class loader (though Thread.getContextClassLoader strangely has a security check, its use is to publish the class loader).

The missing "framework level" access modifier

Here's the scenario. As a creator of publicly licensed, open source APIs, my group has created a Java-based web user interface framework (so what else is new?). To keep things nice and organized as one should in Java, we have used packages with naming convention
org.mygroup.myframework.x, with the x being things like components, validators, converters, utilities, and so on (again, what else is new?).
Now, somewhere in class org.mygroup.myframework.foo.Bar is a method void doStuff() that I need to perform logic specific to my framework, and I need to be able to call it from a few other places in my framework, for example org.mygroup.myframework.far.Boo. Given that Boo is neither a subclass of Bar nor in the exact same package, the method doStuff() must be declared public to be callable by Boo.
However, my framework exists as a tool to allow other developers to create simpler more elegant R.I.A.s for their clients. But if com.yourcompany.yourapplication.YourComponent calls doStuff(), it could have unexpected and undesirable consequences. I would
prefer that this never be allowed to happen. Note that Bar contains other methods that are genuinely public.
In an ivory tower world, we would re-write the Java language and insert a tokenized analogue to default access, that would allow any class in a package structure of our choice to access my method, maybe looking similar to:
[org.mygroup.myframework.*] void doStuff() { .... }
where the wildcard would mean any class whose package begins with org.mygroup.myframework can call, but no one else.
Given that this world does not exist, what other good options might we have?
Note that this is motivated by a real-life scenario; names have been changed to protect the guilty. There exists a real framework where peppered throughout its Javadoc one will find public methods commented as "THIS METHOD IS INTERNAL TO MYFRAMEWORK AND NOT
PART OF ITS PUBLIC API. DO NOT CALL!!!!!!" A little research shows these methods are called from elsewhere within the framework.
In truth, I am a developer using the framework in question. Although our application is deployed and is a success, my team experienced so many challenges that we want to convince our bosses to never use this framework again. We want to do this in a well thought out presentation of the poor design decisions made by the framework's developers, and not just as a rant. This issue would be one (of several) of our points, but we just can't put a finger on how we might have done it differently. There has already been some lively discussion here at my workplace, so I wondered what the rest of the world would think.
Update: No offense to the two answerers so far, but I think you've missed the mark, or I didn't express it well. Either way allow me to try to illuminate things. Put as simply as I can, how should the framework's developers have refactored the following. Note this is a really rough example.
package org.mygroup.myframework.foo;
public class Bar {
/** Adds a Bar component to application UI */
public boolean addComponentHTML() {
// Code that adds the HTML for a Bar component to a UI screen
// returns true if successful
// I need users of my framework to be able to call this method, so
// they can actually add a Bar component to their application's UI
}
/** Not really public, do not call */
public void doStuff() {
// Code that performs internal logic to my framework
// If other users call it, Really Bad Things could happen!
// But I need it to be public so org.mygroup.myframework.far.Boo can call
}
}
Another update: So I just learned that C# has the "internal" access modifier. So perhaps a better way to have phrased this question might have been, "How to simulate/ emulate internal access in Java?" Nevertheless, I am not in search of new answers. Our boss ultimately agreed with the concerns mentioned above
You get closest to the answer when you mention the documentation problem. The real issue isn't that you can't "protect" your internal methods; rather, it is that the internal methods pollute your documentation and introduce the risk that a client module may call an internal method by mistake.
Of course, even if you did have fine grained permissions, you still aren't going to be able to prevent a client module from calling internal methods---the jvm doesn't protect against reflection based calls to private methods anyway.
The approach I use is to define an interface for each problematic class, and have the class implement it. The interface can be documented solely in terms of client modules, while the implementing class can provide what internal documentation you desire. You don't even have to include the implementation javadoc in your distribution bundle if you don't want to, but either way the boundary is clearly demarcated.
As long as you ensure that at runtime only one implementation is loaded per documentation-interface, a modern jvm will guarantee you don't suffer any performance penalty for using it; and, you can load harness/stub versions during testing for an added bonus.
The only idea that I can think in order to supply this missing "Framework level access modifier" is CDI and a better design.
If you have to use a method from very different classes and packages in various (but few) situations THERE WILL BE certainly a way to redesign those classes in order to make those methods "private" and inacessible.
There is no support in Java language for such kind of access level (you would like something like "internal" with namespace). You can only restrict access to package level (or the known inheritance public-protected-private model).
From my experience, you can use Eclipse convention:
create a package called "internal" that all class hierarchy (including sub-packages) of this package will be considered as non-API code and could be changed anytime with no guarantee for your users. In that non-API code, use public methods whenever you like. Since it is only a convention and it is not enforced by the JVM or Java compiler, you cannot prevent users from using the code, but at least let them know that these classes were not meant to be used by 3rd parties.
By the way, in Eclipse platform source code, there is a complex plugin model that enforces you not to use internal code of other plugins by implementing custom class loader for each plugin that prevents loading classes that should be "internal" in these plugins.
Interfaces and dynamic proxies are sometimes used to make sure you only expose methods that you do want to expose.
However that comes at a fairly hefty performance cost, if your methods are called very often.
Using the #Deprecated annotation might also be an option, although it won't stop external users invoking your "framework private" methods, they can't say they hadn't been warned.
In general I don't think you should worry about your users deliberately shooting themselves in the foot too much, so long as you made it clear to them that they shouldn't use something.

Categories