Commit Graph

792 Commits

Author SHA1 Message Date
romanett 493da5d5be Extend ServerConfiguration & GDS Server for ECC (#2817)
* update ServerConfiguration Node to support multiple Application Certificates. Trust List Support for User Certificates & Https Certificates

* GDS ready for ECC Step1

* fix test

* fix build

* ensure hash algorithm is set

* update configurations to new format, fix minor ecc bugs

* implicitly set certificate type of certificate identifier
extend CertificateFactory to allow Revocation with ECC Issuer Certificate

* Revert "update configurations to new format, fix minor ecc bugs"

This reverts commit 9ee17f3aff.

* Allow GDS Certificate Group to have multiple CA Certificates with different Certificate Types

* fix minor bugs

* adress review feedback

* fix some issues

* fix creation of CA signed ECC Certificates

* Update configurations to new ApplicationCertificateFormat and add extra CA Certificates for ECC Certificates

* remove brainpool certs from configuration

* Generate ECC Certificates in Client Tests

* Revert "Generate ECC Certificates in Client Tests"

This reverts commit 90b395f4ff.

* fix crl tests on platforms not supporting ECC

* fix crl test

* Update READMEs for ECC
2025-01-21 16:34:48 +02:00
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
Suciu Mircea Adrian 8733a33594 Fix net462 build (#2949) 2025-01-20 17:00:26 +01:00
Suciu Mircea Adrian 62b4f050bc Add ECDSA support for importing private key from PEM (#2941)
* Add ECDSA support for reading private key from PEM

* Padded x, y EC point coordinates and the d private key with leading zeros to match keySize

* CreateCertificateWithPEMPrivateKey creates either ECDSA or RSA certificate depending on certificate type
2025-01-17 17:51:21 +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
romanett 6038a69656 [ECC] Implicitly set CertificateType of Certificate Identifier & allow Revocation with ECC Issuer Certificate & fix VerifyECDsaKeyPair (#2924)
* implicitly set certificate type of certificate identifier
extend CertificateFactory to allow Revocation with ECC Issuer Certificate

* Add Crl tests for ECC

* fix X509 PFXUtils VerifyECDsaKeyPair
2025-01-13 17:08:37 +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
Suciu Mircea Adrian 6489c1283f Removed unreachable code (#2916) 2024-12-19 09:04:20 +02:00
Suciu Mircea Adrian 5e11541b81 Set corresponding security signature hash and validate ECDSA security signature hash algorithm length for ECC certificates (#2912)
* Use correctly and validate certificate ECDSA signature hash algorithm

* Added tests for validating length of EC certificate signature

* Improved invalidation condition of SignatureAlgorithm

* Changed result text

* Test fix

* Added helper method to set hash algorithm depending on key size;
Reverted ApplicationInstance code

* Fix test CreateSelfSignedForECDsaDefaultTest
2024-12-19 08:50:09 +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
romanett 6c62eb26fd Fix serialization of CertificateTrustList (#2879) 2024-12-04 09:42:19 +01:00
Suciu Mircea Adrian 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
Martin Regen a887f909f1 Allow ExtensionObjects which are encoded with an unknown size (#2869)
An older OPC UA server returns well known extension object(811) which cannot be decoded by the client because the server doesn't set the length of the extension object. 
Recently, based on fuzz testing, the length check has been changed to enforce an exact match, according to spec.

Workaround: Allow a value of -1 for the length, then allow to decode well known extension objects.

Also improve some internal calls to Safe Read functions by calling not via the interface.
2024-12-03 12:06:11 +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 Regen 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
Martin Regen f76c457c72 Support .NET 9.0 build (#2865)
* support .NET 9.0 build
* provide a helper to use the X509CertificateLoader also on older .NET versions
2024-11-28 12:57:10 +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
KircMax 56dd06d97f Using Uri.TryCreate causes regression with namespace uri that use mixed lower/uppercase letters in the <hostname> of the Uri.(#2837)
Uri.TryCreate lower cases the hostnames. Switch always back to the legacy implementation which maintains the casing.
2024-11-07 10:31:18 +01:00
romanett ff3674fe58 Improve crl handling in certificate stores (#2829)
* improve crl handling in certificate stores by not loading CRL with invalid or unsupported content. Hence the revocation check for such certificates may fail.
2024-11-02 11:44:51 +01:00
Martin Regen ce9850c491 Fix bugs in JSON decoder (#2828)
JSON ReadEnumeratedString does not decode the number in e.g. "Red_0".
JSON reencode of JSON content in an extension object runs into an encoder error.
2024-10-31 08:02:32 +01:00
romanett b2d715d6cb Fix net462 build last issue (#2816) 2024-10-26 09:44:10 +02:00
romanett 0c6b38b0a8 Fix build for legacy platforms by disabling ECC on .NET 4.6.2 & NET-Standard2.0 (#2811)
* added ifdef for code that doesn't support ECC
2024-10-24 09:02:05 +02:00
Suciu Mircea Adrian 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
Marc Schier 3672ebefe9 Null pointer exception when reading a complex type with empty arrays. (#2798)
The server under test has a extension object with a complex type.  Type id = {nsu=http://opcfoundation.org/UA/Machinery/Result/;i=5008}.  This contains something with a variant array that is null though (-1).  SetProperty should support setting a Array that is null.  Therefore, test for null collection (case when length was encoded as -1) before dereferencing ahead of the ToArrray() conversion to Array.
2024-10-14 17:18:50 +02:00
Martin Regen cb621df562 Fix ExpandedNodeId.Format output for not well formed uri and JSON Verbose WriteStatusCode (#2794)
-JSON Encoder Verbose and NonReversible encoding with WriteStatusCode may produce invalid JSON
-ExpandedNodeId.Format does not handle not well formed uri correctly, as in the previous implementation
2024-10-11 19:15:26 +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 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 Regen 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 Regen 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 Regen 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] 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