How to add dynamic authorization to JAX-RS service? - authorization

I am trying to secure REST services by adding authorisation. For example, all customers are allowed to call /rest/{custno}/machines/{machno} but they are only allowed to see the machines which they own.
I see that there are annotations like #RolesAllowed but that doesn't help in this case.
I have tried using Interceptors and this seemed to work on Websphere8.5 but is not working on Tomcat 7 or 8. The interceptor was able to get the customer info from the session and from the path and ensure that they are the same or that the user has admin rights. It was quite nice to be able to generate an overview using the annotations to see how each service is secured.
What is a typical approach to this kind of problem?

You should use abac/xacml which will provide you with
An architecture
A policy language (XACML or alfa)
A request/response protocol to query for authorization.
Let's start with the policy.
For example, all customers are allowed to call /rest/{custno}/machines/{machno} but they are only allowed to see the machines which they own.
In pseudo-policy, using ALFA, this would become
/**
* Control access to machines
*/
policyset machines{
target clause objectType == "machine"
apply firstApplicable
/**
* View machines
*/
policy viewMachines{
target clause actionId == "view"
apply firstApplicable
/**
* Users are only allowed to see the machines which they own.
*/
rule usersCanViewTheirOwnMachines{
permit
condition machine.owner == username
}
}
}
The nice thing with this approach is that you need not write any code for this. All of the authorization logic is done inside the policy.
Now, let's talk architecture. You will need:
an interceptor or policy enforcement point (PEP) which in your case would be a JAX-RS filter or interceptor. The interceptor will call out to the authorization service to verify the policies.
an authorization service also known as a Policy Decision Point (PDP) which will process the request you sent against the policies it knows such as the one you just wrote.
Additional reading
ALFA on Wikipedia
XACML Architecture
XACML on Wikipedia

Related

How to check token for already defined policy?

