gopcua / opcua

Native Go OPC-UA library
MIT License
822 stars 251 forks source link

Trouble with calling NewClient() #716

Open justnat3 opened 3 months ago

justnat3 commented 3 months ago

Hey, i've been running into something quite strange (running go 1.22.1 windows/amd64)

I've tried this on linux, and a couple of different versions of go, I get the same result. I also tried creating a certificate on my machine, and within go using crypto/x509.

I inlined the code from setCertificate() which works. However when creating a new client it only tells me that I have a "malformed certificate" which to me looks like the same code.

Is there something I am doing wrong here?

func main() {

    // creates a valid x509 certificate, and a private key
    cert, priv := GenerateCertWithKey() // ([]byte, *rsa.PrivateKey)

    // this succeeds, the same code called in (gocpua)setCertificate()
    parsedCert, err := x509.ParseCertificate(cert)
    if err != nil {
        log.Fatalf("Failed to parse certificate: %s", err)
        return
    }

    // Produces the correct output
    log.Println(parsedCert.URIs)

    ctx := context.Background()

    // This fails parsing the certificate
    c, err := opcua.NewClient(
        Endpoint,
        opcua.SecurityMode(ua.MessageSecurityModeSignAndEncrypt),
        opcua.SecurityPolicy("Basic256Sha256"),
        opcua.PrivateKey(priv),
        opcua.Certificate(cert),
    )

    if err != nil {
        log.Fatal(err)
    }

    defer c.Close(ctx)
    err = c.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
}
Dipp3r commented 2 weeks ago

Hi, I tried reproducing this issue in my environment and found that the error("malformed certificate") you are receiving is completely unrelated to the certificate you are generating. You may have to add other options as part of your client instance opcua.SecurityFromEndpoint(ep, ua.UserTokenTypeAnonymous) and opcua.AuthAnonymous() if you are trying to set an anonymous connection to the server.

Below are the client logs with and without these options:

// your case

opts := []opcua.Option{
  opcua.SecurityMode(ua.MessageSecurityModeSignAndEncrypt),
  opcua.SecurityPolicy("Basic256Sha256"),
  opcua.CertificateFile(certFile),
  opcua.PrivateKeyFile(keyFile),
}

2024/06/19 22:49:01 ❌ Error while setting up a connection "opc.tcp://localhost:port/server-name" 2024/06/19 22:49:01 x509: malformed certificate exit status 1

// with authType set to anonymous

opts := []opcua.Option{
  opcua.SecurityMode(ua.MessageSecurityModeSignAndEncrypt),
  opcua.SecurityPolicy("Basic256Sha256"),
  opcua.SecurityFromEndpoint(ep, ua.UserTokenTypeAnonymous),    // ep is the endpointDescription returned by the SelectEndpoint method
  opcua.AuthAnonymous(),
  opcua.CertificateFile(certFile),
  opcua.PrivateKeyFile(keyFile),
}

2024/06/19 22:48:22 ✅ Connected to the server with endpoint "opc.tcp://localhost:port/server-name" exit status 1