How to get session context in wamp router validator - twisted

According to comment and a criticism for question being too broad; I'll try to make it more specific;
Environment - Server: autobahn|python with twisted, wampv2
Given that:
a) I have a class which extends RouterSession and authenticates user, and at the moment of authentification knows who the user accessing the wamp service is;
and
b) I have a class which extends ApplicationSession and on creation exposes several rpc methods through wamp
How do I access the user data in the exposed RPC method. By the user data - I mean - which I verified at the beginning of a specific client connection through RouterSession.
Because ApplicationSessions are initiated only once, and don't have a clue about caller (from what I have seen in debugger).
The reason I would need this - is to execute the rpc call with the context of a calling user. Where method's result might depend on specific user profile properties.
I am probably looking for something which could represent per-connection created Application instances (which could then hold reference to authorization result and data). Like most of the server Protocols operate in twisted.
-----------------ORIGINAL POST-----------
Brief question: imagine a scenario where user rights are based not on method but object; Example - I may have right to edit my profile account and profile accounts of my subordinates but not any other. This leaves to a situation where I would expose "com.myorg.profile.update_profile_details" RPC through WAMP to everyone, but would have to check which user is trying to modify which profile.
I see there is a validate mechanism in WAMP Router to deal with validating request - but it seems, that it lacks a reference to previous authentication result or session.
I really would like to avoid passing session keys (or, god forbid auth tokens) back and forth through the WAMP; whats the suggested approach for this?
----------------END OF ORIGINAL POST----------

After debugging traces back and forth, I found a solution which fits me - the trick is to pass additional options parameter when registering RPC methods:
self.register(self.test_me_now, 'com.ossnet.testme', options = RegisterOptions(details_arg = 'details', discloseCaller = True))
and voila - there is a new incoming parameter into registered RPC method: 'details'
with following contents:
CallDetails: CallDetails(progress = None, caller = 774234234575675677138, authid = johan.gram, authrole = user, authmethod = ticket)

Related

Spring Security - Secure Remote Password protocol - SRP - Authentication Provider

