Commit Graph
761 Commits
Author SHA1 Message Date
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 23b8502778 Server doesn't start up with mixed https endpoints (#2789)
* allow startup of mixed https endpoints
2024-10-10 07:01:48 +02:00
Martin Regen 7c63d8a18f Client ReadNodes, throw BadInvalidType if a value type returned by an attribute is null (#2746)
Handle a case where a misconfigured server returns a null value for an attribute when a value type is expected. To avoid the NullReferenceException that stops the whole ReadNodes operation, flag the Node with the service result and or return a default value if required.
2024-10-09 10:12:28 +02:00
Martin Regen 3d24c0ed36 Do not create the default folders for DirectoryStore on Open (#2773)
For convenience, the DirectoryStore class creates the default folders when the DirectoryStore is opened. (since #2720)
However this may lead into issues mapping folders to the store when started in docker.

Fix: remove the code which creates default folders and ensure a null directory does not throw a NullReferenceException.
2024-09-26 12:58:03 +02:00
Martin RegenandRandy Armstrong 8131a02984 Pubsub JSON updates preview (#2768)
Add support for Compact and Verbose JSON encodings.

Other bug fixes: 
- Defaults for non reversible forces the namespace Uri in the NodeId encoding and all default values are encoded. This behavior is according to spec. Old behavior can be changed reestablished with properties on creation of the JSON encoders.
- Compact and Verbose are preview for the next spec release. Main difference is to always encode NodeIds and ExpandedNodeIds as string with NamespaceUri. Same for QualifiedName. Both are considered reversible encodings.
- JSON decoder accepts any of the new and existing JSOn encodings no matter if the NodeId are encoded as string or JSON object.

Co-authored-by: Randy Armstrong <randy.armstrong@opcfoundation.org>
2024-09-26 09:59:02 +02:00
Martin RegenandHoelterhoff, Noah cf2e788125 Openstore returns null if CertificateIdentifier is empty (#2761)
- OpenStore behavior changed to return null if the storepath or storetype are invalid or empty, which is a change to the previous release. Hence some support functions should check the return value of OpenStore.
- Fix: Check for null in LoadPrivateKeyEx
- in addition: try fix the new flaky test issue
- fix #2637: an exception when the https server starts and a X509Store certificate has a non exportable private key, it is not needed to create a copy for the TLS transport. Ignore the error and start the cert with the original cert.
- restructure which platforms are supported by https and complextypes, to avoid dependency collisions. Remove netcoreapp3.1 (eol), support netstandard2.0/2.1 instead.

---------

Co-authored-by: Hoelterhoff, Noah <noah.hoelterhoff@sap.com>
2024-09-12 13:36:47 +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 Regen 6833b91fd7 August release testing: Improve cert blob decoding hot path and fix cert validator semaphore regression (#2748)
- cert validator semaphore WaitAsync timeout was not correctly handled, also move all semaphores out of try/finally block to follow best practice
- ParseCertBlob shows up in the hot path. API is changed to use ReadOnlyMemory<byte>.
- Enum.ToString() was flagged in perf analyzer, changed logger call
2024-09-05 16:00:11 +02:00
Martin Regen 1c6253a729 AddRejected method for ICertificateStore (#2720)
- Add a light weight AddRejected certificate store method to `ICertificateStore` to ensure rejected cert history remains small and doesn't have a lot of overhead.
- Number of history certificates is configurable using a new `MaxRejectedCertificates` entry.
- Rejected certs are only saved to directory cert store, others do ignore the attempt
- Fix the caching of `CertificateValidator` and flag some `ÒpenStore` methods deprecated which do not support the caching. Fixes across the board to support the methodology. Basically `store.Close` keeps the cache, `store.Dispose` clears the cache, so recommendation is to use `var store = certStoreIdentifier.OpenStore(); try { ... }-- finally { store.Close }`
2024-09-03 15:23:32 +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
Archie Miller 3e5ad45c6e Remove example of how to select unrecommended RSA15 Policy (#2728)
RSA 15 policy is deprecated
* Remove example of how to select RSA15 Policy in a server
* Add a Warning Message if the Rsa 15 policy is used
2024-08-22 16:18:41 +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
dependabot[bot] 06eb1a1a4e Bump System.Security.Cryptography.Cng from 4.5.2 to 5.0.0 (#2724)
Bumps System.Security.Cryptography.Cng from 4.5.2 to 5.0.0.

---
updated-dependencies:
- dependency-name: System.Security.Cryptography.Cng
  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>
2024-08-21 10:23:24 +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
dependabot[bot]andMartin Regen 4b822fced9 Bump BenchmarkDotNet from 0.13.12 to 0.14.0 and fix some build issues for legacy platforms (#2707)
* Bump BenchmarkDotNet from 0.13.12 to 0.14.0
* Fix NetStandard2.0 and Netstandard2.1 ci builds

Bumps [BenchmarkDotNet](https://github.com/dotnet/BenchmarkDotNet) from 0.13.12 to 0.14.0.
- [Release notes](https://github.com/dotnet/BenchmarkDotNet/releases)
- [Commits](https://github.com/dotnet/BenchmarkDotNet/compare/v0.13.12...v0.14.0)

---
updated-dependencies:
- dependency-name: BenchmarkDotNet
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-08-13 12:24:22 +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
romanett 84628ee3a2 Remove default rejected store creation (#2696)
Disable auto creation of Default Rejected Store
2024-08-05 07:33:23 +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 7b68ff7a04 Fuzzing fixes for June (#2663)
- Indempotent fuzzing revealed issue in DiagnosticInfo
- Matrix may have been used to decode one dimensional array if encoder used the `ArrayDimensions` field, which doesn't seem forbidden. Matrix caused cast exceptionwhen encoding the one dim atrray wrapped in a Matrix object.
- JsonEncoder throws InvalidCastException if NodeId Guid is encoded as Uuid.
- Strings with trailing `0` need to strip off all, or indempotent encoding fails.
2024-07-02 04:47:00 +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
JSGInray 14025f8b72 Fix NullReference in XmlDecoder.ReadExpandedNodeId (#2636)
* Fix XmlDecoder.ReadExpandedNodeId fails with a NullReference when the ExpandedNodeId that was read is equal to ExpandedNodeId.Null
2024-06-28 12:38:29 +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
romanett 240312486b Add null check in SelectEndpoints to avoid warning messages (#2646) 2024-06-14 16:39:34 +02:00
romanett dddc1cb4ab Make X509CertificateStore support CRLs on Windows (#2571)
This PR extends the existing X509 CertificateStore building on top of the .NET X509Store Class to support Certificate Revocation Lists (CRLs) This is important to make the X509Store viable for use as Trust and Issuer Store.

Considerations:
- only Works on Windows, on all other OS the "SupportsCRLs"-Property of the Store still returns false
- builds on top of the Win32 API
- uses source generated P-Invoke calls to call into Win32 API (https://github.com/microsoft/CsWin32)
- makes use of Extension Methods of .NET X509Store Class to make the CRL Enumerate / Add / Delete accessible for the Store Implementation
- guards ever call with OS Support calls and throws PlatformNotSupportedException
- Behaviour of the X509CertificateStore for Linux/MacOS is unchanged
- Added unit tests for the Certificate Store testing all relvant implemented crl functions
- Extended GDS Tests for Integration Testing by utilizing Client & Server making second run on windows with only X509 Stores
2024-06-11 16:17:02 +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 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 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 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 RegenandBhupendra Naphade 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