CloudHSM login/logout error - pkcs#11

So i was trying to login/logout from AWS CloudHSM multiple times. The flow is the following:
Have an open session (C_GetSessionInfo returns slot id 1, state 3, flags 6 while everything goes fine).
If i'm logged in to this session, call C_Logout on this session.
Call C_Login supplying the correct credentials.
Repeat.
After the first login, the first logout/login cycle goes fine but during the second logout a CKR_DEVICE_REMOVED error is returned and every subsequent calls return CKR_SESSION_HANDLE_INVALID.
Calling C_GetSessionInfo after the error returns slot id, state and flags all set to 0 and C_GetSlotList with token present returns an empty list. This behavior (error on the second logout) is completely consistent and happens every single time. No operations are performed while being logged in.
Does anyone know the possible reason for this error and how to avoid it? Thanks in advance.

You need not logout each time when you do some operation. The best way is: You should re-use the session handle id which you got when you login for the first time.

Related

Zend_Auth clearidentity and Zend_Session::destroy causing confusion

I have the following logout action:
public function logoutAction() {
Zend_Auth::getInstance()->clearIdentity();
Zend_Session::destroy();
$this->_helper->flashMessenger->addMessage(array('success' =>
_('You were successfully logged out.')));
$this->_redirect('/index/index');
}
If I don't comment out the line: Zend_Session::destroy() I get an error:
Fatal error: Uncaught exception 'Zend_Session_Exception' with message 'The session was explicitly destroyed during this request, attempting to re-start is not allowed.' in /usr/local/share/php/library/Zend/Controller/Plugin/Broker.php on line 336 Zend_Session_Exception: The session was explicitly destroyed during this request, attempting to re-start is not allowed.
I have read about this issue here and here but remain unclear on how I should proceed. Should I just not use Zend_Session::destroy()? What would be the implications and dangers of not using it, and what is the alternative?
What causes you problems is, that right after destroying the session, you are reusing it (by facilitating the FlashMessenger. If not destroying the session after logout bothers you, you could display a logout page instead of redirecting to your frontpage with a flash message.
Leaving some of your session data intact after your user logged out, might have security implications, but that depends on what you store in your session and where and how you use the data. In order to make sure, that you don't keep data, that belonged to the logged in user in your session, just use a specific session namespace for this data and call unsetNamespace() upon logout.
Zend_Auth have its own session namespace and after Zend_Auth::getInstance()->clearIdentity(); it removes it so there is no need to destroy all session nemaspaces if you use them.
Example what here happens:
// logging user
$_SESSION['Zend_Auth'] = 'logged user data';
// after Zend_Auth::getInstance()->clearIdentity();
$_SESSION['Zend_Auth'] = null;
// after Zend_Session::destroy();
session_destroy();

asp.net mvc azure "Error accessing the data store!"

I've started using the AspProviders code to store my session data in my table storage.
I'm sporadically getting the following error:
Description: Exception of type 'System.Web.HttpException' was thrown. INNER_EXCEPTION:Error accessing the data store! INNER_EXCEPTION:An error occurred while processing this request. INNER_EXCEPTION: ConditionNotMet The condition specified using HTTP conditional header(s) is not met. RequestId:0c4239cc-41fb-42c5-98c5-7e9cc22096af Time:2010-10-15T04:28:07.0726801Z
StackTrace:
System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar)
System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) INNER_EXCEPTION:
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(HttpContext context, String id, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 484
System.Web.SessionState.SessionStateModule.GetSessionStateItem()
System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state) INNER_EXCEPTION:
Microsoft.WindowsAzure.StorageClient.Tasks.Task1.get_Result()
Microsoft.WindowsAzure.StorageClient.Tasks.Task1.ExecuteAndWait()
Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry[T](Func`2 impl, RetryPolicy policy)
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(TableServiceContext svc, SessionRow session, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 603
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(HttpContext context, String id, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 480 INNER_EXCEPTION:
System.Data.Services.Client.DataServiceContext.SaveResult.d__1e.MoveNext()
Anyone run into this? The only useful information I've found is this, which I'm hesitant to do:
If you want to bypass the validation, you can open TableStorageSessionStateProvider.cs, find ReleaseItemExclusive, and modify the code from:
svc.UpdateObject(session);
to:
svc.Detach(session);
svc.AttachTo("Sessions", session, "*");
svc.UpdateObject(session);
from here
Thanks!
So I decided to change this:
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
to this:
try
{
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
}
catch
{
svc.Detach(session);
svc.AttachTo("Sessions", session, "*");
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
}
So, I'll see how that works...
I've encountered this problem as well and after some investigation it seems to happen more often when you have more than one instance and you try to make calls in rapid succession in the same session. (e.g. if you had an auto complete box and making ajax calls on each key press)
This occurs because when you try to access the session data, first of all the web server takes out a lock on that session. When the request is complete, it releases the lock. With the table service provider, it updates this lock status by updating a field in the table. What I think is happening is that Instance1 loads the session row, then Instance2 loads the session row, Instance1 saves down the updated lock status and when Instance2 attempts to save the lock status it gets an error because the object isn't in the same state as when it loaded it (the ETag doesn't match any more).
This is why the fix that you found will stop the error from occurring, because by specifying the "*" in the AttachTo, when Instance2 attempts to save the lock it will turn off ETag checking (and over write the changes made by Instance1).
In our situation we have altered the provider so that we can turn off session for certain paths (the ajax call that was giving us our problems didn't need access to session data, neither did the loading of images) which may be an option for you depending on what is causing your problem.
Unfortunately the TableStorageSessionStateProvider is part of the sample projects and so isn't (as far as I'm aware, but I'll happily be told otherwise) officially supported by Microsoft. It does have other issues, like the fact that it doesn't clean up it's session data once a session expires, so you will end up with lots of junk in the session table and blob container that you'll have to clean up some other way.

Session Management (Zend Framework specific)

I'm trying to get the rememberMe() function to remember users and retain sessions for months at a time.
I've read that if you pass a value through rememberMe() it will not work if the session has already been started. From the session_set_cookie_params() documentation in the PHP manual, "you need to call session_set_cookie_params() for every request and before session_start() is called."
By I am calling Zend_session::start() in my bootstrap as i thought I was supposed to. My problem is that rememberMe() doesn't seem to be working.
When I call session_get_cookie_params(); I get:
Array([lifetime] => 0 [path] => / [domain] => [secure] => httponly] =>)
Any thoughts?
I've solved the problem. sessions were being erased by another website on the same server which expires sessions every 24 minutes. To fix this I set the session.save_path to a new folder. I also set session.gc_maxlifetime and session.cookie_lifetime to be very large numbers.
problem solved!
Don't use the start() method. It should work fine if you are using MVC. The session_start must be called before any output is send and that's right before sending response (because of outputbuffering). The session is started automatically upon first Zend_Session_namespace usage.

How to use Zend_Form_Element_Hash?

Then I'm trying to use Zend_Form_Element_Hash it regenerates a hash every request.
In my code:
// form
$this->addElement('hash', 'hihacker', array('salt' => 'thesal'));
Then I dumping $_SESSION I see a new value each page reload.
Then I send a form it reports an error "The token '28a5e0e2a50a3d4afaa654468fd29420' does not match the given token 'a64407cc11376dac1916d2101de90d29'", each time - new pair of tokens
$form = new Form();
$form->addElement('hash', 'hihacker',
array('salt' => 'YOUR TOO MUCH SALTY TEXT !!##'));
if ($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
// Valid ! you are safe do what ever you want .
} else if (count($form->getErrors('request_token')) > 0) {
///get him to the error controller
$this->_forward('csrf-forbidden', 'error');
return;
}
its working very well for me but double check your session setting
"
Internally, the element stores a unique identifier using Zend_Session_Namespace, and checks for it at submission (checking that the TTL has not expired). The 'Identical' validator is then used to ensure the submitted hash matches the stored hash.
The 'formHidden' view helper is used to render the element in the form.
"
form ZF docs
Zend_Form_Element_Hash is supposed to regenerate every request. What you're describing is your tokens going out of synch. This generally happens with multiple forms or with redirects/forwards.
If you're using ajax somewhere on the page you can put this in the controller action (near the end)
$form->hash->initCsrfToken();
$this->view->hash = $form->hash->getValue();
Then when you do the ajax call, just pull the token and replace the token on the form using a selector and .replaceWith(). This is how you deal with multiple forms as well
Otherwise you're probably either redirecting something or loading something twice and you should change the hop in the Zend library. The hop is how many times a token can be requested before it expires
Check that there is not a hidden redirect or forward somewhere in your script... the hash has a hop count of 1 so any redirect will make it expire.
FWIW i think there was a subtle bug in the hash a few versions of ZF ago. I got stuck on exactly the same problem, and hacked the code to make the hop count = 2. When I upgraded ZF this problem went away.

facebook connect api "Cannot use string offset as an array in" error

Please help! I have been grappling with this error for days and I cannot for the life of me figure it out. I am using facebook connect and fetching a "contact_email" attribute using their api method users_getInfo.
The issue is that when I execute this PHP file, i get this error: "Cannot use string offset as an array in...". This error specifically refers to this line of code: $firstName=$user_details[0]['contact_email'];
I'm thinking this is because the user_getInfo method is not returning any results... However, the most ridiculous part about all this is that, I can execute the code below several dozens of times in a row SUCCESSFULLY without the above error, BUT THEN randomly without changing ANY code at all, I will suddenly encounter this error, in which case it will begin to give me an error several dozens of times, and then AGAIN without any code change, start executing successfully again.
This odd behavior occurs regardless of the attribute i am fetching.. (contact_email, first_name, last_name, etc.). I am running php 5.2.11. Is there something I'm missing??
Please Help!
include_once 'site/fbconnect/config.php'; //has $api_key and $secret defined.
include_once 'site/facebook-platform/client/facebook.php';
global $api_key,$secret;
$fb=new Facebook($api_key,$secret);
$fb->require_login();
$fb_user=$fb->get_loggedin_user();
$user_details=$fb->api_client->users_getInfo($fb_user,array('last_name','first_name','contact_email'));
$email=$user_details[0]['contact_email'];
$firstName=$user_details[0]['first_name'];
$lastName=$user_details[0]['last_name'];
Using the facebook php client API I was also receiving that error but my error was related to checking if the users are friends using the friends_areFriends php method.
//$results_array = $facebook->api_client->friends_areFriends($fb_user, $selected_friend_uid);
//$answer = $results_array[0]['are_friends'];
I would get this error when I assigned the $result, "Cannot use string offset as an array" and aparently the friends_areFriends method above was failing alot. My solution was to create a for loop that ran that code and then check $answer to see if it was an array using php method is_array() and executing the method call again if it wasn't. My loop was for 10 tries before just letting it fail. In the end, this check was severely degrating the performance of my facebook application. Instead, I removed the friends_areFriends api call alltogather and my facebook app performance was nice and fast again.
You could probably implement a similar feature allowing the method to retry itself if the result is not an array. The problem I think is on facebook's side, sometimes they are flooded and the requests do not complete successfully. I caution you not to retry more than 5 tries though because if you do a forever loop, rest assured they will ban you from the using the Facebook API for flooding it, so be careful.