This is how I handle authorization with policies for controller:
At "Startup.cs", in "ConfigureServices" method I add following code:
services.AddAuthorization(options =>
{
options.AddPolicy("can_work", policy => policy
.RequireClaim("my_app", "user", "admin")
);
});
And then all it takes is to decorate given controller or specific method with attribute:
[Authorize(Policy = "can_work")]
As the effect only users with matching policy are granted the usage of controller/method.
Now, I have situation when I cannot rely on just attributes -- I have user token at hand and I have to decide whether to grant access or not. I could manually replicate the above policies rules, but it means I would repeat myself in two places. So I would like to somehow retrieve those policies I set already and check for which the token matches. How to do it?
Maybe I rephrase -- I know I can manually iterate over token claims:
foreach (var claim in token.Claims)
// manually check the value and type, and basically repeat policy again
this would be (a) repeating (b) prone to errors when something change. Instead I would like to have single call
policy_service.GetPoliciesForToken(token);
which will hit the authorization service I defined with policies (see top of the question). And currently I don't know how to write such line.
Background I describe what I need this is for, because maybe there is even simpler way -- SignalR broadcasting. When client calls SignalR method I could use attribute as well, but when the service initiates flow, say every 1 second it sends to all its clients a tick, then I would like to know to which client I can send it. So my idea would be to check user tokens when connecting to SignalR hub, retrieve matching policies (this part I don't know how to do it reusing already set policy options), and then when broadcasting anything simply filter out the clients based on cached info.
For the time being for security concerns it is sufficient for me.
Following King King tips, to some degree now I have one definition and shared check.
I changed how policies are built. I build them manually and keep their instances also for my purposes (see later):
AuthorizationPolicy work_policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireClaim("my_app", "user", "admin")
.Build();
then having policy instances I call services.AddAuthorization(options... which works as before for controllers.
As for SignalR hub I request in constructor IAuthorizationService, and when user connects thanks to attribute Authorize I have this.Context.User provided on one hand, and I have my policies instances, thus I can make such call:
AuthorizationResult auth_result = await authService.AuthorizeAsync(this.Context.User, work_policy);
to check if given user matches or not given policy.

Multi-tenancy in Golang

I'm currently writing a service in Go where I need to deal with multiple tenants. I have settled on using the one database, shared-tables approach using a 'tenant_id' decriminator for tenant separation.
The service is structured like this:
gRPC server -> gRPC Handlers -
\_ Managers (SQL)
/
HTTP/JSON server -> Handlers -
Two servers, one gRPC (administration) and one HTTP/JSON (public API), each running in their own go-routine and with their own respective handlers that can make use of the functionality of the different managers. The managers (lets call one 'inventory-manager'), all lives in different root-level packages. These are as far as I understand it my domain entities.
In this regard I have some questions:
I cannot find any ORM for Go that supports multiple tenants out there. Is writing my own on top of perhaps the sqlx package a valid option?
Other services in the future will require multi-tenant support too, so I guess I would have to create some library/package anyway.
Today, I resolve the tenants by using a ResolveTenantBySubdomain middleware for the public API server. I then place the resolved tenant id in a context value that is sent with the call to the manager. Inside the different methods in the manager, I get the tenant id from the context value. This is then used with every SQL query/exec calls or returns a error if missing or invalid tenant id. Should I even use context for this purpose?
Resolving the tenant on the gRPC server, I believe I have to use the UnaryInterceptor function for middleware handling. Since the gRPC
API interface will only be accessed by other backend services, i guess resolving by subdomain is unneccessary here. But how should I embed the tenant id? In the header?
Really hope I'm asking the right questions.
Regards, Karl.
I cannot find any ORM for Go that supports multiple tenants out there. Is writing my own on top of perhaps the sqlx package a valid option?
ORMs in Go are a controversial topic! Some Go users love them, others hate them and prefer to write SQL manually. This is a matter of personal preference. Asking for specific library recommendations is off-topic here, and in any event, I don't know of any multi-tenant ORM libraries – but there's nothing to prevent you using a wrapper of sqlx (I work daily on a system which does exactly this).
Other services in the future will require multi-tenant support too, so I guess I would have to create some library/package anyway.
It would make sense to abstract this behavior from those internal services in a way which suits your programming and interface schemas, but there's no further details here to answer more concretely.
Today, I resolve the tenants by using a ResolveTenantBySubdomain middleware for the public API server. I then place the resolved tenant id in a context value that is sent with the call to the manager. Inside the different methods in the manager, I get the tenant id from the context value. This is then used with every SQL query/exec calls or returns a error if missing or invalid tenant id. Should I even use context for this purpose?
context.Context is mostly about cancellation, not request propagation. While your use is acceptable according to the documentation for the WithValue function, it's widely considered a bad code smell to use the context package as currently implemented to pass values. Rather than use implicit behavior, which lacks type safety and many other properties, why not be explicit in the function signature of your downstream data layers by passing the tenant ID to the relevant function calls?
Resolving the tenant on the gRPC server, I believe I have to use the UnaryInterceptor function for middleware handling. Since the gRPC API interface will only be accessed by other backend services, i guess resolving by subdomain is unneccessary here. But how should I embed the tenant id? In the header? [sic]
The gRPC library is not opinionated about your design choice. You can use a header value (to pass the tenant ID as an "ambient" parameter to the request) or explicitly add a tenant ID parameter to each remote method invocation which requires it.
Note that passing a tenant ID between your services in this way creates external trust between them – if service A makes a request of service B and annotates it with a tenant ID, you assume service A has performed the necessary access control checks to verify a user of that tenant is indeed making the request. There is nothing in this simple model to prevent a rogue service C asking service B for information about some arbitrary tenant ID. An alternative implementation would implement a more complex trust-nobody policy whereby each service is provided with sufficient access control information to make its own policy decision as to whether a particular request scoped to a particular tenant should be fulfilled.

Where to double-check attributes of the XACML-request against Attribute-Providers at the PDP?

I'm evaluation PDP engines and at the moment I give AuthzForce Core a try. Evaluating a Request by the PDP runs pretty solid so far:
//My request and pdp configuration files
File confLocation = new File("D:/docs/XACML/AuthZForce/IIA001/pdp.xml");//pdp.xml tells the pdp where the policies xml files are
File requestFile = new File("D:/docs/XACML/AuthZForce/IIA001/Request.xml");
//I instantiate the pdp engine and the xacml parser
final PdpEngineConfiguration pdpEngineConf = PdpEngineConfiguration.getInstance(confLocation, null, null);
PdpEngineInoutAdapter<Request, Response> pdp = PdpEngineAdapters.newXacmlJaxbInoutAdapter(pdpEngineConf);
XmlUtils.XmlnsFilteringParser xacmlParserFactory = XacmlJaxbParsingUtils.getXacmlParserFactory(false).getInstance();
//I parse the request file
Object request = xacmlParserFactory.parse(requestFile.toURI().toURL());
if (request instanceof Request) {
//At this point I could access all request attributes or alter them
//I let the PDP evaluate the request
Response response = pdp.evaluate((Request) request);
//I check the results inside the response
for (Result result : response.getResults()) {
if (result.getDecision() == DecisionType.PERMIT) {
//it's permitted!
} else {
//denied!
}
}
}
Now, according to the literature like [1] I should not trust the attributes in the given request-xacml-file. Whenever possible, I have to check against a Attribute Provider (e.g. a Patient database) if the given attributes (e.g. patient birthdate) actually belong to the patient in order to prevent attacks.
Otherwise the attacker could make the patient younger in the Request in order to access the patient's record as a parent guardian.
Questions
Is checking Requests against Attribute Providers the task of a PDP or of another entitiy?
Did OASIS specify anything concrete about that issue? E.g. workflow or syntax of configuration files
Is there a way to make my pdp engine aware of Attribute Providers?
Should I just check the provided request on my own before Response response = pdp.evaluate((Request) request);?
I don't know for other XACML implementations, but regarding AuthzForce, Attribute Providers play the role of PIPs in official XACML terms (see the definition of PIP in XACML spec's Glossary), i.e. responsible for getting any additional attribute that is not in the XACML request context (it usually means they are not provided by the PEP originally), whenever the PDP needs it to evaluate the policy. This relates to steps 5-8 of XACML standard data-flow model (§3.1 of XACML 3.0 spec). Besides, if you read the XACML spec carefully, you notice that the actual entity calling the PIPs for the PDP is the so-called context handler. In practice, this is a matter of implementation, the context handler can take many forms. In AuthzForce, it is just a sub-component of the PDP, but you might have one on the PEP side as well which is application-specific, especially in a typical ABAC/XACML scenario where the PDP is a remote service from the PEP's perspective, and the PDP is possibly talking to many PEPs in completely different application environments.
As mentioned previously, for the workflow, look at section 3.1 Data-flow model in the XACML core spec. For the syntax, XACML core specification defines a syntax for policies, authorization decision requests and responses, nothing else at this point. You may find other things in XACML Profiles, but no such thing as configuration syntax, to my knowledge.
In AuthzForce, the PDP engine is made aware of Attribute Providers by the PDP configuration, i.e. the pdp.xml file in your example. You'll need two other files (XML catalog and schema) depending on the Attribute Provider you want to use. This is documented in the Using Attribute Providers section of AuthzForce Core's wiki.
Your code seems like test code to me since you are getting the xacml request from a local file so it seems you have full control over it, so no need to check further. More generally, it depends on the actual use case, really, no universal rule for that. Some attributes (like a subject-id resulting from authentication) are specific and only known by the PEP in its own app environment, so they are the responsibility of the PEP. Some other attributes are more likely the responsibility of the PDP (through attribute providers) if they can be resolved in a central way, such as attributes in a company's directory or other kind of identity repository.
In addition to #cdan's excellent response, here are a few more pointers:
Is checking Requests against Attribute Providers the task of a PDP or of another entitiy?
The PDP always trusts the information (attributes) it receives whether it be from the PEP or from the PIPs. As such the PDP need not verify values it received from a PEP by checking with a PIP. That's counter-productive an inefficient. If you cannot trust the PEP to send the right value, how can you trust it to enforce the right decision?
Did OASIS specify anything concrete about that issue? E.g. workflow or syntax of configuration files
No, we did not. PIP behavior is outside the scope of the XACML spec.
Is there a way to make my pdp engine aware of Attribute Providers?
Should I just check the provided request on my own before Response response = pdp.evaluate((Request) request);?
The PDP should be configured with PIPs. The PDP will use all the PIPs it can.

When using ABAC security, how do you look up rules?

When implementing ABAC/XACML, the spec indicates you should intercept requests for sensitive data with PEPs, which route the request to PDPs (the PEPs include attributes about the subject, environment, resource and action when calling the PDP).
The PDP then determines what rules need to be evaluated for an access decision.
From Wikipedia:
https://en.wikipedia.org/wiki/XACML
XACML provides a target,[5] which is basically a set of simplified conditions for the subject, resource, and action that must be met for a policy set, policy, or rule to apply to a given request. Once a policy or policy set is found to apply to a given request, its rules are evaluated to determine the access decision and response.
Policy set, policy and rule can all contain target elements.
It's my understanding that how the PDP decides what rules in the PIP are applicable is implementation specific, but this seems like a very important part of the process-- if you miss a rule, for instance, you would not evaluate the request properly. What ways have folks implemented this? What's worked and what hasn't? (I'm reluctantly leaning towards lookups against an EAV-ish table.)
You always configure a PDP with a set of policies. You can give the PDP any number of policies and policy sets (groups of policies) but you must specify the entry point, i.e. there must be a root policy. That root policy may then contain and / or link to other policies (or policy sets).
The PDP alone decides which policies to invoke and evaluate based on the incoming request from the PEP. The PEP does not know how many policies there are. You would not miss a rule like you state in your question. It is the PDP's responsibility not to. You would not typically implement your own PDP. You would use an off-the-shelf one. There are several open-source engines e.g. SunXACML and commercial alternatives e.g. Axiomatics.
The PIP is used for attribute value retrieval, not for policy retrieval.

