-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathConnectTester.cs
More file actions
512 lines (450 loc) · 20.3 KB
/
ConnectTester.cs
File metadata and controls
512 lines (450 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
using Opc.Ua.Security.Certificates;
namespace Quickstarts
{
/// <summary>
/// Wraps connect testing functionality
/// </summary>
public sealed class ConnectTester : IAsyncDisposable
{
public ConnectTester(
ITelemetryContext telemetry,
ManualResetEvent quitEvent = null)
{
m_quitEvent = quitEvent;
m_telemetry = telemetry;
m_logger = telemetry.CreateLogger<ConnectTester>();
}
/// <inheritdoc/>
public async ValueTask DisposeAsync()
{
m_reconnectHandler?.Dispose();
ISession session = m_wrapper?.Session;
if (session != null)
{
await session.DisposeAsync().ConfigureAwait(false);
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Run the tests until cancelled or quit
/// </summary>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task RunAsync(CancellationToken ct)
{
try
{
m_reconnectHandler = new SessionReconnectHandler(
m_telemetry,
true,
kReconnectPeriodExponentialBackoff);
m_logger.LogInformation("OPC UA Security Test Client");
// The application name and config file names
const string applicationName = "ConsoleReferenceClient";
const string configSectionName = "Quickstarts.ReferenceClient";
// Define the UA Client application
var passwordProvider = new CertificatePasswordProvider([]);
var application = new ApplicationInstance(m_telemetry)
{
ApplicationName = applicationName,
ApplicationType = ApplicationType.Client,
ConfigSectionName = configSectionName,
CertificatePasswordProvider = passwordProvider
};
await using (application.ConfigureAwait(false))
{
// load the application configuration.
m_configuration = await application
.LoadApplicationConfigurationAsync(silent: false, ct: ct)
.ConfigureAwait(false);
m_configuration.CertificateManager.AcceptError = AcceptCertificate;
// check the application certificate.
bool haveAppCertificate = await application
.CheckApplicationInstanceCertificatesAsync(false, ct: ct)
.ConfigureAwait(false);
if (!haveAppCertificate)
{
throw new InvalidOperationException("Application instance certificate invalid!");
}
}
m_logger.LogInformation("Connecting to... {ServerUrl}", kServerUrl);
ArrayOf<EndpointDescription> endpoints = await GetEndpointsAsync(
m_configuration,
kServerUrl,
ct).ConfigureAwait(false);
var endpointConfiguration = EndpointConfiguration.Create(m_configuration);
var sessionFactory = new DefaultSessionFactory(m_telemetry);
var userNameidentity = new UserIdentity(kUserName, new UTF8Encoding(false).GetBytes(kPassword));
foreach (EndpointDescription ii in endpoints.ToArray())
{
string userCertificateFile = GetUserCertificateFile(ii.SecurityPolicyUri);
X509Certificate2 x509 = X509CertificateLoader.LoadPkcs12FromFile(
Path.Combine("..\\..\\pki\\trustedUser\\private",
userCertificateFile),
"password");
string thumbprint = x509.Thumbprint;
UserIdentity certificateIdentity = await LoadUserCertificateAsync(
thumbprint,
"password",
ct).ConfigureAwait(false);
var identities = new List<UserIdentity>
{
new()
};
if (!string.IsNullOrEmpty(kUserName))
{
identities.Add(userNameidentity);
}
if (kSupportsX509)
{
identities.Add(certificateIdentity);
}
foreach (UserIdentity identity in identities)
{
try
{
m_logger.LogWarning("{Line}", new string('=', 80));
m_logger.LogWarning(
"SECURITY-POLICY={SecurityPolicyUri} {SecurityMode}",
SecurityPolicies.GetDisplayName(ii.SecurityPolicyUri),
ii.SecurityMode);
m_logger.LogWarning(
"IDENTITY={DisplayName} {TokenType}",
identity.DisplayName,
identity.TokenType);
SessionWrapper wrapper = m_wrapper = await RunTestAsync(
endpointConfiguration,
sessionFactory,
ii,
identity,
ct).ConfigureAwait(false);
m_logger.LogWarning("Waiting for SecureChannel renew");
await wrapper.Session.UpdateSessionAsync(identity, default, ct).ConfigureAwait(false);
for (int count = 0; count < 1; count++)
{
ReadResponse result = await wrapper.Session.ReadAsync(
null,
0,
TimestampsToReturn.Neither,
new List<ReadValueId>
{
new() {
NodeId = VariableIds.Server_ServerStatus_CurrentTime,
AttributeId = Attributes.Value
}
},
ct).ConfigureAwait(false);
m_logger.LogWarning(
"CurrentTime: {CurrentTime}",
result.Results[0].WrappedValue.GetDateTime());
await Task.Delay(5000, ct).ConfigureAwait(false);
}
await wrapper.Session.UpdateSessionAsync(identity, default, ct).ConfigureAwait(false);
await wrapper.Session.CloseAsync(true, ct: ct).ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.Message);
Console.WriteLine("StackTrace: {0}", e.StackTrace);
m_logger.LogWarning(
"SECURITY-POLICY={SecurityPolicyUri} {SecurityMode}",
SecurityPolicies.GetDisplayName(ii.SecurityPolicyUri),
ii.SecurityMode);
m_logger.LogWarning(
"IDENTITY={DisplayName} {TokenType}",
identity.DisplayName,
identity.TokenType);
m_logger.LogWarning("{Line}", new string('=', 80));
}
m_logger.LogWarning(
"TEST COMPLETE: {SecurityPolicyUri} {SecurityMode}",
SecurityPolicies.GetDisplayName(ii.SecurityPolicyUri),
ii.SecurityMode);
m_logger.LogWarning("{Line}", new string('=', 80));
}
}
Console.WriteLine("Ctrl-C to stop.");
m_quitEvent.WaitOne();
}
catch (Exception e)
{
m_logger.LogError("Exception: {Message}", e.Message);
m_logger.LogTrace("StackTrace: {StackTrace}", e.StackTrace);
}
}
internal async Task<SessionWrapper> RunTestAsync(
EndpointConfiguration endpointConfiguration,
DefaultSessionFactory sessionFactory,
EndpointDescription endpointDescription,
UserIdentity identity,
CancellationToken ct)
{
var endpoint = new ConfiguredEndpoint(
null,
endpointDescription,
endpointConfiguration);
// Create the session
ISession isession = await sessionFactory
.CreateAsync(
m_configuration,
endpoint,
false,
false,
m_configuration.ApplicationName,
600000,
//new UserIdentity(),
endpointDescription.SecurityMode != MessageSecurityMode.None ? identity : new UserIdentity(),
default,
ct
)
.ConfigureAwait(false);
bool ownsSession = true;
try
{
SessionWrapper wrapper = m_wrapper = new SessionWrapper { Session = isession };
ownsSession = false;
// Assign the created session
if (!wrapper.Session.Connected)
{
throw new InvalidOperationException("Could not connect to server at " + kServerUrl);
}
wrapper.Session.KeepAliveInterval = 10000;
wrapper.Session.KeepAlive += Session_KeepAlive;
var samples = new ClientSamples(m_telemetry, null, m_quitEvent);
ArrayOf<ReferenceDescription> nodes = await samples.BrowseFullAddressSpaceAsync(
wrapper,
ObjectIds.ObjectsFolder,
null,
ct).ConfigureAwait(false);
return wrapper;
}
finally
{
if (ownsSession)
{
await isession.DisposeAsync().ConfigureAwait(false);
}
}
}
private async Task<UserIdentity> LoadUserCertificateAsync(
string thumbprint,
string password,
CancellationToken ct)
{
CertificateTrustList store = m_configuration.SecurityConfiguration.TrustedUserCertificates;
// get user certificate with matching thumbprint
using CertificateCollection certificates =
await store.GetCertificatesAsync(m_telemetry, ct).ConfigureAwait(false);
using Certificate hit = certificates
.Find(X509FindType.FindByThumbprint, thumbprint, false)
.FirstOrDefault();
// create Certificate Identifier
var cid = new CertificateIdentifier
{
Thumbprint = hit.Thumbprint,
SubjectName = hit.Subject,
StorePath = store.StorePath,
StoreType = store.StoreType
};
return await UserIdentity.CreateAsync(
cid,
new CertificatePasswordProvider(new UTF8Encoding(false).GetBytes(password)),
m_configuration.CertificateManager.CertificateProvider,
ct).ConfigureAwait(false);
}
private static async ValueTask<ArrayOf<EndpointDescription>> GetEndpointsAsync(
ApplicationConfiguration application,
string discoveryUrl,
CancellationToken ct = default)
{
var endpointConfiguration = EndpointConfiguration.Create(application);
using DiscoveryClient client = await DiscoveryClient.CreateAsync(
application,
new Uri(discoveryUrl),
endpointConfiguration,
ct: ct).ConfigureAwait(false);
return await client.GetEndpointsAsync(default, ct).ConfigureAwait(false);
}
private bool AcceptCertificate(Certificate certificate, ServiceResult error)
{
// ****
// Implement a custom logic to decide if the certificate should be
// accepted. Return true to accept, false to reject.
// ***
m_logger.LogInformation("{ServiceResult}", error);
bool certificateAccepted = error.StatusCode == StatusCodes.BadCertificateUntrusted;
if (certificateAccepted)
{
m_logger.LogInformation(
"Untrusted Certificate accepted. Subject = {Subject}",
certificate.Subject);
}
else
{
m_logger.LogInformation(
"Untrusted Certificate rejected. Subject = {Subject}",
certificate.Subject);
}
return certificateAccepted;
}
/// <summary>
/// Handles a keep alive event from a session and triggers a reconnect if necessary.
/// </summary>
private void Session_KeepAlive(ISession session, KeepAliveEventArgs e)
{
try
{
// check for events from discarded sessions.
if (m_wrapper == null || !m_wrapper.Session.Equals(session))
{
return;
}
// start reconnect sequence on communication error.
if (ServiceResult.IsBad(e.Status))
{
SessionReconnectHandler.ReconnectState state = m_reconnectHandler
.BeginReconnect(
m_wrapper.Session,
null,
kReconnectPeriod,
Client_ReconnectComplete
);
if (state == SessionReconnectHandler.ReconnectState.Triggered)
{
m_logger.LogInformation(
"KeepAlive status {StatusCode}, reconnect status {State}, reconnect period {ReconnectPeriod}ms.",
e.Status,
state,
kReconnectPeriod
);
}
else
{
m_logger.LogInformation(
"KeepAlive status {StatusCode}, reconnect status {State}.",
e.Status,
state);
}
// cancel sending a new keep alive request, because reconnect is triggered.
e.CancelKeepAlive = true;
}
}
catch (Exception exception)
{
m_logger.LogError(exception, "Error in OnKeepAlive.");
}
}
private void Client_ReconnectComplete(object sender, EventArgs e)
{
// ignore callbacks from discarded objects.
if (!ReferenceEquals(sender, m_reconnectHandler))
{
return;
}
lock (m_lock)
{
// if session recovered, Session property is null
if (m_reconnectHandler.Session != null)
{
// ensure only a new instance is disposed
// after reactivate, the same session instance may be returned
if (!ReferenceEquals(m_wrapper.Session, m_reconnectHandler.Session))
{
m_logger.LogInformation(
"--- RECONNECTED TO NEW SESSION --- {SessionId}",
m_reconnectHandler.Session.SessionId
);
ISession session = m_wrapper.Session;
m_wrapper = new SessionWrapper { Session = m_reconnectHandler.Session };
session?.Dispose();
}
else
{
m_logger.LogInformation(
"--- REACTIVATED SESSION --- {SessionId}",
m_reconnectHandler.Session.SessionId);
}
}
else
{
m_logger.LogInformation("--- RECONNECT KeepAlive recovered ---");
}
}
}
private static string GetUserCertificateFile(string securityPolicyUri)
{
SecurityPolicyInfo securityPolicy = SecurityPolicies.GetInfo(securityPolicyUri);
switch (securityPolicy.CertificateKeyAlgorithm)
{
case CertificateKeyAlgorithm.BrainpoolP256r1:
return "iama.tester.brainpoolP256r1.pfx";
case CertificateKeyAlgorithm.BrainpoolP384r1:
return "iama.tester.brainpoolP384r1.pfx";
case CertificateKeyAlgorithm.NistP256:
return "iama.tester.nistP256.pfx";
case CertificateKeyAlgorithm.NistP384:
return "iama.tester.nistP384.pfx";
default:
return "iama.tester.rsa.pfx";
}
}
internal sealed class SessionWrapper : IUAClient
{
public ISession Session { get; init; }
}
private readonly Lock m_lock = new();
private SessionReconnectHandler m_reconnectHandler;
private ApplicationConfiguration m_configuration;
private SessionWrapper m_wrapper;
private readonly ILogger m_logger;
private readonly ITelemetryContext m_telemetry;
private readonly ManualResetEvent m_quitEvent;
private const string kServerUrl = "opc.tcp://localhost:62541";
private const string kUserName = "sysadmin";
private const string kPassword = "demo";
private const bool kSupportsX509 = true;
private const int kReconnectPeriod = 1000;
private const int kReconnectPeriodExponentialBackoff = 15000;
}
}