Error 'Certificate Not Trusted' while creating session

85 Views Asked by At

I'm new with OPC Ua protocol but i have to connect e communicate with our customer's opc ua server. First of all i built a client in C# and then the certificate for my client with OpenSSL and i sent it to the customer who put it in the trusted folder for certificates, but every time i try to connect i keep getting 'Certficate Not Trusted' after the session creation. Thats the code of the client and a copy of the certificate that i created https://github.com/PaulettoJacopo/OPC-UA

using System;
using System.Runtime.Intrinsics.X86;
using System.Security.Cryptography.X509Certificates;
using Opc.Ua;
using Opc.Ua.Client;
using System.IO;

class Program
{
    
    private async Task<object> ReadVariableAsync(Session session, NodeId nodeId, CancellationToken cancellationToken = default)
    {
        // Read the value using the 'ReadAsync' method
        ReadValueId readValueId = new ReadValueId { NodeId = nodeId, AttributeId = Attributes.Value };

        // Use await directly on the ReadAsync method and pass the CancellationToken
        ReadResponse readResponse = await session.ReadAsync(
            null,
            0,
            TimestampsToReturn.Both,
            new[] { readValueId },
            cancellationToken
        );

        // Check if the read was successful
        if (readResponse != null && readResponse.Results != null && readResponse.Results.Count > 0 && StatusCode.IsGood(readResponse.Results[0].StatusCode))
        {
            Console.WriteLine($"Value of MyVariable: {readResponse.Results[0].Value}");
            return readResponse.Results[0].Value;
        }
        else
        {
            Console.WriteLine("Failed to read the variable value.");
            return false;
        }

    }

    private async Task<bool> WriteVariableAsync(Session session, NodeId nodeId, object value, CancellationToken cancellationToken = default)
    {
        try
        {
            // Create a WriteValue object with the NodeId, AttributeId, and the value to be written
            WriteValue writeValue = new WriteValue
            {
                NodeId = nodeId,
                AttributeId = Attributes.Value,
                Value = new DataValue(new Variant(value)),
            };

            // Create an array of WriteValue objects
            WriteValueCollection writeValues = new WriteValueCollection
            {
                writeValue
            };

            // Use the WriteAsync method to write the value to the server
            WriteResponse writeResponse = await session.WriteAsync(
                null,
                writeValues,
                cancellationToken
            );

            // Check if the write was successful
            if (writeResponse != null && writeResponse.Results != null && writeResponse.Results.Count > 0
                && StatusCode.IsGood(writeResponse.Results[0]))
            {
                Console.WriteLine("Write operation successful.");
                return true;
            }
            else
            {
                Console.WriteLine($"Failed to write to the variable.");
                return false;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error during write operation: {ex.Message}");
            return false;
        }
    }


    static async Task Main()
    {

        // Define the endpoint URL of the OPC UA server
        string endpointUrl = "opc.tcp://xx.xx.xx";  

        // Define the credentials (username and password) for authentication
        string username = "xxxx";
        string password = "xxxx";
        UserIdentity userIdentity = new UserIdentity(username, password);

        // Load the certificate from a file
        X509Certificate2 certificate = new X509Certificate2(@"C:\xxxx\xxxx.der");



        // Create the OPC UA application configuration
        ApplicationConfiguration config = new ApplicationConfiguration
        {
            // Configure other settings as needed
            // ...
            ClientConfiguration = new ClientConfiguration
            {
                DefaultSessionTimeout = 60000,
            },

            // Set the user identity for authentication
            SecurityConfiguration = new SecurityConfiguration
            {
                ApplicationCertificate = new CertificateIdentifier 
                {   
                    
                    Certificate = certificate,
                },
                AutoAcceptUntrustedCertificates = true,
                RejectSHA1SignedCertificates = true, // Reject SHA-1 signed certificates
            },

        };




        // Create an OPC UA session with the server

        using (var session = await Session.Create(config, new ConfiguredEndpoint(null, new EndpointDescription(endpointUrl)), true, "", 60000, userIdentity, null))
        {
            // Now you can interact with the server using the 'session' object

            Program program = new Program();

            
            //Read a variable
            NodeId nodeId = NodeId.Parse("ns=4;s=xx.xxx.xx .Application.Rx_from_Client.Order");

            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            object value = await program.ReadVariableAsync(session, nodeId, cancellationToken);


           


        }
    }


}

Changed different certificates but cant find the solution.

Those are the commands to create the certificate on OpenSSL

> openssl genpkey -algorithm RSA -out client_key.pem
> openssl req -new -key client_key.pem -out client_csr.pem
> openssl x509 -req -in client_csr.pem -signkey client_key.pem -out client_cert.pem
> openssl x509 -req -in client_csr.pem -CA ca_cert.pem -CAkey ca_key.pem -CAcreateserial -out client_cert.pem
> openssl x509 -in client_cert.pem -outform der -out client_cert.der
1

There are 1 best solutions below

2
Schroeder On

You have to read the manuel of the opc ua server. There must be away to trust certificates. The server must trust your certificate. Also check if the certificate contains the urn of your application as first parameter of SubjectAlternateName and a matching DNS name as second parameter.

Can you post your script to create the certificate?