Commit Graph

730 Commits

Author SHA1 Message Date
Martin Regen 663ed10285 Remove unnecessary dependency on System.Net.Http (#2610)
* Update Opc.Ua.Bindings.Https.csproj
* The library is not necessary!
2024-05-04 06:10:14 +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
mtx500 8143767c3b Serialization of floating point values to XML: Remove superfluous handling of special values (#2588)
* Serialization of floating point values to XML: Remove superfluous handling of special values

NegativeInfinity and NaN
In OPC UA the serialization of floating point values to XML just follows the XML Schema specification (see https://www.w3.org/TR/xmlschema-2/#float). It is sufficient to use the correct .NET XML classes (XmlReader, XmlWriter, XmlConvert). There is no need to treat the special values Infinity, negative Infinity and Not-a-number in special way.

XmlWriter uses XmlConvert internally (see https://referencesource.microsoft.com/#System.Xml/System/Xml/Core/XmlWriter.cs and https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs), and XmlConvert (see https://referencesource.microsoft.com/#System.Xml/System/Xml/XmlConvert.cs and https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs) first takes care of "INF" and "-INF" and then uses the Single / Double routines with the appropriate flags and culture set so that "NaN" is also taken care of.

the removed code parts were inconsistent:
- not all routines contained the special treatment of the special values
- Double values were set with the special Single constants

* Added a unit test for XmlEncoder and XmlDecoder regarding the float and double special values PositiveInfinity,
2024-04-27 20:37:49 +02:00
Suciu Mircea Adrian 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 ca848af366 Reenable .NET Standard 2.0 builds for core library (#2570)
- add netstandard2.0 support back to the core and cert library, to allow to build .NET analyzers
- add custom build steps for .NET 4.7.2
2024-04-03 06:43:44 +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 2bae83414d Set cert validator property may deadlock in semaphore (#2555)
When property is set, call internal update to avoid deadlock (2 properties affected)
2024-03-26 18:09:32 +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
romanett 48fd872e6e fix Role Permissions of Method UnregisterApplication & Add Parameter to CertificateStoreIdentifier OpenStore Method (#2558)
Fix allowed Roles of Method Unregister Application allow Application Self Admin Privilge:
https://reference.opcfoundation.org/GDS/v105/docs/6.6.8

Add Parameter NoPrivateKeys to OpenStoreMethod of CertificateStoreIdentifier to allow GDS client to update the private key  of a store which is not its own store.
2024-03-26 18:06:51 +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
romanett 22096f4050 GDS: implement ApplicationSelfAdmin privilege in GlobalDiscoverySampleServer (#2338)
-Implement the support for ApplicationSelfAdmin privilege
-implement the workflow in a test to pull the trust list after sucessfully receiving a gds signed certificate. 
-this authorization is described here in the OPC Spec: https://reference.opcfoundation.org/GDS/v105/docs/7.6
2024-02-27 08:25:08 +01:00
Martin Regen 1b893b501e Client Republish improvements (#2468)
- only republish available sequence numbers
- store republish result to handle unsuccessful message republish in main loop
- republish in parallel instead of sequential to reduce response times / blocking in the publish response processing loop
2024-02-27 07:36:35 +01:00
Martin Regen 52bf4ae3f3 Only call JsonEncoder.EscapeString from WriteSimpleField if necessary (#2530)
EscapeString is a function which parses every string for special characters, but often times it is already known that there are no escape characters to process. Improve WriteSimpleField to only call JsonEncoder.EscapeString if necessary.

-- note: fixed a few csproj files

Co-authored-by: Bhupendra Naphade <bhnaphad@microsoft.com>
2024-02-26 18:22:52 +01:00
bhnaphade 0fd58b43f2 Deprecate .NET Standard 2.0 from Nuget packages and builds (#2533) 2024-02-26 13:01:39 +01:00
bhnaphade 4c58c1ff16 Improve JsonEncoder.EscapeString and fix test warnings for ToString() (#2527)
Update the function to improve performance. 
Fix test code warnings (CA1305) related to ToString() method

Based on the results of the benchmark runs, `EscapeStringLegacyPlus` was picked for all platforms that do not support `StreamWriter.Write(ReadOnlySpan<char>)`, e.g. .NET Framework. There is a slight improvement for the cases which require a 4 digit hex encoding.
For platforms that support Span end to end `EscapeStringSpanCharsInline` was picked. The functions tries to optimize how often the underlying StreamWriter is called by combining calls to Write into to slices. It was also noted that up to three character strings, it performs better to do single character writes than calling with a small string.
2024-02-21 13:59:16 +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 4a66cc3385 Remove lock from IServiceMessageContext (#2532)
Reduce lock contention for encoders/decoders.

The IServiceMessageContext locks all properties without really a need, because assigning/reading int and objects is transaction safe.
2024-02-20 15:44:27 +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 a391266daf Improve JsonEncoder.WriteDateTime (#2514)
- The default implementation using `ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK"` was identified in a CPU hotpath analysis when decoded DataValues are JSON encoded.
- The "o" time conversion implementations is up to 10 times faster (see .NET6.0), but as a caveat it does not omit trailing zeroes.
- Even with handling the special case to omit the trailing zeroes, the `o` version used with `ConvertToUniversalTime` with .NET8 runs still 3 to 7 times faster than the default implementation.
2024-02-14 06:48:54 +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
Martin Regen 591ceb0614 fix UWP sample build (#2496) 2024-02-06 14:13:04 +02: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
Bo Biene 7867a6fa7e Fix GetEndpoints when https-uabinary is behind reverse proxy with different port (#2362)
Fix: When the port of AlternateBaseAddress is different from the Endpoint port the discovery returns no valid endpoints.

Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-01-19 10:32:26 +01:00
opcfoundation-org 1e927dd502 1.05.03 release final (#2423)
* latest nodeset
2024-01-18 17:29:46 +01:00
bhnaphade 08c83c2f5b Trace information propagation Client to Server side (#2442)
Update OPC UA stack to pass activity trace information from client to server
2024-01-16 22:22:59 +01:00
Martin Regen 55c953d6de Expose hiresclock ticks and benchmark (#2460)
HiResClock uses the strictly monotonic ticks of the Stopwatch. Expose the Ticks for use in client and server timer.
2024-01-16 11:41:59 +01:00
Martin Regen abc0bde9fe Fix the client subscription preview no ack issue, ack forgotten publish responses (#2449)
Issues: 
- no ack were added to the list of ack to send after PR #2427. 
- Sometimes during network interruptions publish responses are never acked from the republish queue, unless cleaned up by the server. 

Fixes: 
- removed some debug code from the publish response processing and added acks to send back to the right list.
- Use a dedicated lock for the list of sequence numbers to send
- Detect still available sleeping sequence numbers and mark for deletion after a reasonable age (sequence number diff > 100).
- Breaking change: A `TransportChannel` which causes a `NullReferenceException` in a service call is now returned as `ServiceResultException` with status `BadSecureChannelClosed`. Use `NullableTransportChannel` to avoid the exception and get a null instead.
2024-01-06 05:07:48 +01:00
Martin Regen 96233dcdc5 Fix nodestate remove for diagnostic infos (#2450)
revert fix for regression introduced by fix for #2343, apply fix in nodemanagers which do not invert the inverse property, so bidirectional references were not removed.
2024-01-05 17:33:22 +01:00
Martin Regen a1c2216c2c Improvements for client keep alive timers and locks in subscriptions and sessions (#2427)
Issue: 
- On high load, the keep alive timers keep firing and may get blocked in locks, leading to thread starvation.
- The `AsyncAutoResetEvent` for subscriptions is triggered from the reader loop inside a lock and the following execution on the subscription workload blocks the reader thread.
- A reconnect is never triggered on a 'BadSessionIdInvalid`

Fixes: 
- Use periodic timer for platforms supporting it
- Make the `PublishingStopped` and lastkeepalive non blocking by using interlocked variables.
- To decouple the reader loop from the subscription processing, create the TaskCompletionSource with `TaskCreationOptions.RunContinuationsAsynchronously` option.
- Trigger a reconnect if the KeepAlive read request returns with a bad service result.
- Remove unnecessary locks around events, changed calls to be thread safe
2023-12-29 12:29:00 +01:00
Martin Regen af7bb8ceca Improve Utils.IsEqual for byte compare (#2440)
- Improve the `Utils.IsEqual` helper for some special cases which compare byte[].
- In the actual implementation the compilers can not optimize for special cases, e.g. comparing a typical certificate as byte[] with 1k size on .NET8 took 167µs, the customized version needs only 69ns and is even faster than a P/Invoke to memc mp (80ns). 
- see benchmark result for improvements
- Due to the little difference between a custom byte[] and the T[] compare, the byte[] was moved back to the tests
- .NET Framework falls back on memcmp
2023-12-22 11:41:04 +01:00
Martin Regen 0b24d62b7c Use EphemeralKeySet for certificates with private key on supporting platforms (#2421)
- In order to reduce leaking private key files on windows, `EphemeralKeySet`  is used on supporting platforms.
- Keys from the Ephemeral Keyset can not be used with `CopyWithPrivateKey`, add support to copy these keys, e.g. for GDS push support.
- MacOS throws PlatformNotSupported when ephemeral keyset is used.
- Kestrel needs a dedicated key without the ephemeral keyset flag.
- Dispose private keys where possible to reduce number of leaked files in tests.
- For bouncy castle legacy support, do not use the `PersistKey` flag by default on netstandard2.0 and net462. However keys may still leak.
2023-12-22 10:55:07 +01:00
Martin Regen 490d85cb4a Make CertStoreIdentifier.GetCertificateStoreTypeByName and RegisteredStoreTypeNames public (#2429)
Allow to check if there is already a regsitration.
2023-12-14 20:31:21 +01:00
Martin Regen 626bdcb9b8 Fix potential deadlocks with WaitAsync on a SemaphoreSlim (#2415)
Fix cases where a cancellable WaitAsync(ct) on a SemaphoreSlim within a try/finally could end up in a deadlock.
Fix: The WaitAsync must be outside the try/finally block. if the WaitAsync is cancelled, it should not release the semaphore
2023-12-07 19:55:05 +01:00
dependabot[bot] 4697c40b86 Bump Microsoft.Extensions.Logging.Abstractions from 3.1.32 to 8.0.0 (#2388)
* Bump Microsoft.Extensions.Logging.Abstractions from 3.1.32 to 8.0.0

Bumps [Microsoft.Extensions.Logging.Abstractions](https://github.com/dotnet/runtime) from 3.1.32 to 8.0.0.
- [Release notes](https://github.com/dotnet/runtime/releases)
- [Commits](https://github.com/dotnet/runtime/commits/v8.0.0)

---
updated-dependencies:
- dependency-name: Microsoft.Extensions.Logging.Abstractions
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* Update UA Server Controls.csproj

* Update UA Client Controls.csproj

* Update Opc.Ua.Core.csproj

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Martin Regen <mregen@microsoft.com>
2023-12-07 19:53:54 +01:00
Martin Regen 343f7b0fbc Add custom test targets to the build process, support for .NET 8. (#2410)
The goal is to reduce the overall number of builds, stop using end of life platforms in the build pipeline and to support
build of future/deprecated build targets in a custom build step, which is also triggered weekly in the ci builds.

In addition:
- added a doc which describes the release and versioning strategy of this project
- produce the Nuget packges with .NET 8 assemblies.
- produce a Docker build based on a .NET 8 based container.
- add custom test targets to test outdated platforms. Need a manual step to enable for VS or command line.
- bug fixes: the latest move to an alternate crypto library for Bouncy Castle, which is only used for the GDS support and  .NET Framework 4.6.2./netstandard2.0, revealed already a few issues which were previously not found. 
- only .NET8/.NET6/.NET Framework 4.8 are tested in Pull requests. Remaining builds in weekly scheduled builds.
2023-12-07 12:03:37 +01:00
Martin Regen 8a2cf92710 SHA-1 signatures will no longer be trusted by default (#2406)
Since some distributions stop to trust SHA1 signatures by default, replace some internal algorithm checks with SHA256 versions.
The test case to force signature check also reenables ECC tests for .NET 4.8 which had been previously disabled.
2023-12-01 09:36:45 +01:00
Martin Regen 65803c4967 Implement async reconnect (#2399)
- Implement the reconnect and republish with async service calls. 

bug fixes:
- subscription Ids should start from a random number
- the keep alive interval calculation is too short, adding +1 for the timeout
- on BadSessionIdInvalid recreate session immediately 
- on a restarted server with new certificate, also reload endpoints when BadCertificateInvalid is returned
2023-11-30 21:02:51 +01:00
dependabot[bot] 1437138550 Bump System.Text.Encodings.Web from 6.0.0 to 8.0.0 (#2386)
Bumps [System.Text.Encodings.Web](https://github.com/dotnet/runtime) from 6.0.0 to 8.0.0.
- [Release notes](https://github.com/dotnet/runtime/releases)
- [Commits](https://github.com/dotnet/runtime/compare/v6.0.0...v8.0.0)

---
updated-dependencies:
- dependency-name: System.Text.Encodings.Web
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-30 20:09:14 +01:00
Martin Regen 9138bb90e0 Support for subclassing of client sessions, subscriptions and monitored items (#2384)
Currently, due to some internal cloning of sessions, subscriptions and monitored items it is not possible to use subclassed variants which are properly recreated after a session reconnect.

- Add a  `ISessionInstantiator` interface to allow to subclass a `Session` and override virtual function.
- Add a `Subscription.CloneSubscription` and `MonitoredItem.CloneMonitoredItem` virtual method to recreate those with event handlers and client handles.
- A sample implementation with `TestableXXX` classes is provided to test the BadInvalidTimestamp fix by injecting modified timestamps in the session class.
- Remove duplicate `IDisposable` with `Session`. `IClientBase` is disposable already.
- adds `knownTypes` parameter to `Session.Load` and `Session.Save` to support save and restore of custom Subscriptions and Monitored items.

bug fixes:
- IOP: an empty DataTypeDictionary throws an exception when loaded by the complex type system, server are allowed to leave it empty to save memory.
- BadInvalidTimestamp should not be returned when the timestamp in the requestheader is out of sync. #2364
2023-11-28 21:17:56 +01:00
Martin Regen a109c81d22 fix .NET 8 build and warning (#2395)
Fix some warnings and build errors with .NET 8. To build as .NET 8, add net8.0 to target.props.
2023-11-27 18:35:47 +01:00