Selectively apply authorization policy to operations

I have a WCF service with multiple operations exposed as a RESTful API. Most operations on the service do not require authentication/authorization, but one or two do. The authorization policy I need to use is outside of my control, and is expensive to run. Therefore, I'd like to avoid using it on those operations that do not require it.
It appears that authorization policies defined in configuration must apply to the entire service - there is no way to apply them to selective operations. This means I need to come up with another mechanism to selectively apply the authorization policy to specific operations.
Operation behaviors don't help because the ServiceSecurityContext.AuthorizationPolicies collection is read-only.
Splitting my service into two contracts - authorized and unauthorized - is messy, and won't help anyway. In order to configure separate behaviors, I will need separate services (not just separate contracts implemented by the one service), so that each has a distinct name for the purposes of configuration. Separate services implies separate .svc files to point to those services, so all my RESTful URLs will change unless I have some crazy URI rewriting scheme. That seems way more work than should be required to make this happen.
I'm starting to think the only reasonable way to do this would be to write my own authorization policy that wraps the expensive one, and only call it for select operations. Of course, I'd need some way of identifying those operations, but I'll cross that bridge when I come to it.
How can I selectively apply an authorization policy to service operations? Is there an easier way?
Since no one has replied, I'm going to say there is no way to do this so I can mark as accepted. I ended up doing exactly what I said - writing a wrapper authorization policy that selectively calls the expensive authorization policy based on some configuration.