When asking this question I am looking for guidance with implementation of my own AuthenticationProvider. By that i mean the following:
Till now i have learned that Spring Security ask the AuthenticationProvider object if the user is authenticated or not. Currently i am using the
DaoAuthenticationProvider wich process the username and the password that is beeing returned by my own custome UserDetailService. All works great!
Spring support a lot of different AuthenticationProvider's for example there is one for LDAP, Jdbc, DAO (as mentioned above) and i was even able to find one for Kerberos. However there is no authentication provider for SRP, thus the need to write one.
My question is here the following:
When we use the DaoAuthenticationProvider i.e. user/password authentication, we have a html form where the username and password are entered and then a button is responsible for submiting those 2 parameters. Bought barameteres are transfered over some transport channel to the server i.e. with one click we are able to send all of the data within the same http reqest i.e. all that is needed for the authentication. That can be seen in the UsernamePasswordAuthenticationFilter. Here the method "attemptAuthentication" takes "HttpServletRequest request" which includes username and password. Till now all good.
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
...
}
Well, in the simple in SRP we have also a form that has a username and password, except the password !!!MUST!!! not be transfered over the network. In order to achieve that constrain a "discussion" between the client and the server has to take place i.e. the following parameters must be exchanged.
1) username (I),
2) a value called "A"
3) a value called "B"
4) a value called "M1"
5) a value called "M2"
Well, let us assume that there is a filter called "SrpAuthenticationProcessingFilter" how should the filter look like if the new authentication protocol was more like a conversation by that i mean from the RFC 5054.
Client Server
Client Hello (I) -------->
Server Hello
Certificate*
Server Key Exchange (N, g, s, B)
<-------- Server Hello Done
Client Key Exchange (A) -------->
[Change cipher spec]
Finished -------->
[Change cipher spec]
<-------- Finished
Application Data <-------> Application Data
Here we have a client that needs to
a) send first his username (I)
b) then the server needs to respond with a value B. (N,g,s are not really necessary in this case)
c) the client sends it's "value A"
d) the the client uses that value B from the server and based on that value calculates a key.
e) the server calculates the key as well based on the value A.
f) the client sends value M1 to the server.
g) the server gets the M1 value and based on a formula which has the M1 value as argument, he is able to verify if the keys
match, if the calculated keys of the bought sides match then the
user is authenticated, and the product i.e. the shared key could
be used further for other processing.
In a contrast to username and password authentication those are 7 steps not one. And 3 of those needs to happen before the SrpAuthenticationProcessingFilter. Now i am aware that there is a possibility to send the username together with the "value A" thus shortening the number of steps, but i would like to strictly follow the RFC. Never take the easy way right?
The question really is where do i place that code which is responcible for the ping pong (conversation) between the client and the server i.e. the first 3 steps a,b and c mentioned above. Should it place them in a SrpEntryPoint object, or somewhere else. if else then were in the context of SpringSecurity?
One way i can thing of solving this is using websockets, but i would also like to make that authentication independent from any layer 5-7 protocol such as websockets, http, spdy etc. . That means that the first implementation should be be trough simple http request/responce and then with any other protocol.
So the structure that could be the right one in order to implement SRP currently is:
SRPAuthenticationEntryPoint implements org.springframework.security.web.AuthenticationEntryPoint - this basically says what should be done if a request for a protected resource gets in, but the user is not authenticated yet. Here we can place a redirect in the case the resource has not been authenticated. Maybe this is also the place which is responsible for the steps a,b,c not sure if that is the right place. Request guidance and information!!
SrpAuthenticationProcessingFilter extends GenericFilterBean. SrpAuthenticationProcessingFilter exists to make partial validation for example to check if the srp paramters received a correct and corrspoding to the srp parameters that the server sets. Here it is important to mention that SrpAuthenticationProcessingFilter is not doing any username validation i.e. that needs to happen in one step before the SrpAuthenticationProcessingFilter is beeing called, maybe that is the SrpEntryPoint or some other step that i do not know how to call it yet. SrpAuthenticationProcessingFilter has a method "doFilter" in which the second structure is beeing created i.e. SrpAuthenticationToken.
SrpAuthenticationToken extend org.springframework.security.authentication.AbstractAuthenticationToken. That token in my understanding is something similar ot the DAO object, the token maps all field needed for sucessefull authentication. When partially validated parameters are populated into the SrpAuthenticationToken that SrpAuthenticationToken is passed to the authenticat method of the org.springframework.security.authentication.AuthenticationManager interface i.e. something like that
myAuthentication = authenticationManager.authenticate(SrpAuthenticationToken);
depending on which Authentication Provider is configured in the Spring Security config then the SrpAuthentication provider is called in our case i.e.:
#Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(sRPAuthenticationProvider);
}
SRPAuthenticationProvider - implements org.springframework.security.authentication.AuthenticationProvider. Over here the steps d,e,f and g are being validated and compared. If something wrong happens then throw new BadCredentialsException("Invalid username/password/Verifiere") exception.
SrpSessionValidator - this one is responsible only for validating particular parameters of the Srp session and would be called from SrpAuthenticationProcessingFilter as well as in one step before the SrpAuthenticationProcessingFilter in order to validate if the username exists in the database at all.
I only have a general idea how to implement that Srp authentication, and thus i would like some comments if that makes sense at all and if SRPAuthenticationEntryPoint is the right place for the steps a,b and c. It does not feel like the right place to me.
Any feedback is greatly appreciated.
regards,
Tito
Addition1 (21 November 2014) -> As an aswer to the question "where to place that code which is responsible for the ping pong (conversation) between the client and the server i.e. the first 3 steps a,b and c " the answer to that would be most likely a standard (i will call it negotiation) filter which will take that job.
Now I would like to rephrase the question i.e. before the authentication is complete and before the M1 and M2 messages are received i.e. steps 1 2 and 3. Where do i place that object? I.e. it should be a place where the object should live for example for 60 seconds and then be automatically deleted in case no M1 and M2 messages has been received. I mean some object before the "SecurityContextHolder" object. I just do not know what is the name of that object/context related to spring security, also i do not know if such construct exists at all?
My approach would be to use AJAX to run the first parts of the protocol up to the creation of A and M1 at the client then post those to the server as the login credentials and check those using Spring Security.
To see how this works there is a junit-js test which runs mutual authentication between a javascript client object and a java server object using Thinbus over at TestSRP6JavascriptClientSessionSHA256.js (note the maven build runs this unit test using the JDK javascript runtime):
// note the following exchange is written in javascript calling client js and invoking server java which is run by JUnit-JS using the JDK javascript runtime so it shows both sides of the full authentication in one unit test method
// normal login flow step1a client: browser starts with username and password given by user at the browser
client.step1(username,password);
// normal login flow step1b server: server starts with username from browser plus salt and verifier saved to database on user registration.
var B = server.step1(username, salt, v);
// normal login flow step2a client: server sends users salt from user registration and the server ephemeral number
var credentials = client.step2(salt, B);
// normal login flow step2b server: client sends its client ephemeral number and proof of a shared session key derived from both ephermal numbers and the password
var M2 = server.step2(credentials.A, credentials.M1);
// normal login flow step3 client: client verifies that the server shows proof of the shared session key which demonstrates that it knows actual verifier
client.step3(M2);
Clearly the javascript client starts with only username and password. The server uses the username to resolve the salt and generates a random B. The client is given salt and B from the server and generates its random A and the M1 which is the password proof. The server step2 which takes M1 as a parameter is the server checking the user password proof and it will throw an exception if the proof is bad. The server then sends M2 which is the server proof that it has the user verifier v which is done to prevent a fake server spoofing the real server.
There is a demo of a browser doing SRP to a Java server over AJAX using Thinbus over at thinbus-srp-js-demo. You could re-use the JAX RS with AJAX approach (e.g. Spring MVC AJAX) to perform the first steps up to the creation of A+M1 at the client then post those to Spring Security using the login form post and have Spring Security verify A+M1 by running step2 on the server object as shown in the junit-js test. Then your AuthenticationManager could resolve the server object created by AJAX from a concurrent map keyed by username.
One minor note is that I would consider checking the server proof M2 as optional if you are using HTTPS to a server. If you are not using HTTPS then server spoofing means they can give the user a page which sends the password and ignores a bad M2; so the M2 proof doesn't provide security in the context of webpages. A mobile app which packages the html/js into a native app using something like phone gap would benefit from an M2 check; it can be added into the page after the user is logged in to be checked by the trusted code.
There is a spring security SRP implimentation at https://bitbucket.org/simon_massey/thinbus-srp-spring-demo
The readme page says:
A salient feature of the integration is that there are no changes to
the standard spring security authentication path other than to
configure the custom SrpAuthenticationProvider.
It also says:
Spring Security does not expose the user HTTPSession to the
AuthenticationProvider. So demo code uses a Guava cache with a timeout
to hold the SRP6JavascriptServerSession for the brief period of the
login exchange. As of Thinbus 1.2.1 the session is serialisable so an
alternative approach for a large stateless website would be to hold
the SRP6JavascriptServerSession object in the DB rather than in an
in-memory cache.

