Commit Graph
368 Commits
Author SHA1 Message Date
romanett 4a44238b8c [Server] Allow Subject Name Change of Application Certificate in GDS Push scenario (#2833)
* allow Subject Name change

* modifiy subject names in push test
2025-01-21 12:23:14 +02:00
romanett 760bfd92bc [Server] Fix: Return full CertificateChain after Certificate Update (#2861)
* simpler update process

* update endpoint descriptions

* adress review feedback

* cleanup
2025-01-13 17:17:15 +02:00
mtx500 57d638ea90 Typos again (#2906)
* Fixed a lot of typos in comments, strings and local variable names. No changes to misspelled function names/parameters.

* Fixed some more typos
2024-12-20 09:33:13 +02:00
Stephan Larws 5b3f91d9dd Handle status code Uncertain according to the specification (#2898)
* #2896: Write output arguments for good and uncertain status code

When a method state's call method is invoked the output arguments should be written in case the status code is good or uncertain. This behavior would be conform with the current specification.

* #2896: The service result corresponds the method call result

The result of the Call method in the CustomNodeManager2 class represents the status of the CallMethodResult. It does not correspond to the ServiceResult of the CallResponse, thus returning Good as a general response is incorrect behavior.
2024-12-17 13:38:51 +02:00
Martin Regen 5ed73fcd95 merge latest release 2024-12-07 17:30:58 +01:00
romanett 67a0df1960 Fix read of NodeId attribute AccessRestrictions by casting return type from Enum to ushort (#2883)
In the read NodeId servcie call an enum is by default cast to Int32, so the cast to ushort is needed here to return the expected type for the AccessRestrictions.
2024-12-05 08:39:09 +01:00
Suciu Mircea AdrianandMartin Regen d0e89a3bf1 Support mutual TLS on server https endpoints (#2849)
A new configuration variable 
    <HttpsMutualTls>true</HttpsMutualTls>
enables the mutual TLS authentication support. The behavior of the TLS endpoint changes as the following:

HttpsMutualTls is true:
The server checks the trust on the certificate which is used by the client for TLS authentication. It must be a valid OPC UA application certificate which is trusted.
A client can still connect without providing a client certificate, but then it is only able to call discovery services.
In order to create a session, the client must use the same application certificate that was used for the TLS channel.

HttpsMutualTls is false:
- There is no application authentication. The server endpoint uses security None and there is no client application authentication.
Instead, only user authentication is used to secure the server, anonymous user authentication is disabled.
Discovery service calls are supported.

Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-12-03 12:43:39 +01:00
Archie Miller ab364b9e98 Update CauseMappings to reflect issue (#2877)
SyspendedToRead caused by Reset remains as per Part 10 Table 7
2024-12-03 10:23:56 +01:00
Archie Miller 6925e1560f Update CauseMappings to reflect issue (#2877)
SyspendedToRead caused by Reset remains as per Part 10 Table 7
2024-12-03 10:03:29 +01:00
Martin RegenandMarc Schier 1fa0b7f26e Register callback to notify about new channel token activation (#2872) (#2873)
For better client diagnostic it is important to have access to the channel token. Today tooling must monitor the channel token change to be aware of the current token, it is more efficient for the tooling to be called back when the token changes. This can be now accomplished in that the owner of a client (Discovery, Session) can retrieve the Transport channel after connect, read the current token and register a change callback.

* Add OnTokenActivated event for token change notifications

Added a new event `OnTokenActivated` to the `UaChannelBase` class in the `Opc.Ua` namespace to notify when a channel token is activated. Implemented this event in the `HttpsTransportChannel` class within the `Opc.Ua.Bindings` namespace. Introduced a protected internal `OnTokenActivated` event handler in the `UaSCBinaryChannel.Symmetric` class, invoked during token changes in the `ActivateToken` and `DiscardTokens` methods. Cleaned up the event handler in the `Dispose` method of the `UaSCBinaryClientChannel` class. Registered the event handler with the internal channel in the `UaSCBinaryTransportChannel` class. Added a new delegate `ChannelTokenActivatedEventHandler` in the `ITransportChannel` interface and updated the interface to include the `OnTokenActivated` event. Made minor formatting and comment adjustments for improved readability and consistency.

* Include channel in callback

Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
2024-12-02 11:21:07 +01:00
Marc Schier 6aedc787b8 Register callback to notify about new channel token activation (#2872)
For better client diagnostic it is important to have access to the channel token. Today tooling must monitor the channel token change to be aware of the current token, it is more efficient for the tooling to be called back when the token changes. This can be now accomplished in that the owner of a client (Discovery, Session) can retrieve the Transport channel after connect, read the current token and register a change callback.

* Add OnTokenActivated event for token change notifications

Added a new event `OnTokenActivated` to the `UaChannelBase` class in the `Opc.Ua` namespace to notify when a channel token is activated. Implemented this event in the `HttpsTransportChannel` class within the `Opc.Ua.Bindings` namespace. Introduced a protected internal `OnTokenActivated` event handler in the `UaSCBinaryChannel.Symmetric` class, invoked during token changes in the `ActivateToken` and `DiscardTokens` methods. Cleaned up the event handler in the `Dispose` method of the `UaSCBinaryClientChannel` class. Registered the event handler with the internal channel in the `UaSCBinaryTransportChannel` class. Added a new delegate `ChannelTokenActivatedEventHandler` in the `ITransportChannel` interface and updated the interface to include the `OnTokenActivated` event. Made minor formatting and comment adjustments for improved readability and consistency.

* Include channel in callback
2024-12-02 09:48:54 +01:00
Martin Regen 0a4804f4c5 Client perf and memory improvements for JSON encoding and subscriptions (#2864)
- reduce EscapeString overhead in JSON encoder
- client monitored items: allocate queues only if needed
- replace SortedDictionary with Dictionary for perf reasons
- revert a change in padding and reduce a log level
2024-11-28 21:32:55 +01:00
Suciu Mircea Adrian 3543d02925 Added a minimal rogue client detection mechanism at the transport level (#2850)
Clients that are failing too often to pass the security validationin a certain interval of time with the Basic128 security profile are now tracked and blocked.
2024-11-22 10:01:30 +01:00
Martin Regen 76b53184de ChannelToken: Dispose HMAC and improve lifetime calculations. (#2846)
- Channels are not disposed (client and server)
- During long running tests an HMAC object leak was observed.
- The HMAC and SymmetricSign objects were not disposed after use, leading to a small incremental memory leak per key renewal. 
- The channel token lifetime is calculated by the system clock, which can change. Instead use the continous HiResClock.TickCount to calculate the lifetimes.
- Token renewal and connection requests are not removed from the request dictionary

Improvements:
- Make ChannelToken disposable. Dispose channels.
- Dispose HMAC and SymmetricSign objects after use.
- Use TickCount to calculate key renewal and key expiry.
- Introduce a 5% jitter to the token renewal timer, to avoid token renewal storms.
- Reduce the allocation per use of the HMAC objects by using ReadOnlySpan and avoid MemoryStream.
2024-11-21 10:16:13 +01:00
Suciu Mircea AdrianandMartin Regen f001eabcc8 Add support for ECC profiles (#2398)
- Port support for ECC NIST/Brainpool profiles from prototyping_ecc branch
- Implement CertProvider to load certs per connection / profile
- Backward compatibility of configuration for existing apps
- SecurityConfiguration specifies app cert types for each profile
- Autodetect the ECC support for brainpool/nist based on platform (mac OS 10 doesn't support brainpool)
- ECC supported on net48 / net5.0 / net 6.0 / netstandard2.1
- ECC supported on windows / linux / macOS (brainpool not < macOS11)
- Self signed certs for each profile are created on start similar to RSA
- RSA only profiles are supported on .NET standard 2.0

Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-10-17 16:02:20 +02:00
romanett 014808e5d8 [Server] update endpoint descriptions after certificate update (#2735)
- Update the Server Endpoint Descriptions after certificate update e.g. from a GDS Push.
Until this PR the server needed a restart.
2024-10-10 19:35:21 +02:00
Martin Regen 41363bd1e1 Release testing: Fix channel remove issue and channel exhaustion on reconnect (#2749)
- During a reconnect fault the channels remain open and are quickly exhausted. Immediately close channels in Opening state similar to channels in Connecting state instead of waiting for timeout cleanup.
- The channel concurrentDictionary sometimes failed to remove a channel. Removing ContainsKey and retry with TryAdd fixes the problem.
2024-09-06 17:07:06 +02:00
Martin RegenandLuis Cantero 6dcee7ebf1 Fix a deadlock in binary channel on cleanup, reduce contention due to locks on high server load (#2714)
Server: Fix a deadlock in the binary channel cleanup (regression from secure channel cleanup)
Server: Use ConcurrentDictionary for sessions and channels to reduce locking overhead
Server: Replace legacy implementation of NodeIdDictionary with standard dictionary, as with IEqualityComparer the look up is much faster than specialized SortedDictionary for each NodeId Type.

Co-authored-by: Luis Cantero <luis@cantero.org>
2024-08-24 09:37:36 +02:00
Martin Regen 9b0e48054b Improve reconnect error messages, misc. small improvements (#2719)
Add the reconnect exception text to the log message, otherwise the exception is filtered out.
Turn off the trace logging in tests, as it causes timeout issues on some ci VMs
reduce callbacks if client reconnect and call AddItems
Fix BadNothingToDo when Loading dictionaries
Revert benchmark.net to v13 due to weird build dependency issues with 14.x
2024-08-21 17:27:35 +02:00
Martin Regen 6291ed6b33 Server SDK mistakenly uses SendBufferSize as ReceiveBufferSize and vice versa (#2718)
Fix the hello message, if the send and receive buffer size is different.
The error was undetected as long as send and receive buffer size were the same size.
Ensure the right values are used for client and server and add some more sanity checks on buffer sizes.
2024-08-19 08:06:47 +02:00
ThomasNehring fd762bf9eb Managed Browse and Browse Next for the UA client. (#2673)
Added a new method ManagedBrowse to the UA  client, which takes care of calling browse next after calling browse, when necessary. It also handles the status codes BadNoContinuationPoint and BadInvalidContinuationPoint.

Added support for the new method in ISession, TraceableSession, Session and SessionAsync.

Use the new methods in the NodeCache and other API that use browse (FetchRefrences etc).

Added unit tests which verify correct behavior of the new methods.
2024-08-18 03:36:21 +02:00
Martin Regen 1032d719da More fuzz targets for binary and Xml decoders (#2621)
- let all Xml encoders and decoders follow the dispose pattern, similar to all the other encoders.
- Add fuzz targets for Xml and binary indempotent fuzzer.
- add a ReadOnlySpan<byte> signature for WriteByteString
- add ArrayPool based IBufferWriter<byte> to support encoding of large byte string with buffers
- add Azure DevOps ci pipeline tests with known artifacts that caused fuzzing errors, to catch regressions.
2024-08-05 08:35:58 +02:00
Martin Regen c4cf54c595 Fix NodeId compare found by fuzzer, Bump Asn1 Nuget due to security update (#2669)
* fix nodeid compare found by fuzzer
* bump security Nuget updates for ASN.1
2024-07-11 09:55:49 +02:00
Michi 332ed1ded9 Fix: RegisterServer and RegisterServer2 do not initiate connection (#2664) 2024-07-02 16:30:21 +02:00
Martin Regen be3a3b0be3 Fix exception in TcpTransportlistener OnAccept call (#2661)
Check for m_channels null value in the OnAccept, it could be already disposed.
2024-07-01 16:18:47 +02:00
Martin Regen defd048d13 Fix macOS build, move https client transport back to core and other maintenance, (#2659)
- change macOS 11 ci builds to newer ones, macOS 11 is deprecated
- fix Opc.Ua.Client EventSource message numbering
- bump nerdgit to 3.6.139
- include .NET Standard 2.0 builds back in Nuget packages for client and server (complex type support requires netcoreapp2.1 which is end of life)
- include .NET Framework 4.7.2 as lowest supported .NET Framework platform
- move https client channel back to core library, as it requires only netstandard2.0 and has no other dependencies. 
- Opc.Ua.Https is now only needed for a https server with kestrel.
- fix security warning for system.private.uri
- upload Quickstarts.Servers to the preview feed to allow use in the samples repo and avoid duplicate codebase
2024-06-28 11:00:17 +02:00
Martin Regen b33c250c2f Fix special case for reconnect without activate (#2643)
-Due to a race condition the channel may never reconnect
-Remove a session.dispose in keep alive which caused flaky tests as a side effect
2024-06-11 10:37:28 +02:00
romanett 8a0349ef9c [Client] select the most secure User Identity Token if a server offers multiple ones (#2611)
This fix makes the client select the most secure UserIdentity Token if a server offers more than one.
Before the client just selected the first UserIdentity Token offered by the server.
Also calculate the security level by the client, as the unsecure response of a server could be spoofed.
2024-06-05 07:13:30 +02:00
romanett 8a1df6d3dc [Client] Fix UserIdentity for CertificateIdentifer & add parameter for console reference client to specify UserCertificate (#2624)
- Fix the UserIdentity constructor to load the private key of a provided certificateIdenifier.
- make UserIdentity constructor throw a ServiceResultException when a Certificate with no private key is specified.
- extend console reference client with two new parameters:
   -uc Thumbprint of a user certifiate located in the TrustedUserCertificatesStore
   -ucp Password of the private key of the user certificate
- add documentation for console reference client
2024-06-05 07:10:07 +02:00
Martin Regen ebf8f6265d Fix reopen secure channel without activate (#2577)
Fix that if a socket is closed, new service calls are queued and a new channel is established without reconnect / activate.
Add some logic which ensures that a BeginConnect operation is only started if a valid service call is queued first.
The activate is prepared by the session reconnect handler which may take some time to respond. Until then, all other service fail immediately with BadNotConnected.
To detect socket failures earlier, the PublishRequest and KeepAlive send are also hooked up to the KeepAliveError to trigger a reconnect. To disable the keep alive timing calcualtion, an additional variable tracks the statuscode of the last error to set KeepAliveStopped to true.
2024-06-02 19:05:17 +02:00
Martin Regen 52d4492ccc Set TCP defaults for max message size to align with min buffer size (#2616)
* Avoid user configuration errors by setting unaligned max message size values, fix defaults.
* Set the MaxMessageSize defaults to multiple of MinBufferSize to avoid rounding errors in other UA implementations.
2024-05-13 07:34:55 +02:00
Martin Regen 7a04a4b396 Add UA Fuzzer solution for afl-fuzz and libfuzzer (#2603)
- Add a solution to provide fuzzer support for afl-fuzz and libfuzzer.
- Add fuzz targets for Binary, Json and Xml encoder and decoder fuzzing. For afl-fuzz and libfuzzer.
- Fix issues in encoders and decoders when unexpected exceptions are returned. The expectation is to return only ServiceResultException with BadDecodingError, BadEncodingError or BadEncodingLimitsExceeded.
- Add a tool to create Testcases. 
- Add a tool to playback crashes and timeouts.
- Solution is extensible with common files to discover new fuzz targets by reflection. New fuzz projects can share many files with the first project.
- Breaking change: Fix how BinaryDecoder is used: Previously, calling close on the BinaryDecoder implicitly disposed the stream. Change behavior so that `using` pattern can be applied across the board.
2024-05-02 22:29:29 +02:00
Suciu Mircea AdrianandMartin Regen d1a9baa6c6 Added a limit to the Channels on the server side and removed "stale" channels (#2540)
* Added MaxChannelCount and detect and cleanup "stale" channels based on ChannelLifetime
* Add Environment.TickCount as time reference
* Set a socket backlog value to avoid socket open overflow
* Added a ChannelKeepAlive to signal when a session is still active
* Add options to console client to leak channels and run connect loop forever

Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-04-22 13:28:19 +02:00
romanett 884ddf38b2 Remove unnecessary casts to RoleBasedIdentity when checking for WellKnownRoles (#2578)
* Improve casts to RoleBasedIdentity when checking for WellKnownRoles
* make IUserIdentity immutable
* add temp variable to make operation thread safe
2024-04-11 08:25:51 +02:00
mtx500 cf7f2219a1 Fixed Typos. No functional changes. (#2581)
* Fixed typos across the board. No functional changes.
2024-04-11 08:21:16 +02:00
Martin Regen ebb55ad25e Improve ArraySegmentStream with ReadOnlyMemory/Span signatures, avoid extra alloc/copy (#2556)
- Implement `int Read(Span<byte> buffer)` and `void Write(ReadOnlySpan<byte> buffer)` in ArraySegmentStream
- for ArraySegmentStream streaming lower the CPU load for .NET8 OPC UA binary encoding/decoding by 50%
- Implement dispose to return buffers that were not transferred. 
- Implement a GetSequence in ArraySegmentStream
2024-03-29 11:50:55 +01:00
Tamás Kleizer d06231a813 Sensitive information redaction (#2545)
Added redaction (disabled by default)
Added redaction strategies for username, password, endpoint, and exception message.
Updated logging to use redaction where it was critical
2024-03-27 14:29:11 +01:00
Martin Regen ec05e8aaac Accept abort message in early message type check (#2557)
In #2510 a message type check was added to catch non UA service connections earlier.
But the Abort message type was missing in the check, so an Abort caused a disconnect.
However, in such a case the transport can just continue with the next message.
2024-03-26 18:08:03 +01:00
Lauri Saurus 3f29a72a37 Make NodeState classes thread safe (#2372)
NodeState classes are not thread safe. In many places event handlers are handled in a manner that can cause NullReferenceException in a case of a bad timing. In addition, in some places non-thread-safe collections are iterated which could cause issues if the collections are changed at the same time.

This PR addresses the aforementioned issues by using local variables for event handlers and then making null check and calling them. When applicable null-conditional operators are used. Non-thread-safe collection iteration is guarded by locking. The issues were reproduces with unit tests part of this PR and also the fix was verified by running the same unit tests.
2024-02-29 16:03:50 +01:00
Martin Regen 988be41a87 Reduce locking in secure channel client send/receive codepath (#2531)
During high load there were a few portions in the send/receive pipeline identified which may cause lock contention and thread starvation due to locks:

- Remove lock for the codepath when a incoming message is processed.
- Add a concurrent dictionary to allow for the processing of OperationCompleted and to add new requests without locking
- Allow to process normal service requests without locking

Due to the change it is possible to send KeepAlive even when a incoming message is received.
2024-02-28 09:00:07 +01:00
mtx500 d95e5fae1d Typos in names of functions. Breaking change! (#2523)
* Fixed typos in names of functions, some in public API. This may be a breaking change.
2024-02-20 16:12:52 +01:00
Martin Regen 61edad9d63 Ensure endpoints are returned when alternate url port does not match (#2511)
- fix NormalizeHostName when host ip addresses are not returned on macOS, try the native hostname
- Ensure endpoints are returned even if the client url port do not match (similar to client)
- Improve endpoint tests
2024-02-17 07:31:10 +01:00
Martin Regen 2b9d8f9de5 Fix warnings, no functional changes. Improve globalization. (#2445)
Fix warnings regarding localization, CLS compliance, performance. No functional changes.

Many but not all adressed:
CA1859
CA1868
CA1305
CA1310
CA1861

- based on the discussion, use IFormatProvider where appropriate in ToString
2024-02-14 17:17:21 +01:00
Martin Regen f8f157188f Check for bad chunk headers and provide remote endpoint in IMessageSocket (#2510)
- Reduce socket log output and demote to Trace
- Check for invalid chunk header and reduce log output
- Close socket immediately if a bad chunk header is detected (e.g. if socket is opened by another protocol)
- Expose Remote endpoint for application
2024-02-14 17:11:19 +01:00
mtx500 339cd24b4b Fixed typos in file names. (#2519)
Fixed typos in file names: renamed some files and amended corresponding project file
2024-02-14 06:49:46 +01:00
Martin Regen ca8aa1d3f0 Simplify BeginConnect (#2512)
- Simplify the BeginConnect implementation, which is an artifact to support IPv6 on .NET Standard 1.3 and UWP. 
- Dual stack is supported by .NET, and the DNS resolution in the socket layer can be delegated to the platform.
- Fixes a race condition under high load, when BeginConnect throws a `Socket already connected` error.
2024-02-13 08:45:22 +01:00
mtx500 d2e436d340 Fix typos in comments, strings and local variable names. No functional changes. (#2507)
Fixed a lot of typos in comments, strings and local variable names. 
No change to misspelled function names and file names.
2024-02-10 07:49:05 +01:00
Suciu Mircea Adrian d573eaa01b Fix TranslateEndpointDescriptions (#2495) 2024-02-06 14:12:14 +02:00
bhnaphade 6ff65020a4 Updated activity creates on server to set partent activityContext (#2491)
Update activity creation on server side so that OTEL can capture parent information
2024-02-01 13:48:18 +01:00
Martin Regen f46b0556bd Add small breaking API changes to .373 release / revert or improve a few changes from 116-preview (#2474)
- return serviceResult from client Session.Republish API (Breaking API change)
- refactor #2447.  move SessionCreated virtual callback to end of Session.Create.
- fix bug in timeouthint calculation (always 0)
- do not print error if BadSequenceNumberUnknown is returned (server may have cleaned up himself)
- allow for a acktosend threshold when publish response requests are processed out of order
- revert EndAsync call to not throw timeout exception
- use static Randomgenerator instance in X509PfxUtils
- Print suppressible Certificate validation failed errors only if not auto accepted or accepted in callback.
2024-01-26 06:24:51 +01:00