Why Cryptoki.C_OpenSession disconnect from HSM sometimes - java

I' created a web service isAlive to check if I can create session with the HSM soft using the Cryptoki ,I automated the execution of my web service using SoapUI so I execute my service in a loop each 40s ,it work well but after a number of call I can't connect to my HSM until I restart my App : this the part of code that I used to connect to HSM
// create session handle
CK_SESSION_HANDLE session= new CK_SESSION_HANDLE();
// return code
CK_RV retcode;
// get session
retcode=Cryptoki.C_OpenSession(safeNetSlot, CKF.RW_SESSION, null, null, session);
checkRetCode(retcode, "Could not open session on HSM");
log.debug("Session [{}]",session.longValue());
// do login
final String recovHsmPassword = PasswordManagement.recoverPassword(hsmPassword);
retcode=Cryptoki.C_Login(session, CKU.USER, recovHsmPassword.getBytes(), recovHsmPassword.length());
checkRetCode(retcode, "Could not login as user");
During the execution of my service I watch logs I look that the session.longValue() incremented with each calls :
This's the logs :
INFO 5056 --- [nio-8191-exec-5] ccom.test.app.V1Controler : Request for isAlive API
DEBUG 5056 --- [nio-8191-exec-5] com.test.app.hsm.HsmService : Session [1]
INFO 5056 --- [nio-8191-exec-5] com.test.app.V1Controler : Request for isAlive API
DEBUG 5056 --- [nio-8191-exec-5] com.test.app.hsm.HsmService : Session [2]
INFO 5056 --- [nio-8191-exec-5] com.test.app.V1Controler : Request for isAlive API
DEBUG 5056 --- [nio-8191-exec-5] com.test.app.hsm.HsmService : Session [3]
INFO 5056 --- [nio-8191-exec-5] com.test.app.V1Controler : Request for isAlive API
......
INFO 5056 --- [nio-8191-exec-5] com.test.app.V1Controler : Request for isAlive API
DEBUG 5056 --- [nio-8191-exec-5] com.test.app.hsm.HsmService : Session [1176]
INFO 5056 --- [nio-8191-exec-5] com.test.app.V1Controler : Request for isAlive API
2018-08-14 10:39:06.550 ERROR 1 --- [nio-8443-exec-3] com.test.app.hsm.HsmService : HSM return error [MSG_ERROR general error]
I ask if someone have an idea how Cryptoki.C_OpenSession works and why I desconnect from my HSM

Generally HSM's have a bounded number of sessions available. Currently you are opening sessions, but you are never closing them with C_CloseSession. You should handle sessions as if they are resources, and resources may be sparse.
Note that there is also a function called C_TokenInfo that can be used to check the token status. Make sure you are using the right function for the job. You don't want to use a password when not required.

Related

Not starting the JMS listener using jmsListenerEndpointRegistry.start()

