Search in sources :

Example 1 with ApplicationDescription

use of org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription in project milo by eclipse.

the class DiscoveryClient method findServers.

/**
 * Query the FindServers service at the {@code endpointUrl}.
 * <p>
 * The discovery URL(s) for each server {@link ApplicationDescription} in the response can then be used in a
 * {@link #getEndpoints(String)} call to discover the endpoints for that server.
 *
 * @param endpointUrl the endpoint URL to find servers at.
 * @param customizer  a {@link Consumer} that accepts a {@link UaStackClientConfigBuilder} for customization.
 * @return a List of {@link ApplicationDescription}s returned by the FindServers service.
 */
public static CompletableFuture<List<ApplicationDescription>> findServers(String endpointUrl, Consumer<UaStackClientConfigBuilder> customizer) {
    EndpointDescription endpoint = new EndpointDescription(endpointUrl, null, null, MessageSecurityMode.None, SecurityPolicy.None.getUri(), null, Stack.TCP_UASC_UABINARY_TRANSPORT_URI, ubyte(0));
    UaStackClientConfigBuilder builder = UaStackClientConfig.builder();
    builder.setEndpoint(endpoint);
    customizer.accept(builder);
    UaStackClientConfig config = builder.build();
    try {
        UaStackClient stackClient = UaStackClient.create(config);
        DiscoveryClient discoveryClient = new DiscoveryClient(stackClient);
        return discoveryClient.connect().thenCompose(c -> c.findServers(endpointUrl, new String[0], new String[0])).whenComplete((e, ex) -> discoveryClient.disconnect()).thenApply(response -> l(response.getServers()));
    } catch (UaException e) {
        return failedFuture(e);
    }
}
Also used : StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) FindServersResponse(org.eclipse.milo.opcua.stack.core.types.structured.FindServersResponse) CompletableFuture(java.util.concurrent.CompletableFuture) Unsigned.ubyte(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.ubyte) RequestHeader(org.eclipse.milo.opcua.stack.core.types.structured.RequestHeader) Consumer(java.util.function.Consumer) Strings(com.google.common.base.Strings) GetEndpointsRequest(org.eclipse.milo.opcua.stack.core.types.structured.GetEndpointsRequest) GetEndpointsResponse(org.eclipse.milo.opcua.stack.core.types.structured.GetEndpointsResponse) List(java.util.List) Stack(org.eclipse.milo.opcua.stack.core.Stack) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ConversionUtil.l(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.l) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) MessageSecurityMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MessageSecurityMode) FutureUtils.failedFuture(org.eclipse.milo.opcua.stack.core.util.FutureUtils.failedFuture) UaException(org.eclipse.milo.opcua.stack.core.UaException) FindServersRequest(org.eclipse.milo.opcua.stack.core.types.structured.FindServersRequest) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) EndpointUtil(org.eclipse.milo.opcua.stack.core.util.EndpointUtil) UaException(org.eclipse.milo.opcua.stack.core.UaException) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription)

Example 2 with ApplicationDescription

use of org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription in project milo by eclipse.

the class DefaultSubscriptionServiceSet method onTransferSubscriptions.

@Override
public void onTransferSubscriptions(ServiceRequest service) throws UaException {
    TransferSubscriptionsRequest request = (TransferSubscriptionsRequest) service.getRequest();
    OpcUaServer server = service.attr(ServiceAttributes.SERVER_KEY).get();
    Session session = service.attr(ServiceAttributes.SESSION_KEY).get();
    List<UInteger> subscriptionIds = l(request.getSubscriptionIds());
    if (subscriptionIds.isEmpty()) {
        throw new UaException(StatusCodes.Bad_NothingToDo);
    }
    List<TransferResult> results = Lists.newArrayList();
    for (UInteger subscriptionId : subscriptionIds) {
        Subscription subscription = server.getSubscriptions().get(subscriptionId);
        if (subscription == null) {
            results.add(new TransferResult(new StatusCode(StatusCodes.Bad_SubscriptionIdInvalid), new UInteger[0]));
        } else {
            Session otherSession = subscription.getSession();
            if (!sessionsHaveSameUser(session, otherSession)) {
                results.add(new TransferResult(new StatusCode(StatusCodes.Bad_UserAccessDenied), new UInteger[0]));
            } else {
                UInteger[] availableSequenceNumbers;
                synchronized (subscription) {
                    otherSession.getSubscriptionManager().sendStatusChangeNotification(subscription, new StatusCode(StatusCodes.Good_SubscriptionTransferred));
                    otherSession.getSubscriptionManager().removeSubscription(subscriptionId);
                    subscription.setSubscriptionManager(session.getSubscriptionManager());
                    subscriptionManager.addSubscription(subscription);
                    subscription.getMonitoredItems().values().forEach(item -> item.setSession(session));
                    availableSequenceNumbers = subscription.getAvailableSequenceNumbers();
                    if (request.getSendInitialValues()) {
                        subscription.getMonitoredItems().values().stream().filter(item -> item instanceof MonitoredDataItem).map(item -> (MonitoredDataItem) item).forEach(MonitoredDataItem::maybeSendLastValue);
                    }
                }
                subscription.getSubscriptionDiagnostics().getTransferRequestCount().increment();
                ApplicationDescription toClient = session.getClientDescription();
                ApplicationDescription fromClient = otherSession.getClientDescription();
                if (Objects.equals(toClient, fromClient)) {
                    subscription.getSubscriptionDiagnostics().getTransferredToSameClientCount().increment();
                } else {
                    subscription.getSubscriptionDiagnostics().getTransferredToAltClientCount().increment();
                }
                results.add(new TransferResult(StatusCode.GOOD, availableSequenceNumbers));
            }
        }
    }
    TransferSubscriptionsResponse response = new TransferSubscriptionsResponse(service.createResponseHeader(), a(results, TransferResult.class), new DiagnosticInfo[0]);
    service.setResponse(response);
}
Also used : StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) MonitoredDataItem(org.eclipse.milo.opcua.sdk.server.items.MonitoredDataItem) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) Subscription(org.eclipse.milo.opcua.sdk.server.subscriptions.Subscription) TransferResult(org.eclipse.milo.opcua.stack.core.types.structured.TransferResult) TransferSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsResponse) Session(org.eclipse.milo.opcua.sdk.server.Session) OpcUaServer(org.eclipse.milo.opcua.sdk.server.OpcUaServer) ConversionUtil.a(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.a) Objects(java.util.Objects) DiagnosticInfo(org.eclipse.milo.opcua.stack.core.types.builtin.DiagnosticInfo) List(java.util.List) Lists(com.google.common.collect.Lists) ServiceRequest(org.eclipse.milo.opcua.stack.server.services.ServiceRequest) ConversionUtil.l(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.l) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) UaException(org.eclipse.milo.opcua.stack.core.UaException) SubscriptionManager(org.eclipse.milo.opcua.sdk.server.subscriptions.SubscriptionManager) SubscriptionServiceSet(org.eclipse.milo.opcua.stack.server.services.SubscriptionServiceSet) TransferSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest) OpcUaServer(org.eclipse.milo.opcua.sdk.server.OpcUaServer) TransferSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest) UaException(org.eclipse.milo.opcua.stack.core.UaException) TransferResult(org.eclipse.milo.opcua.stack.core.types.structured.TransferResult) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) MonitoredDataItem(org.eclipse.milo.opcua.sdk.server.items.MonitoredDataItem) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) TransferSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsResponse) Subscription(org.eclipse.milo.opcua.sdk.server.subscriptions.Subscription) Session(org.eclipse.milo.opcua.sdk.server.Session)

Example 3 with ApplicationDescription

use of org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription in project milo by eclipse.

the class SessionFsmFactory method createSession.

@SuppressWarnings("Duplicates")
private static CompletableFuture<CreateSessionResponse> createSession(FsmContext<State, Event> ctx, OpcUaClient client) {
    UaStackClient stackClient = client.getStackClient();
    EndpointDescription endpoint = stackClient.getConfig().getEndpoint();
    String gatewayServerUri = endpoint.getServer().getGatewayServerUri();
    String serverUri;
    if (gatewayServerUri != null && !gatewayServerUri.isEmpty()) {
        serverUri = endpoint.getServer().getApplicationUri();
    } else {
        serverUri = null;
    }
    ByteString clientNonce = NonceUtil.generateNonce(32);
    ByteString clientCertificate = stackClient.getConfig().getCertificate().map(c -> {
        try {
            return ByteString.of(c.getEncoded());
        } catch (CertificateEncodingException e) {
            return ByteString.NULL_VALUE;
        }
    }).orElse(ByteString.NULL_VALUE);
    ApplicationDescription clientDescription = new ApplicationDescription(client.getConfig().getApplicationUri(), client.getConfig().getProductUri(), client.getConfig().getApplicationName(), ApplicationType.Client, null, null, null);
    CreateSessionRequest request = new CreateSessionRequest(client.newRequestHeader(), clientDescription, serverUri, client.getConfig().getEndpoint().getEndpointUrl(), client.getConfig().getSessionName().get(), clientNonce, clientCertificate, client.getConfig().getSessionTimeout().doubleValue(), client.getConfig().getMaxResponseMessageSize());
    LOGGER.debug("[{}] Sending CreateSessionRequest...", ctx.getInstanceId());
    return stackClient.sendRequest(request).thenApply(CreateSessionResponse.class::cast).thenCompose(response -> {
        try {
            SecurityPolicy securityPolicy = SecurityPolicy.fromUri(endpoint.getSecurityPolicyUri());
            if (securityPolicy != SecurityPolicy.None) {
                if (response.getServerCertificate().isNullOrEmpty()) {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "Certificate missing from CreateSessionResponse");
                }
                List<X509Certificate> serverCertificateChain = CertificateUtil.decodeCertificates(response.getServerCertificate().bytesOrEmpty());
                X509Certificate serverCertificate = serverCertificateChain.get(0);
                X509Certificate certificateFromEndpoint = CertificateUtil.decodeCertificate(endpoint.getServerCertificate().bytesOrEmpty());
                if (!serverCertificate.equals(certificateFromEndpoint)) {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "Certificate from CreateSessionResponse did not " + "match certificate from EndpointDescription!");
                }
                client.getConfig().getCertificateValidator().validateCertificateChain(serverCertificateChain, endpoint.getServer().getApplicationUri(), EndpointUtil.getHost(endpoint.getEndpointUrl()));
                SignatureData serverSignature = response.getServerSignature();
                byte[] dataBytes = Bytes.concat(clientCertificate.bytesOrEmpty(), clientNonce.bytesOrEmpty());
                byte[] signatureBytes = serverSignature.getSignature().bytesOrEmpty();
                SignatureUtil.verify(SecurityAlgorithm.fromUri(serverSignature.getAlgorithm()), serverCertificate, dataBytes, signatureBytes);
            }
            return completedFuture(response);
        } catch (UaException e) {
            return failedFuture(e);
        }
    });
}
Also used : X509Certificate(java.security.cert.X509Certificate) KEY_CLOSE_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_CLOSE_FUTURE) KeyPair(java.security.KeyPair) SignedSoftwareCertificate(org.eclipse.milo.opcua.stack.core.types.structured.SignedSoftwareCertificate) Arrays(java.util.Arrays) ApplicationType(org.eclipse.milo.opcua.stack.core.types.enumerated.ApplicationType) ScheduledFuture(java.util.concurrent.ScheduledFuture) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) LoggerFactory(org.slf4j.LoggerFactory) ServerState(org.eclipse.milo.opcua.stack.core.types.enumerated.ServerState) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) ReadRequest(org.eclipse.milo.opcua.stack.core.types.structured.ReadRequest) TransferResult(org.eclipse.milo.opcua.stack.core.types.structured.TransferResult) KEY_WAIT_TIME(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_WAIT_TIME) OpcUaSubscriptionManager(org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscriptionManager) ByteBuffer(java.nio.ByteBuffer) QualifiedName(org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName) UserIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.UserIdentityToken) SecurityAlgorithm(org.eclipse.milo.opcua.stack.core.security.SecurityAlgorithm) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) KEY_SESSION_INITIALIZERS(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION_INITIALIZERS) CertificateUtil(org.eclipse.milo.opcua.stack.core.util.CertificateUtil) CreateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionRequest) ActivateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.ActivateSessionRequest) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) Predicate(java.util.function.Predicate) KEY_SESSION_ACTIVITY_LISTENERS(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION_ACTIVITY_LISTENERS) TransferSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsResponse) Streams(com.google.common.collect.Streams) Bytes(com.google.common.primitives.Bytes) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) KEY_WAIT_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_WAIT_FUTURE) ActivateSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.ActivateSessionResponse) List(java.util.List) Stream(java.util.stream.Stream) PrivateKey(java.security.PrivateKey) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) KEY_KEEP_ALIVE_FAILURE_COUNT(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_KEEP_ALIVE_FAILURE_COUNT) EndpointUtil(org.eclipse.milo.opcua.stack.core.util.EndpointUtil) OpcUaSession(org.eclipse.milo.opcua.sdk.client.OpcUaSession) CertificateEncodingException(java.security.cert.CertificateEncodingException) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) CloseSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CloseSessionRequest) KEY_SESSION_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION_FUTURE) ActionContext(com.digitalpetri.strictmachine.dsl.ActionContext) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) SignedIdentityToken(org.eclipse.milo.opcua.sdk.client.api.identity.SignedIdentityToken) CompletableFuture(java.util.concurrent.CompletableFuture) CreateSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionResponse) RequestHeader(org.eclipse.milo.opcua.stack.core.types.structured.RequestHeader) ImmutableList(com.google.common.collect.ImmutableList) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ConversionUtil.l(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.l) SignatureData(org.eclipse.milo.opcua.stack.core.types.structured.SignatureData) ReadResponse(org.eclipse.milo.opcua.stack.core.types.structured.ReadResponse) FutureUtils.complete(org.eclipse.milo.opcua.stack.core.util.FutureUtils.complete) ServiceFaultListener(org.eclipse.milo.opcua.sdk.client.api.ServiceFaultListener) SessionFuture(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.SessionFuture) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) TransferSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest) KEY_SESSION(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) SignatureUtil(org.eclipse.milo.opcua.stack.core.util.SignatureUtil) Fsm(com.digitalpetri.strictmachine.Fsm) Logger(org.slf4j.Logger) OpcUaClientConfig(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig) UaStackClient(org.eclipse.milo.opcua.stack.client.UaStackClient) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) KEY_KEEP_ALIVE_SCHEDULED_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_KEEP_ALIVE_SCHEDULED_FUTURE) TimeUnit(java.util.concurrent.TimeUnit) NonceUtil(org.eclipse.milo.opcua.stack.core.util.NonceUtil) FsmContext(com.digitalpetri.strictmachine.FsmContext) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) FutureUtils.failedFuture(org.eclipse.milo.opcua.stack.core.util.FutureUtils.failedFuture) UaException(org.eclipse.milo.opcua.stack.core.UaException) FsmBuilder(com.digitalpetri.strictmachine.dsl.FsmBuilder) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) UaException(org.eclipse.milo.opcua.stack.core.UaException) CertificateEncodingException(java.security.cert.CertificateEncodingException) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) X509Certificate(java.security.cert.X509Certificate) SignatureData(org.eclipse.milo.opcua.stack.core.types.structured.SignatureData) CreateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionRequest) UaStackClient(org.eclipse.milo.opcua.stack.client.UaStackClient) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy)

Example 4 with ApplicationDescription

use of org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription in project milo by eclipse.

the class SessionManager method stripNonEssentialFields.

/**
 * Strip the non-essential fields from an EndpointDescription and its ApplicationDescription
 * for return by the CreateSession service.
 * <p>
 * See Part 4, 5.6.6.2 for details.
 *
 * @param endpoint the {@link EndpointDescription} to strip non-essential fields from.
 * @return a new {@link EndpointDescription} with only the essential fields.
 */
private static EndpointDescription stripNonEssentialFields(EndpointDescription endpoint) {
    // It is recommended that Servers only include the server.applicationUri, endpointUrl,
    // securityMode, securityPolicyUri, userIdentityTokens, transportProfileUri, and
    // securityLevel with all other parameters set to null. Only the recommended parameters
    // shall be verified by the client.
    ApplicationDescription applicationDescription = endpoint.getServer();
    ApplicationDescription newApplicationDescription = new ApplicationDescription(applicationDescription.getApplicationUri(), null, null, ApplicationType.Server, null, null, null);
    return new EndpointDescription(endpoint.getEndpointUrl(), newApplicationDescription, ByteString.NULL_VALUE, endpoint.getSecurityMode(), endpoint.getSecurityPolicyUri(), endpoint.getUserIdentityTokens(), endpoint.getTransportProfileUri(), endpoint.getSecurityLevel());
}
Also used : EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription)

Example 5 with ApplicationDescription

use of org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription in project milo by eclipse.

the class SessionManager method createSession.

private CreateSessionResponse createSession(ServiceRequest serviceRequest) throws UaException {
    CreateSessionRequest request = (CreateSessionRequest) serviceRequest.getRequest();
    long maxSessionCount = server.getConfig().getLimits().getMaxSessionCount().longValue();
    if (createdSessions.size() + activeSessions.size() >= maxSessionCount) {
        throw new UaException(StatusCodes.Bad_TooManySessions);
    }
    ByteString serverNonce = NonceUtil.generateNonce(32);
    NodeId authenticationToken = new NodeId(0, NonceUtil.generateNonce(32));
    long maxRequestMessageSize = serviceRequest.getServer().getConfig().getEncodingLimits().getMaxMessageSize();
    double revisedSessionTimeout = Math.max(5000, Math.min(server.getConfig().getLimits().getMaxSessionTimeout(), request.getRequestedSessionTimeout()));
    ApplicationDescription clientDescription = request.getClientDescription();
    long secureChannelId = serviceRequest.getSecureChannelId();
    EndpointDescription endpoint = serviceRequest.getEndpoint();
    SecurityPolicy securityPolicy = SecurityPolicy.fromUri(endpoint.getSecurityPolicyUri());
    EndpointDescription[] serverEndpoints = server.getEndpointDescriptions().stream().filter(ed -> !ed.getEndpointUrl().endsWith("/discovery")).filter(ed -> endpointMatchesUrl(ed, request.getEndpointUrl())).filter(ed -> Objects.equal(endpoint.getTransportProfileUri(), ed.getTransportProfileUri())).map(SessionManager::stripNonEssentialFields).toArray(EndpointDescription[]::new);
    if (serverEndpoints.length == 0) {
        // GetEndpoints in UaStackServer returns *all* endpoints regardless of a hostname
        // match in the endpoint URL if the result after filtering is 0 endpoints. Do the
        // same here.
        serverEndpoints = server.getEndpointDescriptions().stream().filter(ed -> !ed.getEndpointUrl().endsWith("/discovery")).filter(ed -> Objects.equal(endpoint.getTransportProfileUri(), ed.getTransportProfileUri())).map(SessionManager::stripNonEssentialFields).toArray(EndpointDescription[]::new);
    }
    ByteString clientNonce = request.getClientNonce();
    if (securityPolicy != SecurityPolicy.None) {
        NonceUtil.validateNonce(clientNonce);
        if (clientNonces.contains(clientNonce)) {
            throw new UaException(StatusCodes.Bad_NonceInvalid);
        }
    }
    if (securityPolicy != SecurityPolicy.None && clientNonce.isNotNull()) {
        clientNonces.add(clientNonce);
        while (clientNonces.size() > 64) {
            clientNonces.remove(0);
        }
    }
    ByteString clientCertificateBytes = request.getClientCertificate();
    if (securityPolicy != SecurityPolicy.None && serviceRequest.getClientCertificateBytes() != null) {
        if (!Objects.equal(clientCertificateBytes, serviceRequest.getClientCertificateBytes())) {
            throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "certificate used to open secure channel " + "differs from certificate used to create session");
        }
    }
    SecurityConfiguration securityConfiguration = createSecurityConfiguration(endpoint, clientCertificateBytes);
    if (securityPolicy != SecurityPolicy.None) {
        X509Certificate clientCertificate = securityConfiguration.getClientCertificate();
        List<X509Certificate> clientCertificateChain = securityConfiguration.getClientCertificateChain();
        if (clientCertificate == null || clientCertificateChain == null) {
            throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "client certificate must be non-null");
        }
        ServerCertificateValidator certificateValidator = server.getConfig().getCertificateValidator();
        certificateValidator.validateCertificateChain(clientCertificateChain, clientDescription.getApplicationUri());
    }
    // SignatureData must be created using only the bytes of the client
    // leaf certificate, not the bytes of the client certificate chain.
    SignatureData serverSignature = getServerSignature(securityPolicy, securityConfiguration.getKeyPair(), clientNonce, securityConfiguration.getClientCertificateBytes());
    NodeId sessionId = new NodeId(1, "Session:" + UUID.randomUUID());
    String sessionName = request.getSessionName();
    Duration sessionTimeout = Duration.ofMillis(DoubleMath.roundToLong(revisedSessionTimeout, RoundingMode.UP));
    Session session = new Session(server, sessionId, sessionName, sessionTimeout, clientDescription, request.getServerUri(), request.getMaxResponseMessageSize(), endpoint, secureChannelId, securityConfiguration);
    session.setLastNonce(serverNonce);
    session.addLifecycleListener((s, remove) -> {
        createdSessions.remove(authenticationToken);
        activeSessions.remove(authenticationToken);
        sessionListeners.forEach(l -> l.onSessionClosed(s));
    });
    createdSessions.put(authenticationToken, session);
    sessionListeners.forEach(l -> l.onSessionCreated(session));
    return new CreateSessionResponse(serviceRequest.createResponseHeader(), sessionId, authenticationToken, revisedSessionTimeout, serverNonce, endpoint.getServerCertificate(), serverEndpoints, new SignedSoftwareCertificate[0], serverSignature, uint(maxRequestMessageSize));
}
Also used : X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) SignedSoftwareCertificate(org.eclipse.milo.opcua.stack.core.types.structured.SignedSoftwareCertificate) MonitoredItemServiceSet(org.eclipse.milo.opcua.stack.server.services.MonitoredItemServiceSet) DigestUtil.sha1(org.eclipse.milo.opcua.stack.core.util.DigestUtil.sha1) Arrays(java.util.Arrays) ApplicationType(org.eclipse.milo.opcua.stack.core.types.enumerated.ApplicationType) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) LoggerFactory(org.slf4j.LoggerFactory) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) ByteBuffer(java.nio.ByteBuffer) UserIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.UserIdentityToken) AttributeServiceSet(org.eclipse.milo.opcua.stack.server.services.AttributeServiceSet) SecurityAlgorithm(org.eclipse.milo.opcua.stack.core.security.SecurityAlgorithm) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) Duration(java.time.Duration) Map(java.util.Map) NodeManagementServiceSet(org.eclipse.milo.opcua.stack.server.services.NodeManagementServiceSet) Objects(com.google.common.base.Objects) ServiceAttributes(org.eclipse.milo.opcua.sdk.server.services.ServiceAttributes) CertificateUtil(org.eclipse.milo.opcua.stack.core.util.CertificateUtil) RoundingMode(java.math.RoundingMode) CreateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionRequest) ActivateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.ActivateSessionRequest) ServerDiagnosticsSummary(org.eclipse.milo.opcua.sdk.server.diagnostics.ServerDiagnosticsSummary) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) UUID(java.util.UUID) Bytes(com.google.common.primitives.Bytes) DiagnosticInfo(org.eclipse.milo.opcua.stack.core.types.builtin.DiagnosticInfo) ActivateSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.ActivateSessionResponse) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) CloseSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CloseSessionResponse) Optional(java.util.Optional) NotNull(org.jetbrains.annotations.NotNull) EndpointUtil(org.eclipse.milo.opcua.stack.core.util.EndpointUtil) SubscriptionServiceSet(org.eclipse.milo.opcua.stack.server.services.SubscriptionServiceSet) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CloseSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CloseSessionRequest) ViewServiceSet(org.eclipse.milo.opcua.stack.server.services.ViewServiceSet) UserTokenPolicy(org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy) UaRuntimeException(org.eclipse.milo.opcua.stack.core.UaRuntimeException) Strings.nullToEmpty(com.google.common.base.Strings.nullToEmpty) IdentityValidator(org.eclipse.milo.opcua.sdk.server.identity.IdentityValidator) CreateSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionResponse) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ServiceRequest(org.eclipse.milo.opcua.stack.server.services.ServiceRequest) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ServerCertificateValidator(org.eclipse.milo.opcua.stack.server.security.ServerCertificateValidator) MethodServiceSet(org.eclipse.milo.opcua.stack.server.services.MethodServiceSet) ConversionUtil.l(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.l) MessageSecurityMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MessageSecurityMode) SignatureData(org.eclipse.milo.opcua.stack.core.types.structured.SignatureData) AttributeHistoryServiceSet(org.eclipse.milo.opcua.stack.server.services.AttributeHistoryServiceSet) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) QueryServiceSet(org.eclipse.milo.opcua.stack.server.services.QueryServiceSet) DoubleMath(com.google.common.math.DoubleMath) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) SignatureUtil(org.eclipse.milo.opcua.stack.core.util.SignatureUtil) Lists.newCopyOnWriteArrayList(com.google.common.collect.Lists.newCopyOnWriteArrayList) Logger(org.slf4j.Logger) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) AnonymousIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.AnonymousIdentityToken) UserTokenType(org.eclipse.milo.opcua.stack.core.types.enumerated.UserTokenType) SessionServiceSet(org.eclipse.milo.opcua.stack.server.services.SessionServiceSet) Maps(com.google.common.collect.Maps) NonceUtil(org.eclipse.milo.opcua.stack.core.util.NonceUtil) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) UaException(org.eclipse.milo.opcua.stack.core.UaException) UaException(org.eclipse.milo.opcua.stack.core.UaException) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) Duration(java.time.Duration) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) X509Certificate(java.security.cert.X509Certificate) SignatureData(org.eclipse.milo.opcua.stack.core.types.structured.SignatureData) ServerCertificateValidator(org.eclipse.milo.opcua.stack.server.security.ServerCertificateValidator) CreateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionRequest) CreateSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionResponse) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId)

Aggregations

ApplicationDescription (org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription)5 List (java.util.List)4 StatusCodes (org.eclipse.milo.opcua.stack.core.StatusCodes)4 UaException (org.eclipse.milo.opcua.stack.core.UaException)4 EndpointDescription (org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription)4 ConversionUtil.l (org.eclipse.milo.opcua.stack.core.util.ConversionUtil.l)4 SecurityPolicy (org.eclipse.milo.opcua.stack.core.security.SecurityPolicy)3 StatusCode (org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode)3 UInteger (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger)3 EndpointUtil (org.eclipse.milo.opcua.stack.core.util.EndpointUtil)3 Lists (com.google.common.collect.Lists)2 Bytes (com.google.common.primitives.Bytes)2 ByteBuffer (java.nio.ByteBuffer)2 KeyPair (java.security.KeyPair)2 X509Certificate (java.security.cert.X509Certificate)2 Arrays (java.util.Arrays)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 SecurityAlgorithm (org.eclipse.milo.opcua.stack.core.security.SecurityAlgorithm)2 ByteString (org.eclipse.milo.opcua.stack.core.types.builtin.ByteString)2 DiagnosticInfo (org.eclipse.milo.opcua.stack.core.types.builtin.DiagnosticInfo)2