Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENG-2386: implement "encryption" certificates for "encrypted" connection #123

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

led0nk
Copy link
Member

@led0nk led0nk commented Feb 4, 2025

Description:

What we are trying to achieve here:

  • implementation of Basic256Sha256
  • implementation of Basic256 (depracated)
  • implementation of Basic128Rsa15 (depracated)

User flow:

  • set an input.yaml e.g.:
input:
  opcua:
    endpoint: <your-endpoint>
    username: ''
    password: ''
    subscribeEnabled: true
    useHeartbeat: true
    securityMode: SignAndEncrypt
    securityPolicy: Basic256Sha256
    nodeIDs:
      - i=2255

important: set the fields securityMode and securityPolicy

  • benthos-umh logs will then show a warning, since the connection is not successfull but we also print out an info-message to tell the user he has to trust the client on the server-side
  • when he trusted the client's certificate (which is specified in the info-message via application-uri, benthos-umh will retry connection and then get the specified nodes / browse first

The easiest way for user-experience would be to set the option Trust all clients in the OPC-UA-Servers configuration, which depends on the Software you're running on.

Examples:

Basic256Sha256

Basic256Sha256-kepware
See the logs of this run here:
basic256sha256.log

Basic256

Basic256-kepware
See the logs of this run here:
basic256.log

Basic128Rsa15

Basic128Rsa15-kepware
basic128rsa15.log

What needs to be done here

  • testing with Siemens-OPC-Server failed due to Siemens-settings (doesn't even work with UAExpert)
  • testing with Prosys-OPC-Server failed due to Prosys-settings (doesn't even work with UAExpert)
  • rewrite ginkgo-tests for encryption

As an outlook:

  • maybe silently try to connect / or with a limited amount of times without erroring out (maybe within every 5 seconds) so that we don't instantly throw out an error here:
    func (g *OPCUAInput) connectWithSecurity(ctx context.Context, endpoints []*ua.EndpointDescription, authType ua.UserTokenType) (*opcua.Client, error) {
    foundEndpoint, err := g.getEndpointIfExists(endpoints, authType, g.SecurityMode, g.SecurityPolicy)
    if err != nil {
    g.Log.Errorf("Failed to get endpoint: %s", err)
    return nil, err
    }
    if foundEndpoint == nil {
    g.Log.Errorf("No suitable endpoint found")
    return nil, errors.New("no suitable endpoint found")
    }
    opts, err := g.GetOPCUAClientOptions(foundEndpoint, authType)
    if err != nil {
    g.Log.Errorf("Failed to get OPC UA client options: %s", err)
    return nil, err
    }
    c, err := opcua.NewClient(foundEndpoint.EndpointURL, opts...)
    if err != nil {
    g.Log.Errorf("Failed to create a new client: %v", err)
    return nil, err
    }
    // Connect to the selected endpoint
    if err := c.Connect(ctx); err != nil {
    _ = g.Close(ctx)
    g.Log.Errorf("Failed to connect: %v", err)
    return nil, err
    }
    return c, nil
    }

-> this would lead to benthos retrying to connect every 5 seconds, which makes it much harder for the user to get the correct application-uri from the logs (as you can see in all of the provided logs)

Copy link
Contributor

coderabbitai bot commented Feb 4, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

seeded private-key

impl SignatureAlgorithm

cmt changes
Copy link
Member

@JeremyTheocharis JeremyTheocharis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall Impressions

  • Great Feature Work:
    The implementation of encryption certificates for Basic256Sha256, Basic256, and Basic128Rsa15 is a key step for securing OPC UA connections. The work is promising and sets a strong foundation for future enhancements.

  • User Experience Focus:
    Although this is a security feature, it’s crucial that even non-security experts can understand and use it. The logs, configuration messages, and documentation should be clear, friendly, and guide the user seamlessly—mirroring the user-centric experience of products like Apple and Linear.

Detailed Technical Feedback

  1. Certificate Generation & Seed Handling (opcua_plugin/connect.go & generate_cert.go):

    • Random String Length:
      Increase the default certificate seed random string length from 8 to 64 characters for better entropy.
    • User Messaging:
      Log a clear message that includes a copy-paste-ready configuration snippet when a random certificate seed is generated. For example:
      "The client certificate was generated randomly upon startup and will change on every restart. To use the current dynamically generated certificate as a fixed certificate, copy the following configuration snippet into your config: certificateSeed: "<generated_seed>"." (where generated_seed is the current auto-generated g.certificateSeed)
  2. Configuration & Documentation (opcua_plugin/opcua.go):

    • Rewording of the certificateSeed Field:
      Update the description to:
      "The certificate seed is used to deterministically generate the client certificate when using encryption. If not set, a new (random) certificate will be generated at every restart, requiring the OPC UA server to trust all client certificates. For a fixed certificate, set this value to a fixed random string of at least 64 characters."

Example:

if g.CertificateSeed == "" {
            // Generate a 64-character random seed if none is provided
            g.CertificateSeed = randomString(64)
            // Prepare a configuration snippet for the user to copy into their config
            configSnippet := fmt.Sprintf("certificateSeed: \"%s\"", g.CertificateSeed)
            g.Log.Infof("The client certificate was generated randomly upon startup and will change on every restart.\n"+
                "To use a fixed certificate, please copy and paste the following line into your configuration:\n%s", configSnippet)
        }

Here an example for the README:

Encryption Certificates & Certificate Seed

To enhance the security of OPC UA connections, benthos-umh now supports generating client certificates when using encryption. This feature operates in two modes:

  1. Dynamic Mode (Default):
    If no certificate seed is provided, benthos-umh automatically generates a new random certificate seed (64 characters long) at each startup. This results in a new client certificate every time the service restarts, meaning the OPC UA server must be configured to trust all client certificates.

  2. Fixed Mode:
    For environments where the OPC UA server requires each client certificate to be explicitly trusted, you can set a fixed certificate seed. By providing a fixed random string (of at least 64 characters) via the configuration, the client certificate will be deterministically generated on every startup, ensuring consistency.

How It Works

When operating in Dynamic Mode, the application logs a clear message that includes a copy-paste-ready configuration snippet. For example, you might see a log message like this:

Client Certificate Notice:
The client certificate was generated randomly upon startup and will change on every restart.
To use the current dynamically generated certificate as a fixed certificate, copy the following configuration snippet into your config:
certificateSeed: "REPLACE_WITH_GENERATED_SEED"

Simply copy that line into your configuration file to lock the certificate to the current seed, ensuring that the same certificate is generated on every restart.

Configuration Example

Below is an example of how to set up the OPC UA input with a fixed certificate seed in your benthos.yaml:

input:
  opcua:
    endpoint: 'opc.tcp://localhost:46010'
    nodeIDs: ['ns=2;s=IoTSensors']
    securityMode: SignAndEncrypt
    securityPolicy: Basic256Sha256
    certificateSeed: "your-fixed-64-character-random-string"

Replace "your-fixed-64-character-random-string" with a secure, random string that is at least 64 characters long. If you leave out the certificateSeed field, benthos-umh will generate one automatically at startup, which means the client certificate will change with every restart.

g.Log.Errorf("Failed to generate certificate: %v", err)
return nil, err
}
// Generate certificates if we don't connect without Security
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe no double negation? Generate certificates, when we connect with security

}
// cache the tls.Certificate for future calls
g.cachedTLSCertificate = &cert
g.Log.Infof("The clients certificate was created, to use an encrypted connection "+
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this only make sense when the certificate seed was choosen by the user / is fixed. if its random, it will not work

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if its random, you can instead output:

The client certificate was generated randomly upon starting up, and will change upon every restart. In order to fix it, e.g., to trust the client certificate in the server, please set the certificateSeed cofniguration variable to a random 64 length string (e.g., generated by a random generator) or alternatively use this to fix the current certificate: %s), (g.CertificateSeed)