I am trying to start the JMS listener using jmsListenerEndpointRegistry.start() which was stopped using jmsListenerEndpointRegistry.stop(). But looks like it is not getting started. When I am trying to consume the messages it is not allowing me to do so as it is still stopped. Please help me how to start it back using start method.
In application.properties I have spring.jms.listener.auto-startup=true
Using Apache ActiveMQ(Version-5.16.3)
2022-01-06 16:27:54.699 INFO 28804 --- [nio-9091-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 22 ms
2022-01-06 16:27:54.726 ERROR 28804 --- [nio-9091-exec-1] com.jms.poc.controller.JmsController : --------- Trying to start JMS using jmsListenerEndpointRegistry.start()----------
2022-01-06 16:27:54.727 ERROR 28804 --- [nio-9091-exec-1] com.jms.poc.controller.JmsController : ----------jmsListenerEndpointRegistry.isRunning()-------- : false
There is no need to change the autoStartup property in startJmsListener - that property only applies when the application context is initialized.
You have no #JmsListeneners - the only one is commented out.
registry.isRunning() only returns true when at least one of its containers is running.

"Unauthorized: Full authentication is required to access this resource" when booting up the app

This is a bit annoying since I've solved the original problem (which was this) but now this is another thing that I can't quite debug myself.
I am using JHispter 6.10 (Spring Boot 2.2.7.RELEASE) + React for my project. I've recently come to the need of using entities as catalogues (so they can be managed easily by an admin) and they need to be used on the register page. My first problem was that they wouldn't the dropdown in the register page, but that problem had to do with SecurityConfiguration.java, so I added the entities to be permitted to All:
.antMatchers("/api/comunidad-famdals").permitAll()
.antMatchers("/api/ciudads").permitAll()
.antMatchers("/api/estados").permitAll()
.antMatchers("/api/ladrillo-famdals").permitAll()
.antMatchers("/api/pais").permitAll()
.antMatchers("/api/**").authenticated()
And that seems to work just fine, but the first time I load the app (in dev mode), it throws the next error:
2020-10-09 02:03:33.337 DEBUG 63312 --- [ XNIO-1 task-9] c.f.m.r.CustomAuditEventRepository : Enter: add() with argument[s] = [AuditEvent [timestamp=2020-10-09T07:03:33.302498Z, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null, type=org.springframework.security.access.AccessDeniedException, message=Access is denied}]]
2020-10-09 02:03:33.342 DEBUG 63312 --- [ XNIO-1 task-9] c.f.m.r.CustomAuditEventRepository : Exit: add() with result = null
2020-10-09 02:03:33.473 WARN 63312 --- [ XNIO-1 task-9] o.z.problem.spring.common.AdviceTraits : Unauthorized: Full authentication is required to access this resource
2020-10-09 02:03:33.564 WARN 63312 --- [ XNIO-1 task-9] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.security.authentication.InsufficientAuthenticationException: Full authentication is required to access this resource]
And when trying to register, the dropdown still doesn't show anything:
But if I go home once again, the terminal shows that all the queries have been done correctly, and sure enough, if I go back to the register page:
I would like to know if I am missing something on my SecurityConfiguration.java or if the order of the configuration needs to be different for it to work properly.
you have to give permissions to your endpoint in the Spring Boot Configuration (SecurityConfiguration.java)
add a new antMatchers parameter to the HttpSecurity.authorizeRequests() it should look like this:
http
.authorizeRequests()
.antMatchers("/api/yourEndpoint").permitAll()
of course you have to select who has authority to call this endpoint
Hope it works for you :)

Cognito authentication keeps retrying forever, without throwing exception

I have a simple test code for Cognito authentication code in Java with Spring Boot. It works fine on my local, but when I on my remote server (CentOS) it acts very weirdly. If a user does not exist in the pool. keeps creating and recreating new threads and sending the request.
The code:
protected boolean isValidCognito(String username, String password) {
// Retrieving the AWS credentials from the default instance profile credentials instead of ".withCredentials()".
// More info on https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html
AWSCognitoIdentityProvider awsCognitoIDPClient = AWSCognitoIdentityProviderClientBuilder.standard().build();
Map<String,String> authParams =new HashMap<>();
authParams.put("USERNAME", username);
authParams.put("PASSWORD", password);
AdminInitiateAuthRequest initialRequest = new AdminInitiateAuthRequest()
.withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
.withAuthParameters(authParams)
.withClientId(COGNITO_CLIENT_ID)
.withUserPoolId(COGNITO_POOL_ID);
try {
// NOTE: I know the request is being sent for sure, so we probably get at least this far
AdminInitiateAuthResult initialResponse = awsCognitoIDPClient.adminInitiateAuth(initialRequest);
Map<String, String> challengeParams = initialResponse.getChallengeParameters();
String cognitoUserIdForSrp = challengeParams.get("USER_ID_FOR_SRP");
String cognitoUserAttributes = challengeParams.get("userAttributes");
logger.debug("Cognito authenticated user ID: " + cognitoUserIdForSrp
+ " with user attributes: " + cognitoUserAttributes);
return true;
} catch (NotAuthorizedException nae) {
logger.error("Invalid Cognito username/password provided for " + authParams.get("USERNAME"));
return false;
} catch (AWSCognitoIdentityProviderException acipe) {
logger.error("Amazon Cognito Identity Provider Error!");
logger.debug("Make sure the user exists in the pool, and ALLOW_ADMIN_USER_PASSWORD_AUTH is enabled.");
return false;
} catch (Exception e) {
logger.error("Unexpected Error: ", e);
return false;
}
}
Logs if it helps:
2020-02-25 17:14:54.919 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:54.926 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:54.935 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:54.942 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:54.950 DEBUG 25144 --- [http-nio-8080-exec-98] c.c.c.r.persistence.CognDaoImpl : There is a user migrated to Cognito with user_id: SOME_UUID
2020-02-25 17:14:54.950 INFO 25144 --- [http-nio-8080-exec-98] c.c.c.r.c.AuthenticationController : my_email#mailinator.com has been migrated. Using Cognito for authentication.
2020-02-25 17:14:56.655 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:56.673 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:56.683 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:56.692 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:56.705 DEBUG 25144 --- [http-nio-8080-exec-160] c.c.c.r.persistence.CogDaoImpl : There is a user migrated to Cognito with user_id: SOME_UUID
2020-02-25 17:14:56.705 INFO 25144 --- [http-nio-8080-exec-160] c.c.c.r.c.AuthenticationController : my_email#mailinator.com has been migrated. Using Cognito for authentication.
...
There is nothing inherently wrong with "creating and recreating threads". If you have too many threads, your jvm will run out of memory or your process will die because you have hit some system limits. If you think your code is going into a loop, you need to find out who is calling your code and analyze that part of your code. Perhaps a thread-dump may help.

