Search in sources :

Example 1 with UserTokenPolicy

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

the class AnonymousProviderTest method testGetIdentityToken_EmptyPolicyId.

@Test
public void testGetIdentityToken_EmptyPolicyId() throws Exception {
    EndpointDescription endpoint = new EndpointDescription(null, null, null, null, null, new UserTokenPolicy[] { new UserTokenPolicy("", UserTokenType.Anonymous, null, null, null) }, null, null);
    AnonymousProvider p = new AnonymousProvider();
    SignedIdentityToken signedIdentityToken = p.getIdentityToken(endpoint, ByteString.NULL_VALUE);
    assertEquals(signedIdentityToken.getToken().getPolicyId(), "");
    assertTrue(signedIdentityToken.getToken() instanceof AnonymousIdentityToken);
}
Also used : AnonymousIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.AnonymousIdentityToken) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) UserTokenPolicy(org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy) Test(org.testng.annotations.Test)

Example 2 with UserTokenPolicy

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

the class AnonymousProviderTest method testGetIdentityToken.

@Test
public void testGetIdentityToken() throws Exception {
    EndpointDescription endpoint = new EndpointDescription(null, null, null, null, null, new UserTokenPolicy[] { new UserTokenPolicy("anonymous", UserTokenType.Anonymous, null, null, null) }, null, null);
    AnonymousProvider p = new AnonymousProvider();
    SignedIdentityToken signedIdentityToken = p.getIdentityToken(endpoint, ByteString.NULL_VALUE);
    assertEquals(signedIdentityToken.getToken().getPolicyId(), "anonymous");
    assertTrue(signedIdentityToken.getToken() instanceof AnonymousIdentityToken);
}
Also used : AnonymousIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.AnonymousIdentityToken) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) UserTokenPolicy(org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy) Test(org.testng.annotations.Test)

Example 3 with UserTokenPolicy

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

the class SessionManager method validateIdentityToken.

private Object validateIdentityToken(Session session, Object tokenObject, SignatureData tokenSignature) throws UaException {
    IdentityValidator identityValidator = server.getConfig().getIdentityValidator();
    UserTokenPolicy tokenPolicy = validatePolicyId(session, tokenObject);
    if (tokenObject instanceof UserIdentityToken) {
        return identityValidator.validateIdentityToken(session, (UserIdentityToken) tokenObject, tokenPolicy, tokenSignature);
    } else {
        throw new UaException(StatusCodes.Bad_IdentityTokenInvalid);
    }
}
Also used : IdentityValidator(org.eclipse.milo.opcua.sdk.server.identity.IdentityValidator) UaException(org.eclipse.milo.opcua.stack.core.UaException) UserIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.UserIdentityToken) UserTokenPolicy(org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy)

Example 4 with UserTokenPolicy

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

the class SessionManager method validatePolicyId.

/**
 * Validates the policyId on a {@link UserIdentityToken} Object is a policyId that exists on the Endpoint that
 * {@code session} is connected to.
 *
 * @param session     the current {@link Session}
 * @param tokenObject the {@link UserIdentityToken} Object from the client.
 * @return the first {@link UserTokenPolicy} on the Endpoint matching the policyId.
 * @throws UaException if the token object is invalid or no matching policy is found.
 */
private UserTokenPolicy validatePolicyId(Session session, Object tokenObject) throws UaException {
    if (tokenObject instanceof UserIdentityToken) {
        UserIdentityToken token = (UserIdentityToken) tokenObject;
        String policyId = token.getPolicyId();
        List<UserTokenPolicy> userIdentityTokens = l(session.getEndpoint().getUserIdentityTokens());
        Optional<UserTokenPolicy> policy = userIdentityTokens.stream().filter(t -> Objects.equal(policyId, t.getPolicyId())).findFirst();
        return policy.orElseThrow(() -> new UaException(StatusCodes.Bad_IdentityTokenInvalid, "policy not found: " + policyId));
    } else {
        throw new UaException(StatusCodes.Bad_IdentityTokenInvalid);
    }
}
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) UserIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.UserIdentityToken) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) UserTokenPolicy(org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy)

Example 5 with UserTokenPolicy

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

the class UsernameProvider method getIdentityToken.

@Override
public SignedIdentityToken getIdentityToken(EndpointDescription endpoint, ByteString serverNonce) throws Exception {
    List<UserTokenPolicy> userIdentityTokens = l(endpoint.getUserIdentityTokens());
    List<UserTokenPolicy> tokenPolicies = userIdentityTokens.stream().filter(t -> t.getTokenType() == UserTokenType.UserName).collect(Collectors.toList());
    if (tokenPolicies.isEmpty()) {
        throw new Exception("no UserTokenPolicy with UserTokenType.UserName found");
    }
    UserTokenPolicy tokenPolicy = policyChooser.apply(tokenPolicies);
    SecurityPolicy securityPolicy;
    String securityPolicyUri = tokenPolicy.getSecurityPolicyUri();
    try {
        if (securityPolicyUri == null || securityPolicyUri.isEmpty()) {
            securityPolicyUri = endpoint.getSecurityPolicyUri();
        }
        securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);
    } catch (Throwable t) {
        throw new UaException(StatusCodes.Bad_SecurityPolicyRejected, t);
    }
    byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8);
    byte[] nonceBytes = serverNonce.bytesOrEmpty();
    ByteBuf buffer = Unpooled.buffer();
    if (securityPolicy == SecurityPolicy.None) {
        buffer.writeBytes(passwordBytes);
    } else {
        NonceUtil.validateNonce(serverNonce);
        buffer.writeIntLE(passwordBytes.length + nonceBytes.length);
        buffer.writeBytes(passwordBytes);
        buffer.writeBytes(nonceBytes);
        ByteString bs = endpoint.getServerCertificate();
        if (bs == null || bs.isNull()) {
            throw new UaException(StatusCodes.Bad_ConfigurationError, "UserTokenPolicy requires encryption but " + "server did not provide a certificate in endpoint");
        }
        List<X509Certificate> certificateChain = CertificateUtil.decodeCertificates(bs.bytes());
        X509Certificate certificate = certificateChain.get(0);
        if (SecurityPolicy.None.getUri().equals(endpoint.getSecurityPolicyUri()) || !Stack.TCP_UASC_UABINARY_TRANSPORT_URI.equals(endpoint.getTransportProfileUri())) {
            // If the SecurityPolicy is None or if this is an HTTP(S) connection the certificate used to encrypt
            // the username and password must be trusted. Otherwise, if it's a secure connection, the certificate
            // will have already been validated and verified when the secure channel or session was created.
            certificateValidator.validateCertificateChain(certificateChain, endpoint.getServer().getApplicationUri(), EndpointUtil.getHost(endpoint.getEndpointUrl()));
        }
        int plainTextBlockSize = SecureChannel.getAsymmetricPlainTextBlockSize(certificate, securityPolicy.getAsymmetricEncryptionAlgorithm());
        int cipherTextBlockSize = SecureChannel.getAsymmetricCipherTextBlockSize(certificate, securityPolicy.getAsymmetricEncryptionAlgorithm());
        int blockCount = (buffer.readableBytes() + plainTextBlockSize - 1) / plainTextBlockSize;
        Cipher cipher = getAndInitializeCipher(certificate, securityPolicy);
        ByteBuffer plainTextNioBuffer = buffer.nioBuffer();
        ByteBuffer cipherTextNioBuffer = Unpooled.buffer(cipherTextBlockSize * blockCount).nioBuffer(0, cipherTextBlockSize * blockCount);
        for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) {
            int position = blockNumber * plainTextBlockSize;
            int limit = Math.min(buffer.readableBytes(), (blockNumber + 1) * plainTextBlockSize);
            ((Buffer) plainTextNioBuffer).position(position);
            ((Buffer) plainTextNioBuffer).limit(limit);
            cipher.doFinal(plainTextNioBuffer, cipherTextNioBuffer);
        }
        ((Buffer) cipherTextNioBuffer).flip();
        buffer = Unpooled.wrappedBuffer(cipherTextNioBuffer);
    }
    byte[] bs = new byte[buffer.readableBytes()];
    buffer.readBytes(bs);
    // UA Part 4, Section 7.35.3 UserNameIdentityToken:
    // encryptionAlgorithm parameter is null if the password is not encrypted.
    String securityAlgorithmUri = securityPolicy.getAsymmetricEncryptionAlgorithm().getUri();
    String encryptionAlgorithm = securityAlgorithmUri.isEmpty() ? null : securityAlgorithmUri;
    UserNameIdentityToken token = new UserNameIdentityToken(tokenPolicy.getPolicyId(), username, ByteString.of(bs), encryptionAlgorithm);
    return new SignedIdentityToken(token, new SignatureData(null, null));
}
Also used : X509Certificate(java.security.cert.X509Certificate) UserTokenPolicy(org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) GeneralSecurityException(java.security.GeneralSecurityException) ByteBuf(io.netty.buffer.ByteBuf) ClientCertificateValidator(org.eclipse.milo.opcua.stack.client.security.ClientCertificateValidator) 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) Buffer(java.nio.Buffer) SignatureData(org.eclipse.milo.opcua.stack.core.types.structured.SignatureData) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) CertificateUtil(org.eclipse.milo.opcua.stack.core.util.CertificateUtil) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) UserTokenType(org.eclipse.milo.opcua.stack.core.types.enumerated.UserTokenType) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) NonceUtil(org.eclipse.milo.opcua.stack.core.util.NonceUtil) List(java.util.List) SecureChannel(org.eclipse.milo.opcua.stack.core.channel.SecureChannel) UaException(org.eclipse.milo.opcua.stack.core.UaException) UserNameIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.UserNameIdentityToken) EndpointUtil(org.eclipse.milo.opcua.stack.core.util.EndpointUtil) ByteBuffer(java.nio.ByteBuffer) Buffer(java.nio.Buffer) UaException(org.eclipse.milo.opcua.stack.core.UaException) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer) UserNameIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.UserNameIdentityToken) GeneralSecurityException(java.security.GeneralSecurityException) UaException(org.eclipse.milo.opcua.stack.core.UaException) X509Certificate(java.security.cert.X509Certificate) SignatureData(org.eclipse.milo.opcua.stack.core.types.structured.SignatureData) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) Cipher(javax.crypto.Cipher) UserTokenPolicy(org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy)

Aggregations

UserTokenPolicy (org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy)8 EndpointDescription (org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription)6 UaException (org.eclipse.milo.opcua.stack.core.UaException)4 AnonymousIdentityToken (org.eclipse.milo.opcua.stack.core.types.structured.AnonymousIdentityToken)4 Test (org.testng.annotations.Test)4 X509Certificate (java.security.cert.X509Certificate)3 SecurityPolicy (org.eclipse.milo.opcua.stack.core.security.SecurityPolicy)3 ByteString (org.eclipse.milo.opcua.stack.core.types.builtin.ByteString)3 ByteBuffer (java.nio.ByteBuffer)2 List (java.util.List)2 IdentityValidator (org.eclipse.milo.opcua.sdk.server.identity.IdentityValidator)2 StatusCodes (org.eclipse.milo.opcua.stack.core.StatusCodes)2 SignatureData (org.eclipse.milo.opcua.stack.core.types.structured.SignatureData)2 UserIdentityToken (org.eclipse.milo.opcua.stack.core.types.structured.UserIdentityToken)2 Objects (com.google.common.base.Objects)1 Strings.nullToEmpty (com.google.common.base.Strings.nullToEmpty)1 Lists (com.google.common.collect.Lists)1 Lists.newCopyOnWriteArrayList (com.google.common.collect.Lists.newCopyOnWriteArrayList)1 Maps (com.google.common.collect.Maps)1 DoubleMath (com.google.common.math.DoubleMath)1