Apache Shiro - issue with isPermitted() method and wrong Authorizer class

We have implemented a class called AuthorizerImpl that contains two objects: an AuthorizingRealm and a Subject. We have implemented an isPermitted() method which subsequently calls the isPermitted() method on the subject. Our code looks something like this:
// UserContext object uc is passed in here
AuthorizerImpl auth = new AuthorizerImpl(uc.getUser());
auth.isPermitted("winnebago:drive:eagle5");
We initially log in and authenticate a user's permissions using the above code. The first time a user logs in, it is a a "base user" so to speak. There are certain screens that are specific to certain users, so we call the above code again with a different uc.getUser() to verify the new users permissions. What I am seeing though is that the backend Shiro code is using the previous user to check the permissions, not the new user that I passed into the isPermitted() method. Each time we are calling "new AuthorizerImpl(uc.getUser())" we are creating a new Subject and AuthorizingRealm that are instance variables inside the AuthorizingRealm object. It was my impression that when I create a new AuthorizerImpl, it should use the new subject and realm that we are creating in the constructor. However, it seems that Shiro is caching the previous realm object that was used and is using that? We are using the DefaultSecurityManager. After doing some debugging, I noticed that the DefaultSecurityManager has an authorizer instance variable. It appears to be using the first authorizer object and not the new one that should be created with the new user, which leads me to believe it is is being cached. Is there a way to turn off this caching? Is this what is happening or is it something else? The permissions are being retrieved correctly from the database if the correct user is used to check. How can I resolve this?
Thank you in advance.

How do I bind the current user session to a dynamic var using Clojure Friend library?

