use of org.eclipse.milo.opcua.stack.core.types.structured.OpenSecureChannelResponse in project milo by eclipse.
the class UascServerAsymmetricHandler method openSecureChannel.
private OpenSecureChannelResponse openSecureChannel(ChannelHandlerContext ctx, OpenSecureChannelRequest request) throws UaException {
SecurityTokenRequestType requestType = request.getRequestType();
if (requestType == SecurityTokenRequestType.Issue) {
secureChannel.setMessageSecurityMode(request.getSecurityMode());
String endpointUrl = ctx.channel().attr(UascServerHelloHandler.ENDPOINT_URL_KEY).get();
EndpointDescription endpoint = stackServer.getEndpointDescriptions().stream().filter(e -> {
boolean transportMatch = Objects.equals(e.getTransportProfileUri(), transportProfile.getUri());
boolean pathMatch = Objects.equals(EndpointUtil.getPath(e.getEndpointUrl()), EndpointUtil.getPath(endpointUrl));
boolean securityPolicyMatch = Objects.equals(e.getSecurityPolicyUri(), secureChannel.getSecurityPolicy().getUri());
boolean securityModeMatch = Objects.equals(e.getSecurityMode(), request.getSecurityMode());
return transportMatch && pathMatch && securityPolicyMatch && securityModeMatch;
}).findFirst().orElseThrow(() -> {
String message = String.format("no matching endpoint found: transportProfile=%s, " + "endpointUrl=%s, securityPolicy=%s, securityMode=%s", transportProfile, endpointUrl, secureChannel.getSecurityPolicy(), request.getSecurityMode());
return new UaException(StatusCodes.Bad_SecurityChecksFailed, message);
});
ctx.channel().attr(ENDPOINT_KEY).set(endpoint);
}
if (requestType == SecurityTokenRequestType.Renew && secureChannel.getMessageSecurityMode() != request.getSecurityMode()) {
throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "secure channel renewal requested a different MessageSecurityMode.");
}
long channelLifetime = request.getRequestedLifetime().longValue();
channelLifetime = Math.min(channelLifetime, stackServer.getConfig().getMaximumSecureChannelLifetime().longValue());
channelLifetime = Math.max(channelLifetime, stackServer.getConfig().getMinimumSecureChannelLifetime().longValue());
ChannelSecurityToken newToken = new ChannelSecurityToken(uint(secureChannel.getChannelId()), uint(stackServer.getNextTokenId()), DateTime.now(), uint(channelLifetime));
SecurityKeys newKeys = null;
if (secureChannel.isSymmetricSigningEnabled()) {
// Validate the remote nonce; it must be non-null and the correct length for the security algorithm.
ByteString remoteNonce = request.getClientNonce();
NonceUtil.validateNonce(remoteNonce, secureChannel.getSecurityPolicy());
ByteString localNonce = generateNonce(secureChannel.getSecurityPolicy());
secureChannel.setLocalNonce(localNonce);
secureChannel.setRemoteNonce(remoteNonce);
newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getRemoteNonce(), secureChannel.getLocalNonce());
}
ChannelSecurity oldSecrets = secureChannel.getChannelSecurity();
SecurityKeys oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null;
ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null;
ChannelSecurity newSecrets = new ChannelSecurity(newKeys, newToken, oldKeys, oldToken);
secureChannel.setChannelSecurity(newSecrets);
/*
* Cancel the previous timeout, if it exists, and start a new one.
*/
if (secureChannelTimeout == null || secureChannelTimeout.cancel()) {
final long lifetime = channelLifetime;
secureChannelTimeout = Stack.sharedWheelTimer().newTimeout(timeout -> {
logger.debug("SecureChannel renewal timed out after {}ms. id={}, channel={}", lifetime, secureChannel.getChannelId(), ctx.channel());
ctx.close();
}, channelLifetime, TimeUnit.MILLISECONDS);
}
ResponseHeader responseHeader = new ResponseHeader(DateTime.now(), request.getRequestHeader().getRequestHandle(), StatusCode.GOOD, null, null, null);
return new OpenSecureChannelResponse(responseHeader, uint(PROTOCOL_VERSION), newToken, secureChannel.getLocalNonce());
}
use of org.eclipse.milo.opcua.stack.core.types.structured.OpenSecureChannelResponse in project milo by eclipse.
the class UascClientMessageHandler method onOpenSecureChannel.
private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
if (secureChannelTimeout != null) {
if (secureChannelTimeout.cancel()) {
logger.debug("OpenSecureChannel timeout canceled");
secureChannelTimeout = null;
} else {
logger.warn("timed out waiting for secure channel");
handshakeFuture.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, "timed out waiting for secure channel"));
ctx.close();
return;
}
}
// skip messageType, chunkType, messageSize, secureChannelId
buffer.skipBytes(3 + 1 + 4 + 4);
AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer, config.getEncodingLimits());
if (headerRef.compareAndSet(null, securityHeader)) {
// first time we've received the header; validate and verify the server certificate
CertificateValidator certificateValidator = config.getCertificateValidator();
SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityHeader.getSecurityPolicyUri());
if (securityPolicy != SecurityPolicy.None) {
ByteString serverCertificateBytes = securityHeader.getSenderCertificate();
List<X509Certificate> serverCertificateChain = CertificateUtil.decodeCertificates(serverCertificateBytes.bytesOrEmpty());
certificateValidator.validateCertificateChain(serverCertificateChain);
}
} else {
if (!securityHeader.equals(headerRef.get())) {
throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match");
}
}
if (accumulateChunk(buffer)) {
final List<ByteBuf> buffersToDecode = chunkBuffers;
chunkBuffers = new ArrayList<>(maxChunkCount);
serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
ByteBuf message;
try {
ChunkDecoder.DecodedMessage decodedMessage = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);
message = decodedMessage.getMessage();
} catch (MessageAbortException e) {
logger.warn("Received message abort chunk; error={}, reason={}", e.getStatusCode(), e.getMessage());
return;
} catch (MessageDecodeException e) {
logger.error("Error decoding asymmetric message", e);
handshakeFuture.completeExceptionally(e);
ctx.close();
return;
}
try {
UaResponseMessage response = (UaResponseMessage) binaryDecoder.setBuffer(message).readMessage(null);
StatusCode serviceResult = response.getResponseHeader().getServiceResult();
if (serviceResult.isGood()) {
OpenSecureChannelResponse oscr = (OpenSecureChannelResponse) response;
secureChannel.setChannelId(oscr.getSecurityToken().getChannelId().longValue());
logger.debug("Received OpenSecureChannelResponse.");
NonceUtil.validateNonce(oscr.getServerNonce(), secureChannel.getSecurityPolicy());
installSecurityToken(ctx, oscr);
handshakeFuture.complete(secureChannel);
} else {
ServiceFault serviceFault = (response instanceof ServiceFault) ? (ServiceFault) response : new ServiceFault(response.getResponseHeader());
handshakeFuture.completeExceptionally(new UaServiceFaultException(serviceFault));
ctx.close();
}
} catch (Throwable t) {
logger.error("Error decoding OpenSecureChannelResponse", t);
handshakeFuture.completeExceptionally(t);
ctx.close();
} finally {
message.release();
}
});
}
}
use of org.eclipse.milo.opcua.stack.core.types.structured.OpenSecureChannelResponse in project milo by eclipse.
the class UascClientMessageHandler method installSecurityToken.
private void installSecurityToken(ChannelHandlerContext ctx, OpenSecureChannelResponse response) {
ChannelSecurity.SecurityKeys newKeys = null;
if (response.getServerProtocolVersion().longValue() < PROTOCOL_VERSION) {
throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported, "server protocol version unsupported: " + response.getServerProtocolVersion());
}
ChannelSecurityToken newToken = response.getSecurityToken();
if (secureChannel.isSymmetricSigningEnabled()) {
secureChannel.setRemoteNonce(response.getServerNonce());
newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getLocalNonce(), secureChannel.getRemoteNonce());
}
ChannelSecurity oldSecrets = secureChannel.getChannelSecurity();
ChannelSecurity.SecurityKeys oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null;
ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null;
secureChannel.setChannelSecurity(new ChannelSecurity(newKeys, newToken, oldKeys, oldToken));
DateTime createdAt = response.getSecurityToken().getCreatedAt();
long revisedLifetime = response.getSecurityToken().getRevisedLifetime().longValue();
if (revisedLifetime > 0) {
long renewAt = (long) (revisedLifetime * 0.75);
renewFuture = ctx.executor().schedule(() -> sendOpenSecureChannelRequest(ctx, SecurityTokenRequestType.Renew), renewAt, TimeUnit.MILLISECONDS);
} else {
logger.warn("Server revised secure channel lifetime to 0; renewal will not occur.");
}
ctx.executor().execute(() -> {
// SecureChannel is ready; remove the acknowledge handler.
if (ctx.pipeline().get(UascClientAcknowledgeHandler.class) != null) {
ctx.pipeline().remove(UascClientAcknowledgeHandler.class);
}
});
ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();
long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue();
long previousTokenId = channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L);
logger.debug("SecureChannel id={}, currentTokenId={}, previousTokenId={}, lifetime={}ms, createdAt={}", secureChannel.getChannelId(), currentTokenId, previousTokenId, revisedLifetime, createdAt);
}
use of org.eclipse.milo.opcua.stack.core.types.structured.OpenSecureChannelResponse in project milo by eclipse.
the class UascServerAsymmetricHandler method sendOpenSecureChannelResponse.
private void sendOpenSecureChannelResponse(ChannelHandlerContext ctx, long requestId, OpenSecureChannelRequest request) {
serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
ByteBuf messageBuffer = BufferUtil.pooledBuffer();
try {
OpenSecureChannelResponse response = openSecureChannel(ctx, request);
binaryEncoder.setBuffer(messageBuffer);
binaryEncoder.writeMessage(null, response);
checkMessageSize(messageBuffer);
EncodedMessage encodedMessage = chunkEncoder.encodeAsymmetric(secureChannel, requestId, messageBuffer, MessageType.OpenSecureChannel);
if (!symmetricHandlerAdded) {
UascServerSymmetricHandler symmetricHandler = new UascServerSymmetricHandler(stackServer, serializationQueue, secureChannel);
ctx.pipeline().addBefore(ctx.name(), null, symmetricHandler);
symmetricHandlerAdded = true;
}
CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer();
for (ByteBuf chunk : encodedMessage.getMessageChunks()) {
chunkComposite.addComponent(chunk);
chunkComposite.writerIndex(chunkComposite.writerIndex() + chunk.readableBytes());
}
ctx.writeAndFlush(chunkComposite, ctx.voidPromise());
logger.debug("Sent OpenSecureChannelResponse.");
} catch (MessageEncodeException e) {
logger.error("Error encoding OpenSecureChannelResponse: {}", e.getMessage(), e);
ctx.fireExceptionCaught(e);
} catch (UaSerializationException e) {
logger.error("Error serializing OpenSecureChannelResponse: {}", e.getMessage(), e);
ctx.fireExceptionCaught(e);
} catch (UaException e) {
logger.error("Error installing security token: {}", e.getStatusCode(), e);
ctx.close();
} finally {
messageBuffer.release();
}
});
}
Aggregations