How to send a Disconnect-Request using java?

I was able to send an Access-Request to Freeradius server and get Access-Accept, using tinyradius library in a spring boot application. Now I need to send a COA Request and then a Disconnect-Request to end the session.
I tried to send a COA-Request, and I get an error.
> 2019-07-23 08:11:26.383 INFO 1 --- [nio-8080-exec-2]
> org.tinyradius.util.RadiusClient : communication failure,
> retry 1 2019-07-23 08:11:29.387 INFO 1 --- [nio-8080-exec-2]
> org.tinyradius.util.RadiusClient : communication failure,
> retry 2 2019-07-23 08:11:32.391 ERROR 1 --- [nio-8080-exec-2]
> org.tinyradius.util.RadiusClient : communication failure
> (timeout), no more retries
RadiusClient rc = new RadiusClient("172.17.0.2", "testing123");
CoaRequest coaRequest=new CoaRequest();
coaRequest.setAuthenticator(dto.getAuthenticator().getBytes());
RadiusPacket response = rc.communicate(coaRequest,3799);
I get 'Receive timed out' error and the request doesn't seem to hit the server either. I would like to know how to send the COA-Request and Disconnect-Request using Tinyradius library

Eclipse milo: Session closed when trying to read data

I have an external OPC UA server, from which I would like to read data. I use username and password authentication, so my client is initialized like follows:
public class MyClient {
// ...
public MyClient() throws Exception {
EndpointDescription[] endpoints =
UaTcpStackClient.getEndpoints(OPCConstants.OPC_SERVER_URI).get();
// using the first endpoint
EndpointDescription endpoint = endpoints[0];
// client configuration
OpcUaClientConfig config = OpcUaClientConfig.builder()
.setApplicationName(LocalizedText.english("Example Client"))
.setApplicationUri(String.format("some:example-client:%s",
UUID.randomUUID()))
.setIdentityProvider(new UsernameProvider(USERNAME, PWD))
.setEndpoint(endpoint)
.build();
}
}
The client's request is the following:
public CompletableFuture<DataValue> getData(NodeId nodeId) {
LOGGER.debug("Sending request");
return client.readValue(60000000.0, TimestampsToReturn.Server, nodeId);
}
I call this request from the main method after initializing the client and connecting it to the server:
MyClient client = new MyClient();
NodeId requestedData = new NodeId(DATA_ID, DATA_KEY);
LOGGER.info("Sending synchronous TestStackRequest NodeId={}",
requestedData);
client.connect();
DataValue response = client.getData(requestedData).get();
LOGGER.info("Received response value={}", response.getValue());
client.disconnect();
However, this code doesn't work (the session is closed when trying to read informations from the server). I get the following output:
2018-04-12 17:43:27,765 DEBUG --- [ua-netty-event-loop-0] Recycler : -Dio.netty.recycler.maxCapacity.default: 262144
2018-04-12 17:43:27,777 DEBUG --- [ua-netty-event-loop-0] UaTcpClientAcknowledgeHandler : Sent Hello message on channel=[id: 0xfd9519e3, L:/172.20.100.54:55805 - R:/172.20.100.135:4840].
2018-04-12 17:43:27,786 DEBUG --- [ua-netty-event-loop-0] UaTcpClientAcknowledgeHandler : Received Acknowledge message on channel=[id: 0xfd9519e3, L:/172.20.100.54:55805 - R:/172.20.100.135:4840].
2018-04-12 17:43:27,793 DEBUG --- [ua-netty-event-loop-0] UaTcpClientMessageHandler : OpenSecureChannel timeout scheduled for +5s
2018-04-12 17:43:27,946 DEBUG --- [ua-shared-pool-0] UaTcpClientMessageHandler : Sent OpenSecureChannelRequest (Issue, id=0, currentToken=-1, previousToken=-1).
2018-04-12 17:43:27,951 DEBUG --- [ua-netty-event-loop-0] UaTcpClientMessageHandler : OpenSecureChannel timeout canceled
2018-04-12 17:43:27,961 DEBUG --- [ua-shared-pool-0] UaTcpClientMessageHandler : Received OpenSecureChannelResponse.
2018-04-12 17:43:27,967 DEBUG --- [ua-shared-pool-0] UaTcpClientMessageHandler : SecureChannel id=1698234671, currentTokenId=1, previousTokenId=-1, lifetime=3600000ms, createdAt=DateTime{utcTime=131680285857690000, javaDate=Thu Apr 12 19:43:05 CEST 2018}
2018-04-12 17:43:27,968 DEBUG --- [ua-netty-event-loop-0] UaTcpClientMessageHandler : 0 message(s) queued before handshake completed; sending now.
2018-04-12 17:43:27,968 DEBUG --- [ua-shared-pool-1] ClientChannelManager : Channel bootstrap succeeded: localAddress=/172.20.100.54:55805, remoteAddress=/172.20.100.135:4840
2018-04-12 17:43:27,996 DEBUG --- [ua-shared-pool-0] ClientChannelManager : disconnect(), currentState=Connected
2018-04-12 17:43:27,997 DEBUG --- [ua-shared-pool-1] ClientChannelManager : Sending CloseSecureChannelRequest...
2018-04-12 17:43:28,000 DEBUG --- [ua-netty-event-loop-0] ClientChannelManager : channelInactive(), disconnect complete
2018-04-12 17:43:28,001 DEBUG --- [ua-netty-event-loop-0] ClientChannelManager : disconnect complete, state set to Idle
2018-04-12 17:43:28,011 INFO --- [main] OpcUaClient : Eclipse Milo OPC UA Stack version: 0.2.1
2018-04-12 17:43:28,011 INFO --- [main] OpcUaClient : Eclipse Milo OPC UA Client SDK version: 0.2.1
2018-04-12 17:43:28,056 DEBUG --- [main] OpcUaClient : Added ServiceFaultListener: org.eclipse.milo.opcua.sdk.client.session.SessionFsm$FaultListener#46d59067
2018-04-12 17:43:28,066 DEBUG --- [main] OpcUaClient : Added SessionActivityListener: org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscriptionManager$1#78452606
2018-04-12 17:43:28,189 INFO --- [main] CommunicationMain : Sending synchronous TestStackRequest NodeId=NodeId{ns=6, id=::opcua:opcData.outGoing.basic.cycleStep}
2018-04-12 17:43:28,189 DEBUG --- [main] ClientChannelManager : connect(), currentState=NotConnected
2018-04-12 17:43:28,190 DEBUG --- [main] ClientChannelManager : connect() while NotConnected
java.lang.Exception
at org.eclipse.milo.opcua.stack.client.ClientChannelManager.connect(ClientChannelManager.java:67)
at org.eclipse.milo.opcua.stack.client.UaTcpStackClient.connect(UaTcpStackClient.java:127)
at org.eclipse.milo.opcua.sdk.client.OpcUaClient.connect(OpcUaClient.java:313)
at com.mycompany.opcua.participants.MyClient.connect(MyClient.java:147)
at com.mycompany.opcua.participants.CommunicationMain.testClient(CommunicationMain.java:69)
at com.mycompany.opcua.participants.CommunicationMain.main(CommunicationMain.java:51)
2018-04-12 17:43:28,190 DEBUG --- [main] MyClient : Sending request
2018-04-12 17:43:28,197 DEBUG --- [ua-netty-event-loop-1] UaTcpClientAcknowledgeHandler : Sent Hello message on channel=[id: 0xd9b3f832, L:/172.20.100.54:55806 - R:/172.20.100.135:4840].
2018-04-12 17:43:28,204 DEBUG --- [ua-netty-event-loop-1] UaTcpClientAcknowledgeHandler : Received Acknowledge message on channel=[id: 0xd9b3f832, L:/172.20.100.54:55806 - R:/172.20.100.135:4840].
2018-04-12 17:43:28,205 DEBUG --- [ua-netty-event-loop-1] UaTcpClientMessageHandler : OpenSecureChannel timeout scheduled for +5s
2018-04-12 17:43:28,205 DEBUG --- [ua-shared-pool-0] UaTcpClientMessageHandler : Sent OpenSecureChannelRequest (Issue, id=0, currentToken=-1, previousToken=-1).
2018-04-12 17:43:28,208 DEBUG --- [ua-netty-event-loop-1] UaTcpClientMessageHandler : OpenSecureChannel timeout canceled
2018-04-12 17:43:28,208 DEBUG --- [ua-shared-pool-0] UaTcpClientMessageHandler : Received OpenSecureChannelResponse.
2018-04-12 17:43:28,209 DEBUG --- [ua-shared-pool-0] UaTcpClientMessageHandler : SecureChannel id=1698234672, currentTokenId=1, previousTokenId=-1, lifetime=3600000ms, createdAt=DateTime{utcTime=131680285860260000, javaDate=Thu Apr 12 19:43:06 CEST 2018}
2018-04-12 17:43:28,209 DEBUG --- [ua-netty-event-loop-1] UaTcpClientMessageHandler : 0 message(s) queued before handshake completed; sending now.
2018-04-12 17:43:28,209 DEBUG --- [ua-shared-pool-1] ClientChannelManager : Channel bootstrap succeeded: localAddress=/172.20.100.54:55806, remoteAddress=/172.20.100.135:4840
2018-04-12 17:43:28,210 DEBUG --- [ua-shared-pool-0] SessionFsm : S(Inactive) x E(CreateSessionEvent) = S'(Creating)
Exception in thread "main" java.util.concurrent.ExecutionException: UaException: status=Bad_SessionClosed, message=The session was closed by the client.
at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)2018-04-12 17:43:28,212 DEBUG --- [ua-shared-pool-1] SessionFsm : Sending CreateSessionRequest...
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
at com.mycompany.opcua.participants.CommunicationMain.testClient(CommunicationMain.java:70)
at com.mycompany.opcua.participants.CommunicationMain.main(CommunicationMain.java:51)
Caused by: UaException: status=Bad_SessionClosed, message=The session was closed by the client.
at org.eclipse.milo.opcua.stack.core.util.FutureUtils.failedUaFuture(FutureUtils.java:100)
at org.eclipse.milo.opcua.stack.core.util.FutureUtils.failedUaFuture(FutureUtils.java:88)
at org.eclipse.milo.opcua.sdk.client.session.states.Inactive.(Inactive.java:28)
at org.eclipse.milo.opcua.sdk.client.session.SessionFsm.(SessionFsm.java:69)
at org.eclipse.milo.opcua.sdk.client.OpcUaClient.(OpcUaClient.java:159)2018-04-12 17:43:28,212 INFO --- [NonceUtilSecureRandom] NonceUtil : SecureRandom seeded in 0ms.
at com.mycompany.opcua.participants.MyClient.(MyClient.java:112)
at com.mycompany.opcua.participants.CommunicationMain.testClient(CommunicationMain.java:60)
... 1 more
I use Eclipse milo 0.2.1 as OPC UA library.
Could you please tell me hat can cause this issue and how to fix it? Can it be a race condition related to this?
I can connect to the same server using other client (UaExpert).
Thank you in advance.
All of the calls you're making (connect(), disconnect(), and readValues()) are asynchronous, so what's likely happening here is you're not connected when you attempt the read.
Make sure for these examples you block for the result before moving to the next step. (you're not doing this on connect())

Categories

Resources