I am using the Friend Authentication Library for Clojure to add HTTP basic auth to my webapp.
I have a set of database access functions in a db.clj module that abstracts away the current user so I can invoke methods like (db/get-item ...) for example to retrieve an item for the current user without explicitly specifying the user. I do this by defining a dynamic var called *username*. This allows me to easily test the database access functions at the REPL for different users, then the webapp code can rebind *username* to the session user for when it calls the db functions.
I need to bind *username* to the user for the current session so that whenever the functions in db.clj are accessed from a web server request, the *username* var is set properly.
I can get the session username from ((friend/current-authentication) :username) but I can't figure out where I can hook this into the web-server code. I have a simple middleware:
(defn wrap-username [app]
(fn [req]
(binding [*username* (friend/current-authentication :username)]
(app req))))
But no matter where I call this middleware from, current-authentication always returns nil.
I am trying to understand how the friend authentication code works in order to determine the correct place to do my binding but so far I haven't figured it out.
I guess the way you are calling current-authentication is incorrect as the documentation says you need to pass the current request to this function, so it should be something like:
(binding [*username* ((friend/current-authentication req) :username)] ...
Also make sure the friend middleware is applied before your username middleware.

Rest and ZF session management

I'm trying to create a web service which utilizes Zend framework. The API is REST based and uses Zend_Rest_Controller as base class. I wish to have user management and session, and for that I'm using the following code:
Login (POST)
// user id and password fetched first
$users = new Application_Model_DbTable_UserInfo();
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'users');
$authAdapter->setIdentityColumn('userid')
->setCredentialColumn('password');
$authAdapter->setIdentity($userid)
->setCredential($pwd);
$result = $auth->authenticate($authAdapter);
if($result->isValid()){
Zend_Session::rememberMe(604800);
$storage = new Zend_Auth_Storage_Session();
$usa = $authAdapter->getResultRowObject();
$auth->getStorage()->write($usa);
$authSession = new Zend_Session_Namespace('Zend_Auth');
$authSession->setExpirationSeconds(60*60);
}
and when accessing the service with e.g. some GET method I wish to check that there is a valid session with the following code:
$auth = Zend_Auth::getInstance();
if(!$auth->hasIdentity())
{
// error handling etc.
}
I never get an identity, hence the service doesn't work.
I have followed the guidance for ZF authentication quite strictly, but does the REST stuff need additional items to be taken into account?
I know I'm not answering your question, but if you are REALLY planning to implement a true REST interface (which implies it's going to enable you to scale well), you'd probably better forget about sessions and using Zend_Auth in the way you've depicted above.
Take a look here, where something about REST interfaces and authentication has been discussed already:
Can you help me understand this? "Common REST Mistakes: Sessions are irrelevant"
In short, quoting from the Q/A thread above, "To be RESTful, each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP". I really feel like seconding that.

Restlet: Adding a role depending on which 'project' (group) the user is accessing

Assume a blackboard type application. There are 2 Projects - ProjectA and ProjectB. User 'nupul' (me) is part of both projects. For A I'm an admin and for B I'm just a 'member' (no admin rights)
When accessing the resource at /MySite/ProjectA/Items I want to check if the user is an admin or not.
I know it can be simply done by picking out the {projectName} parameter from the request and using the identifier (of the user making the request) and forwarding that to check against a DB etc.,
My question is 'how' can I add the roles using an Enroler 'during' authentication itself. Since I don't have access to the {projectName} parameter at that stage. I don't know if you have to use Groups/Realms etc., to make this work, but honestly it's just taking me tooooooooooooooooooo long to even understand how to effectively use this? (i.e., before the request is forwarded to the resource)
I mean I know I can create these groups/realms but how do I access the correct 'role' from the resource???? Restlet seriously needs to have more realistic examples and a much better documentation showing the use of it's classes!! It's driving me insane!! Authentication shouldn't be THIS DIFFICULT! :)
The way to do what you want is to split your routers basing on project name within your application (method createInboundRoot). In this case, the projectname will be evaluated before calling the authenticator. See below some examples of implementing such approach:
public Restlet createInboundRoot() {
Router rootRouter = new Router(getContext());
rootRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
rootRouter.attach("/{projectname}/", createApplicationForProject());
return rootRouter;
}
private Restlet createApplicationForProject() {
Router router = new Router(getContext());
ChallengeAuthenticator guard
= new ChallengeAuthenticator(getContext(),
ChallengeScheme.HTTP_BASIC, "realm");
guard.setVerifier(verifier);
guard.setEnroler(enroler);
guard.setNext(router);
router.attach("items", ItemsServerResource.class);
return guard;
}
Using such approach, you'll have access to the value of the projectname variable within the verifier and be able to use it in the authentication processing.
Hope it helps you,
Thierry