@@ -46,7 +47,8 @@ var OPCUAConfigSpec = service.NewConfigSpec().
Field(service.NewBoolField("useHeartbeat").Description("Set to true to provide an extra message with the servers timestamp as a heartbeat").Default(false)).
Field(service.NewIntField("pollRate").Description("The rate in milliseconds at which to poll the OPC UA server when not using subscriptions. Defaults to 1000ms (1 second).").Default(DefaultPollRate)).
Field(service.NewBoolField("autoReconnect").Description("Set to true to automatically reconnect to the OPC UA server when the connection is lost. Defaults to 'false'").Default(false)).
Field(service.NewIntField("reconnectIntervalInSeconds").Description("The interval in seconds at which to reconnect to the OPC UA server when the connection is lost. This is only used if `autoReconnect` is set to true. Defaults to 5 seconds.").Default(5))
Field(service.NewIntField("reconnectIntervalInSeconds").Description("The interval in seconds at which to reconnect to the OPC UA server when the connection is lost. This is only used if `autoReconnect` is set to true. Defaults to 5 seconds.").Default(5)).
Field(service.NewStringField("certificateSeed").Description("The certificate seed is a secret string provided by the user, which will then get hashed to create the clients certificate. This is needed to ensure an explicit trusted client, which is significant for an encrypted connection. If not set, this will be provided by a random created string.").Default(""))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we put that into the README as well? Maybe also rename that:

The certificate seed is used to deterministically create the client certificate when using encryption. If not set, then the certificate will be random upon restart, which means the server must trust all client certificates. If the server requires to trust each single client certificate, then the certificate seed must be set to a random (but therefore fixed) string with at least 64 characters.

if g.CertificateSeed == "" {
// Generate an 8-character random string if no 'certificateSeed'
// provided by the user.
g.CertificateSeed = randomString(8)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would increase the random string from 8 to 64

.DS_Store Outdated
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants