Initial project state: .NET reference, design, Rust port (M0+M1), evidence
rust / build / test / clippy / fmt (push) Has been cancelled

Layout:
- src/                    .NET 10 x64 reference: MxNativeCodec, MxNativeClient,
                          MxAsbClient, probes, tests, harnesses. Executable spec.
- design/                 Architectural plan for the Rust port (M0–M6), error
                          model, protocol invariants, risks (R1–R16), adversarial
                          review log (review.md).
- rust/                   Rust workspace. M0 skeleton + M1 codec parity.
                          mxaccess-codec: 215 unit tests + 2 cross-implementation
                          parity tests (byte-identical against .NET reference).
                          Other crates are M0 stubs awaiting M2+.
- captures/               Frida + netsh + pcap evidence per CLAUDE.md
                          ("captures are evidence, not throwaway logs").
- analysis/               Decompiled C# (frida/proxy/decompiled-*),
                          Ghidra exports for native DLLs (`exports/` only —
                          working state at `projects/` and AVEVA's input
                          binaries at `input/` are gitignored).
- docs/                   Reverse-engineering reference docs.
- tools/                  Setup-LiveProbeEnv.ps1 (Infisical credential fetcher),
                          Compute-Crc.ps1 (.NET parity helper).
- .github/workflows/      Rust CI: fmt + build + test + clippy on Windows.
- LICENSE                 MIT (Joseph Doherty, 2026).

Verified:
- cargo test --workspace → 217 passed (215 unit + 2 .NET parity), 0 failed
- cargo clippy --workspace -- -D warnings → clean
- cargo fmt --all -- --check → clean
- cargo publish --dry-run -p mxaccess-codec → packages cleanly

Excluded from history (see .gitignore):
- **/bin, **/obj, **/target — build artifacts
- analysis/ghidra/projects/ — Ghidra working state (regenerable)
- analysis/ghidra/input/ — AVEVA proprietary DLLs (vendor IP)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-05-05 06:21:00 -04:00
parent 43733699b0
commit fe2a6db786
3849 changed files with 352975 additions and 0 deletions
@@ -0,0 +1,637 @@
#define TRACE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.ServiceModel;
using System.ServiceModel.Discovery;
using System.Text;
using System.Xml;
using ArchestrAServices.Common;
using ArchestrAServices.Contract;
using ArchestrAServices.Proxy;
namespace ASBClientAccessLayer;
public class ASBClient : IASBClient1, IASBClient
{
private ManageASBSecurityProxy AsbSecurityProxy;
public bool Connected
{
get
{
if (AsbSecurityProxy != null && AsbSecurityProxy.State == CommunicationState.Opened)
{
return AsbSecurityProxy.SecureSessionEstablished;
}
return false;
}
}
public ASBClient()
{
AsbSecurityProxy = null;
}
public ASBClient(string SrNodeName)
{
AsbSecurityProxy = new ManageASBSecurityProxy(SrNodeName);
string errorMessage = string.Empty;
if (!AsbSecurityProxy.Connect(string.Empty, out errorMessage))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, "Error opening persistent endpoint to System Authentication service on node {0}: {1}", SrNodeName, errorMessage);
}
}
public bool Reconnect()
{
if (AsbSecurityProxy != null)
{
AsbSecurityProxy.Disconnect();
string errorMessage = string.Empty;
if (!AsbSecurityProxy.Connect(string.Empty, out errorMessage))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, "Error re-opening persistent endpoint to System Authentication service on node {0}: {1}", AsbSecurityProxy.SRNodeName, errorMessage);
return false;
}
return true;
}
return false;
}
public bool Disconnect()
{
if (AsbSecurityProxy != null)
{
AsbSecurityProxy.Disconnect();
return true;
}
return false;
}
public ArchestrAResult OpenTemporaryRegistrationEndpoint(string repositoryNode, SecureString passphrase)
{
ArchestrAResult archestrAResult = ResultFactory.MakeResult(ArchestrAError.BadNoCommunication, 0);
string errorMessage = string.Empty;
ManageASBSecurityProxy asbSecurityProxy = AsbSecurityProxy;
if (asbSecurityProxy == null)
{
using (asbSecurityProxy = new ManageASBSecurityProxy(repositoryNode))
{
asbSecurityProxy.Connect(string.Empty, out errorMessage);
EnableRegistration(archestrAResult, asbSecurityProxy, passphrase, out errorMessage);
}
}
else
{
EnableRegistration(archestrAResult, asbSecurityProxy, passphrase, out errorMessage);
}
return archestrAResult;
}
private ArchestrAResult EnableRegistration(ArchestrAResult archestrAResult, ManageASBSecurityProxy Proxy, SecureString passphrase, out string errorMessage)
{
errorMessage = string.Empty;
if (Proxy.State == CommunicationState.Opened && Proxy.SecureSessionEstablished)
{
archestrAResult = Proxy.RegisterServiceBusEnable(new SystemAuthenticationASBConfiguration
{
solutionName = "EnableRegistration",
EncryptedSharedSecret = Encoding.ASCII.GetBytes(ConvertToString(passphrase))
});
if (archestrAResult.Status != 0)
{
errorMessage = "failed to open registration endpoint";
}
}
return archestrAResult;
}
public ArchestrAResult CloseTemporaryRegistrationEndpoint(string repositoryNode)
{
ArchestrAResult archestrAResult = ResultFactory.MakeResult(ArchestrAError.BadNoCommunication, 0);
string errorMessage = string.Empty;
ManageASBSecurityProxy asbSecurityProxy = AsbSecurityProxy;
if (asbSecurityProxy == null)
{
using (asbSecurityProxy = new ManageASBSecurityProxy(repositoryNode))
{
asbSecurityProxy.Connect(string.Empty, out errorMessage);
DisableRegistration(archestrAResult, asbSecurityProxy, out errorMessage);
}
}
else
{
DisableRegistration(archestrAResult, asbSecurityProxy, out errorMessage);
}
return archestrAResult;
}
private ArchestrAResult DisableRegistration(ArchestrAResult archestrAResult, ManageASBSecurityProxy Proxy, out string errorMessage)
{
errorMessage = string.Empty;
if (Proxy.State == CommunicationState.Opened && Proxy.SecureSessionEstablished)
{
archestrAResult = Proxy.RegisterServiceBusEnable(new SystemAuthenticationASBConfiguration
{
solutionName = "DisableRegistration",
EncryptedSharedSecret = null
});
if (archestrAResult.Status != 0)
{
errorMessage = "failed to close registration endpoint";
}
}
return archestrAResult;
}
public ArchestrAResult OpenTemporaryPairingEndpoint(string repositoryNode, SecureString passphrase)
{
ArchestrAResult archestrAResult = ResultFactory.MakeResult(ArchestrAError.BadNoCommunication, 0);
string errorMessage = string.Empty;
ManageASBSecurityProxy asbSecurityProxy = AsbSecurityProxy;
if (asbSecurityProxy == null)
{
using (asbSecurityProxy = new ManageASBSecurityProxy(repositoryNode))
{
asbSecurityProxy.Connect(string.Empty, out errorMessage);
EnablePairing(archestrAResult, asbSecurityProxy, passphrase, out errorMessage);
}
}
else
{
EnablePairing(archestrAResult, asbSecurityProxy, passphrase, out errorMessage);
}
return archestrAResult;
}
private ArchestrAResult EnablePairing(ArchestrAResult archestrAResult, ManageASBSecurityProxy Proxy, SecureString passphrase, out string errorMessage)
{
errorMessage = string.Empty;
if (Proxy.State == CommunicationState.Opened && Proxy.SecureSessionEstablished)
{
archestrAResult = Proxy.RegisterServiceBusEnable(new SystemAuthenticationASBConfiguration
{
solutionName = "EnablePairing",
EncryptedSharedSecret = Encoding.ASCII.GetBytes(ConvertToString(passphrase))
});
if (archestrAResult.Status != 0)
{
errorMessage = "failed to open pairing endpoint";
}
}
return archestrAResult;
}
public ArchestrAResult CloseTemporaryPairingEndpoint(string repositoryNode)
{
ArchestrAResult archestrAResult = ResultFactory.MakeResult(ArchestrAError.BadNoCommunication, 0);
string errorMessage = string.Empty;
ManageASBSecurityProxy asbSecurityProxy = AsbSecurityProxy;
if (asbSecurityProxy == null)
{
using (asbSecurityProxy = new ManageASBSecurityProxy(repositoryNode))
{
asbSecurityProxy.Connect(string.Empty, out errorMessage);
DisablePairing(archestrAResult, asbSecurityProxy, out errorMessage);
}
}
else
{
DisablePairing(archestrAResult, asbSecurityProxy, out errorMessage);
}
return archestrAResult;
}
private ArchestrAResult DisablePairing(ArchestrAResult archestrAResult, ManageASBSecurityProxy Proxy, out string errorMessage)
{
errorMessage = string.Empty;
if (Proxy.State == CommunicationState.Opened && Proxy.SecureSessionEstablished)
{
archestrAResult = Proxy.RegisterServiceBusEnable(new SystemAuthenticationASBConfiguration
{
solutionName = "DisablePairing",
EncryptedSharedSecret = null
});
if (archestrAResult.Status != 0)
{
errorMessage = "failed to close pairing endpoint";
}
}
return archestrAResult;
}
public ArchestrAResult GetRegistrationEndpointStatus(string repositoryNode, out List<TemporaryEndpointStatus> ConfigurationData)
{
ConfigurationData = new List<TemporaryEndpointStatus>();
ArchestrAResult archestrAResult = ResultFactory.MakeResult(ArchestrAError.BadNoCommunication, 0);
string errorMessage = string.Empty;
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, "GetRegistrationEndpointStatus: Creating new ManageASBSecurityProxy for {0}", repositoryNode);
ManageASBSecurityProxy asbSecurityProxy = AsbSecurityProxy;
if (asbSecurityProxy == null)
{
using (asbSecurityProxy = new ManageASBSecurityProxy(repositoryNode))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, "GetRegistrationEndpointStatus: Calling Connect with empty passphrase");
asbSecurityProxy.Connect(string.Empty, out errorMessage);
RetrieveTemporaryEndpoint(archestrAResult, asbSecurityProxy, ConfigurationData, out errorMessage);
}
}
else
{
RetrieveTemporaryEndpoint(archestrAResult, asbSecurityProxy, ConfigurationData, out errorMessage);
}
return archestrAResult;
}
private ArchestrAResult RetrieveTemporaryEndpoint(ArchestrAResult archestrAResult, ManageASBSecurityProxy Proxy, List<TemporaryEndpointStatus> ConfigurationData, out string errorMessage)
{
errorMessage = string.Empty;
if (Proxy.State == CommunicationState.Opened && Proxy.SecureSessionEstablished)
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, "GetRegistrationEndpointStatus: Calling GetRegistrationEndpointStatus");
archestrAResult = Proxy.GetRegistrationEndpointStatus(out var ConfigurationData2);
if (archestrAResult.Status != 0)
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, "GetRegistrationEndpointStatus: failed to retrieve temporary endpoint status: {0}", archestrAResult.Status);
errorMessage = "failed to retrieve temporary endpoint status";
}
else
{
StatusTemporaryEndpoint[] array = ConfigurationData2;
for (int i = 0; i < array.Length; i++)
{
StatusTemporaryEndpoint statusTemporaryEndpoint = array[i];
ConfigurationData.Add(new TemporaryEndpointStatus
{
EndpointName = statusTemporaryEndpoint.EndpointName,
EndpointState = (TemporaryEndpointState)Enum.Parse(typeof(TemporaryEndpointState), statusTemporaryEndpoint.EndpointState, ignoreCase: true)
});
}
}
}
return archestrAResult;
}
public RegistrationResult RegisterWithSR(string repositoryNode, SecureString passphrase)
{
string value = new ManageSecurityConfiguration().Registration(AsbSecurityProxy, repositoryNode, ConvertToString(passphrase), null, isRegister: true);
RegistrationResult result = RegistrationResult.Success;
if (!string.IsNullOrEmpty(value))
{
result = RegistrationResult.RepositoryNodeNotConfigured;
}
return result;
}
public RegistrationResult CopySolutionFromSR(string repositoryNode, SecureString passphrase, string solutionName)
{
string value = new ManageSecurityConfiguration().Registration(AsbSecurityProxy, repositoryNode, ConvertToString(passphrase), solutionName, isRegister: false);
RegistrationResult result = RegistrationResult.Success;
if (!string.IsNullOrEmpty(value))
{
result = RegistrationResult.RepositoryNodeNotConfigured;
}
return result;
}
public RegistrationResult RemoveSolutionFromThisNode(string solutionName)
{
if (string.IsNullOrEmpty(solutionName))
{
return RegistrationResult.NodeInaccessible;
}
string value = RegistryHandler.DeleteFromRegistry(solutionName);
RegistrationResult result = RegistrationResult.Success;
if (!string.IsNullOrEmpty(value))
{
result = RegistrationResult.RepositoryNodeNotConfigured;
}
return result;
}
public string GetPassphraseForSolution(string solutionName)
{
return new ManageSecurityConfiguration().GetPassphraseForSolution(solutionName);
}
public RegistrationResult UnregisterWithSR(string repositoryNode)
{
string text = new ManageSecurityConfiguration().UnRegistration(repositoryNode);
RegistrationResult result = RegistrationResult.Success;
if (!string.IsNullOrEmpty(text))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, string.Format("UnregisterWithSR({0}) failed: {1}", string.IsNullOrEmpty(repositoryNode) ? "<Default>" : repositoryNode, text));
result = RegistrationResult.RepositoryNodeNotConfigured;
}
return result;
}
public RegistrationResult PairSRNodes(string remoteRepositoryNode, SecureString passphrase)
{
RegistrationResult result = RegistrationResult.Success;
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"PairSRNodes Enter: {remoteRepositoryNode}");
ManageSecurityConfiguration manageSecurityConfiguration = new ManageSecurityConfiguration();
string SRNodeName = string.Empty;
RegistryHandler.GetSrNode(out SRNodeName);
if (HostNameValidator.IsRemoteNodeSameasSRNode(remoteRepositoryNode, SRNodeName))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, "PairSRNodes failed: Pairing to same SRNode is not allowed");
result = RegistrationResult.NodeInaccessible;
}
else
{
string text = manageSecurityConfiguration.PairDefaultSRwithRemoteSR(remoteRepositoryNode, ConvertToString(passphrase));
if (!string.IsNullOrEmpty(text))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, $"PairSRNodes failed: {text}");
result = RegistrationResult.RepositoryNodeNotConfigured;
}
}
return result;
}
public RegistrationResult UnpairSRNodes(string remoteRepositoryNode)
{
string SRNodeName = string.Empty;
RegistryHandler.GetSrNode(out SRNodeName);
RegistrationResult result = RegistrationResult.Success;
if (HostNameValidator.IsRemoteNodeSameasSRNode(remoteRepositoryNode, SRNodeName))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, "UnPairSRNode failed: Un-pairing to same SRNode is not allowed");
result = RegistrationResult.NodeInaccessible;
}
else
{
string remoteSolutionName = "Archestra_" + remoteRepositoryNode;
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, string.Format("UnpairSRNodes called for solution '{0}'", string.IsNullOrEmpty(remoteRepositoryNode) ? "<Empty>" : remoteRepositoryNode));
SynchronizeSolutionsWithSR();
string text = new ManageSecurityConfiguration().UnpairDefaultSRfromRemoteSR(remoteSolutionName);
if (!string.IsNullOrEmpty(text))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, $"UnpairSRNodes failed: {text}");
result = RegistrationResult.RepositoryNodeNotConfigured;
}
}
return result;
}
public string GetChangedASBExtraInfo()
{
SynchronizeSolutionsWithSR();
string empty = string.Empty;
string XMLExtraInfo = string.Empty;
string SRNodeName = string.Empty;
empty = RegistryHandler.GetSrNode(out SRNodeName);
if (!string.IsNullOrEmpty(SRNodeName))
{
ManageASBSecurityProxy asbSecurityProxy = AsbSecurityProxy;
if (asbSecurityProxy == null)
{
using (asbSecurityProxy = new ManageASBSecurityProxy(SRNodeName))
{
asbSecurityProxy.Connect(string.Empty, out empty);
RetrieveExtraInfoChanges(asbSecurityProxy, out XMLExtraInfo, out empty);
}
}
else
{
RetrieveExtraInfoChanges(asbSecurityProxy, out XMLExtraInfo, out empty);
}
}
else
{
empty = "No repository node is registered";
}
return XMLExtraInfo;
}
private void RetrieveExtraInfoChanges(ManageASBSecurityProxy Proxy, out string XMLExtraInfo, out string errorMessage)
{
XMLExtraInfo = string.Empty;
errorMessage = string.Empty;
if (Proxy.State == CommunicationState.Opened && Proxy.SecureSessionEstablished && Proxy.QueryExtraInfoChanges(out XMLExtraInfo, Environment.MachineName).Status != 0)
{
errorMessage = "failed to retrieve temporary endpoint status";
}
}
private void SynchronizeSolutionsWithSR()
{
if (!string.IsNullOrEmpty(RegistryHandler.GetDefaultSolutionName(out var DefaultSolutionName)) || !string.IsNullOrEmpty(RegistryHandler.GetSrNode(DefaultSolutionName, out var SRNodeName)) || !string.IsNullOrEmpty(RegistryHandler.GetSolutionPassphrase(DefaultSolutionName, out var passphrase)))
{
return;
}
using SecureString secureString = new SecureString();
string text = passphrase;
foreach (char c in text)
{
secureString.AppendChar(c);
}
List<string> pairedSolutionsInSR = GetPairedSolutionsInSR(SRNodeName);
List<string> solutionsAtThisNode = GetSolutionsAtThisNode();
if (!pairedSolutionsInSR.Any() || !solutionsAtThisNode.Any())
{
return;
}
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach (string item in pairedSolutionsInSR)
{
dictionary.Add(item, 0);
}
Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
foreach (string item2 in solutionsAtThisNode)
{
dictionary2.Add(item2, 0);
}
int value;
foreach (string item3 in pairedSolutionsInSR)
{
if (item3 != DefaultSolutionName && !dictionary2.TryGetValue(item3, out value))
{
CopySolutionFromSR(SRNodeName, secureString, item3);
}
}
foreach (string item4 in solutionsAtThisNode)
{
if (item4 != DefaultSolutionName && !dictionary.TryGetValue(item4, out value))
{
RemoveSolutionFromThisNode(item4);
}
}
}
public List<string> GetPairedSolutionsInSR(string repositoryNode)
{
List<string> SolutionNames = new List<string>();
new ManageSecurityConfiguration().GetSolutionsPairedWithSR(AsbSecurityProxy, repositoryNode, out SolutionNames);
return SolutionNames;
}
public List<string> GetSolutionsAtThisNode()
{
return RegistryHandler.EnumerateSolutionsAtThisNode();
}
public string GetDiscoveryEndpoint()
{
return SvcUtilities.GetDiscoveryEndpoint();
}
public FindResponse FindServices(FindCriteria findCriteria, out ASBDiscoveryResult Result)
{
Result = ASBDiscoveryResult.Unknown;
string text = SvcUtilities.GetDiscoveryEndpoint();
if (!string.IsNullOrEmpty(text))
{
if (!text.ToLower().EndsWith("/probe"))
{
text += "/Probe";
}
return InternalFindServices(text, findCriteria, out Result);
}
Result = ASBDiscoveryResult.DiscoveryNotAvailable;
return null;
}
public EndpointDiscoveryMetadata FindServiceEndpoint(Type ContractType, Uri[] Scopes, out ASBDiscoveryResult Result)
{
Result = ASBDiscoveryResult.Unknown;
string text = SvcUtilities.GetDiscoveryEndpoint();
if (!string.IsNullOrEmpty(text))
{
if (!text.ToLower().EndsWith("/probe"))
{
text += "/Probe";
}
Uri probeEndpointAddress = new Uri(text);
return InternalFindServiceEndpoint(ContractType.Name, Scopes, probeEndpointAddress, out Result);
}
Result = ASBDiscoveryResult.DiscoveryNotAvailable;
return null;
}
public RegistrationResult UnPairRemoteSR(string RemoteRepositoryNode, out string errorMessage)
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "UnPairRemoteSR Entered");
string SRNodeName = string.Empty;
errorMessage = string.Empty;
RegistryHandler.GetSrNode(out SRNodeName);
RegistrationResult registrationResult = RegistrationResult.Success;
if (HostNameValidator.IsRemoteNodeSameasSRNode(RemoteRepositoryNode, SRNodeName))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, "UnPairRemoteSR failed: Un-pairing to same SRNode is not allowed");
registrationResult = RegistrationResult.NodeInaccessible;
}
else
{
string remoteSolutionName = "Archestra_" + RemoteRepositoryNode;
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, string.Format("UnPairRemoteSR called for solution '{0}'", string.IsNullOrEmpty(RemoteRepositoryNode) ? "<Empty>" : RemoteRepositoryNode));
SynchronizeSolutionsWithSR();
registrationResult = new ManageSecurityConfiguration().UnPairRemoteSR(remoteSolutionName, out errorMessage);
if (registrationResult != RegistrationResult.Success)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, $"UnPairRemoteSR failed: {errorMessage}");
}
}
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "UnPairRemoteSR Exit");
return registrationResult;
}
public static string ConvertToString(SecureString password)
{
if (password == null)
{
return string.Empty;
}
IntPtr intPtr = IntPtr.Zero;
try
{
intPtr = Marshal.SecureStringToGlobalAllocUnicode(password);
return Marshal.PtrToStringUni(intPtr);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(intPtr);
}
}
private FindResponse InternalFindServices(string discoveryendpoint, FindCriteria findiCriteria, out ASBDiscoveryResult Result)
{
if (string.IsNullOrEmpty(discoveryendpoint))
{
Result = ASBDiscoveryResult.DiscoveryBadParameters;
return null;
}
if (findiCriteria == null)
{
Result = ASBDiscoveryResult.DiscoveryBadParameters;
return null;
}
Result = ASBDiscoveryResult.Unknown;
try
{
Uri uri = new Uri(discoveryendpoint);
EndpointAddress endpointAddress = new EndpointAddress(uri);
using DiscoveryClient discoveryClient = new DiscoveryClient(new DiscoveryEndpoint(SvcUtilities.GetBinding(uri.ToString()), endpointAddress));
FindResponse findResponse = discoveryClient.Find(findiCriteria);
if (findResponse != null && findResponse.Endpoints.Count > 0)
{
Result = ASBDiscoveryResult.Success;
}
else
{
Result = ASBDiscoveryResult.DiscoveryReturnedNoEndpoints;
}
return findResponse;
}
catch (Exception)
{
}
return null;
}
private EndpointDiscoveryMetadata InternalFindServiceEndpoint(string ContractName, Uri[] Scopes, Uri probeEndpointAddress, out ASBDiscoveryResult Result)
{
if (string.IsNullOrEmpty(ContractName))
{
Result = ASBDiscoveryResult.DiscoveryBadParameters;
return null;
}
if (probeEndpointAddress == null)
{
Result = ASBDiscoveryResult.DiscoveryBadParameters;
return null;
}
EndpointAddress endpointAddress = new EndpointAddress(probeEndpointAddress);
using (DiscoveryClient discoveryClient = new DiscoveryClient(new DiscoveryEndpoint(SvcUtilities.GetBinding(probeEndpointAddress.ToString()), endpointAddress)))
{
FindCriteria findCriteria = new FindCriteria();
Result = ASBDiscoveryResult.Unknown;
try
{
XmlQualifiedName item = new XmlQualifiedName(ContractName, "http://ArchestrAServices.Contract");
findCriteria.ContractTypeNames.Add(item);
findCriteria.Scopes.Concat(Scopes.ToList());
FindResponse findResponse = discoveryClient.Find(findCriteria);
if (findResponse != null && findResponse.Endpoints.Count > 0)
{
Result = ASBDiscoveryResult.Success;
return findResponse.Endpoints[0];
}
Result = ASBDiscoveryResult.DiscoveryReturnedNoEndpoints;
}
catch (TargetInvocationException)
{
}
catch (UriFormatException)
{
}
}
return null;
}
}
@@ -0,0 +1,10 @@
namespace ASBClientAccessLayer;
public enum ASBDiscoveryResult
{
Success = 0,
DiscoveryNotAvailable = 1,
DiscoveryReturnedNoEndpoints = 2,
DiscoveryBadParameters = 3,
Unknown = 65535
}
@@ -0,0 +1,10 @@
namespace ASBClientAccessLayer;
public enum ASBDiscoveryResult1
{
Success = 0,
DiscoveryNotAvailable = 1,
DiscoveryReturnedNoEndpoints = 2,
DiscoveryBadParameters = 3,
Unknown = 65535
}
@@ -0,0 +1,104 @@
#define TRACE
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Discovery;
using System.Xml;
using ArchestrAServices.Common;
namespace ASBClientAccessLayer;
public class ClientAccessUtilities
{
private Random random = new Random();
public ClientAccessUtilities()
{
random = new Random(Environment.TickCount);
}
public EndpointDiscoveryMetadata FindServiceEndpoint(Type ContractType, Uri[] Scopes, out ASBDiscoveryResult1 Result)
{
Collection<Uri> scopes = new Collection<Uri>(Scopes.ToList());
return FindServiceEndpoint(ContractType.Name, scopes, out Result);
}
public EndpointDiscoveryMetadata FindServiceEndpoint(string ContractTypeName, Collection<Uri> Scopes, out ASBDiscoveryResult1 Result)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"FindServiceEndpoint -- Enter");
Result = ASBDiscoveryResult1.Unknown;
string text = SvcUtilities.GetDiscoveryEndpoint();
if (!string.IsNullOrEmpty(text))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"FindServiceEndpoint -- DiscoveryEndPoint {text} method");
if (!text.ToLower().EndsWith("/probe"))
{
text += "/Probe";
}
Uri probeEndpointAddress = new Uri(text);
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"FindServiceEndpoint -- calling InternalFindServiceEndpoint() method");
return InternalFindServiceEndpoint(ContractTypeName, Scopes, probeEndpointAddress, out Result);
}
Result = ASBDiscoveryResult1.DiscoveryNotAvailable;
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"FindServiceEndpoint -- Exit");
return null;
}
private EndpointDiscoveryMetadata InternalFindServiceEndpoint(string ContractName, Collection<Uri> Scopes, Uri probeEndpointAddress, out ASBDiscoveryResult1 Result)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Warning, 0, $"InternalFindServiceEndpoint() Enter");
if (string.IsNullOrEmpty(ContractName))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Warning, 0, $"InternalFindServiceEndpoint() Empty contact name");
Result = ASBDiscoveryResult1.DiscoveryBadParameters;
return null;
}
if (probeEndpointAddress == null)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Warning, 0, $"InternalFindServiceEndpoint() probeEndpointAddress is null");
Result = ASBDiscoveryResult1.DiscoveryBadParameters;
return null;
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"InternalFindServiceEndpoint() initializing...");
EndpointAddress endpointAddress = new EndpointAddress(probeEndpointAddress);
using (DiscoveryClient discoveryClient = new DiscoveryClient(new DiscoveryEndpoint(SvcUtilities.GetBinding(probeEndpointAddress.ToString()), endpointAddress)))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"InternalFindServiceEndpoint() Creating FindCriteria instance ...");
FindCriteria findCriteria = new FindCriteria();
Result = ASBDiscoveryResult1.Unknown;
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"FindServiceEndpoint finding services with interface {ContractName} and {findCriteria.Scopes.Count()} scopes");
try
{
XmlQualifiedName item = new XmlQualifiedName(ContractName, "http://ArchestrAServices.Contract");
findCriteria.ContractTypeNames.Add(item);
foreach (Uri Scope in Scopes)
{
findCriteria.Scopes.Add(Scope);
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"FindServiceEndpoint finding services with interface {ContractName} and {findCriteria.Scopes.Count()} scopes");
foreach (Uri scope in findCriteria.Scopes)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $" {scope.AbsoluteUri.ToString()}");
}
FindResponse findResponse = discoveryClient.Find(findCriteria);
if (findResponse != null && findResponse.Endpoints.Count > 0)
{
Result = ASBDiscoveryResult1.Success;
return findResponse.Endpoints[random.Next(findResponse.Endpoints.Count())];
}
Result = ASBDiscoveryResult1.DiscoveryReturnedNoEndpoints;
}
catch (TargetInvocationException)
{
}
catch (UriFormatException)
{
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"InternalFindServiceEndpoint() Enter");
}
return null;
}
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Security;
using System.ServiceModel.Discovery;
using ArchestrAServices.Contract;
namespace ASBClientAccessLayer;
public interface IASBClient
{
bool Connected { get; }
bool Reconnect();
bool Disconnect();
ArchestrAResult OpenTemporaryRegistrationEndpoint(string repositoryNode, SecureString passphrase);
ArchestrAResult CloseTemporaryRegistrationEndpoint(string repositoryNode);
ArchestrAResult OpenTemporaryPairingEndpoint(string repositoryNode, SecureString passphrase);
ArchestrAResult CloseTemporaryPairingEndpoint(string repositoryNode);
ArchestrAResult GetRegistrationEndpointStatus(string repositoryNode, out List<TemporaryEndpointStatus> ConfigurationData);
RegistrationResult RegisterWithSR(string repositoryNode, SecureString passphrase);
RegistrationResult CopySolutionFromSR(string repositoryNode, SecureString passphrase, string solutionName);
RegistrationResult RemoveSolutionFromThisNode(string solutionName);
string GetPassphraseForSolution(string solutionName);
RegistrationResult UnregisterWithSR(string repositoryNode);
RegistrationResult PairSRNodes(string remoteRepositoryNode, SecureString passphrase);
RegistrationResult UnpairSRNodes(string repositoryNode);
string GetChangedASBExtraInfo();
List<string> GetPairedSolutionsInSR(string repositoryNode);
List<string> GetSolutionsAtThisNode();
string GetDiscoveryEndpoint();
FindResponse FindServices(FindCriteria findCriteria, out ASBDiscoveryResult Result);
EndpointDiscoveryMetadata FindServiceEndpoint(Type ContractType, Uri[] Scopes, out ASBDiscoveryResult Result);
}
@@ -0,0 +1,6 @@
namespace ASBClientAccessLayer;
public interface IASBClient1 : IASBClient
{
RegistrationResult UnPairRemoteSR(string RemoteRepositoryNode, out string errorMessage);
}
@@ -0,0 +1,804 @@
#define TRACE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.Text;
using ArchestrAServices.Common;
using ArchestrAServices.Contract;
using ArchestrAServices.Proxy;
using Microsoft.Win32;
namespace ASBClientAccessLayer;
public class ManageSecurityConfiguration
{
public string RegisterSecurityConfiguration(SystemAuthenticationASBConfiguration ConfigurationData, string xmlExtraInfo, string srNodeName, bool isRegister)
{
string empty = string.Empty;
try
{
ASBConfigurationInformation aSBConfigurationInformation = new ASBConfigurationInformation();
ConfigurationData = GetConfigurationInformation(ConfigurationData, aSBConfigurationInformation);
aSBConfigurationInformation.InitializationVector = ValidateSecurityConfiguration(ConfigurationData.initializationVector);
aSBConfigurationInformation.SolutionName = ConfigurationData.solutionName;
aSBConfigurationInformation.KeySize = ConfigurationData.keySize;
aSBConfigurationInformation.PasswordDerivationIterations = ConfigurationData.passwordDerivationIterations;
aSBConfigurationInformation.Prime = ValidateSecurityConfiguration(ConfigurationData.prime);
aSBConfigurationInformation.SaltValue = ValidateSecurityConfiguration(ConfigurationData.saltValue);
aSBConfigurationInformation.IsDefault = ConfigurationData.isDefault;
aSBConfigurationInformation.SRNodeName = ConfigurationData.srNodeName;
Dictionary<string, string> dictionary = RegistryHandler.ParseXMLExtraInfo(xmlExtraInfo);
string value = string.Empty;
string value2 = string.Empty;
string value3 = string.Empty;
string value4 = string.Empty;
dictionary.TryGetValue("PrimaryGlobalDiscovery", out value);
dictionary.TryGetValue("SecondaryGlobalDiscovery", out value2);
dictionary.TryGetValue("PrimaryUniversalDiscovery", out value3);
dictionary.TryGetValue("SecondaryUniversalDiscovery", out value4);
aSBConfigurationInformation.PrimaryGlobalDiscovery = value;
aSBConfigurationInformation.SecondaryGlobalDiscovery = value2;
aSBConfigurationInformation.PrimaryUniversalDiscovery = value3;
aSBConfigurationInformation.SecondaryUniversalDiscovery = value4;
return RegistryHandler.CreateASBConfigInfoStructureInRegistry(aSBConfigurationInformation, srNodeName, isRegister);
}
catch (Exception ex)
{
return ex.Message;
}
}
private static SystemAuthenticationASBConfiguration GetConfigurationInformation(SystemAuthenticationASBConfiguration ConfigurationData, ASBConfigurationInformation asbConfigurationInformation)
{
if (ConfigurationData.EncryptedCertificate != null)
{
asbConfigurationInformation.EncryptedCertificate = ValidateSecurityConfiguration(ConfigurationData.EncryptedCertificate);
}
if (ConfigurationData.EncryptedSharedSecret != null)
{
asbConfigurationInformation.EncryptedSharedSecret = ValidateSecurityConfiguration(ConfigurationData.EncryptedSharedSecret);
}
asbConfigurationInformation.Generator = ValidateSecurityConfiguration(ConfigurationData.generator);
if (!string.IsNullOrEmpty(ConfigurationData.hashAlgorithm))
{
asbConfigurationInformation.HashAlgorithm = ConfigurationData.hashAlgorithm;
}
else
{
asbConfigurationInformation.HashAlgorithm = string.Empty;
}
return ConfigurationData;
}
public string GetPassphraseForSolution(string solutionName)
{
string passphrase = string.Empty;
_ = string.Empty;
RegistryHandler.GetSolutionPassphrase(solutionName, out passphrase);
if (string.IsNullOrEmpty(passphrase))
{
string SRNodeName = string.Empty;
RegistryHandler.GetSrNode(out SRNodeName);
string passphrase2 = string.Empty;
RegistryHandler.GetSolutionPassphrase(string.Empty, out passphrase2);
Registration(SRNodeName, passphrase2, solutionName, isRegister: false);
RegistryHandler.GetSolutionPassphrase(solutionName, out passphrase);
}
return passphrase;
}
public string Registration(string srNode, string passPhrase, string SolutionName, bool isRegister)
{
return Registration(null, srNode, passPhrase, SolutionName, isRegister);
}
public string Registration(ManageASBSecurityProxy AsbSecurityProxy, string srNode, string passPhrase, string SolutionName, bool isRegister)
{
string errorMessage = string.Empty;
ManageASBSecurityProxy manageASBSecurityProxy = AsbSecurityProxy;
if (isRegister)
{
if (manageASBSecurityProxy == null)
{
manageASBSecurityProxy = new ManageASBSecurityProxy(srNode);
string text = SystemAuthenticationConstants.MakeTemporaryRegistrationEndpointAddress(srNode);
bool flag;
switch (RegistryHandler.SecureCommunicationMode)
{
case SecureCommunicationModes.Required:
flag = ConnectTemporaryEndpoint(passPhrase, text + "S", manageASBSecurityProxy, out errorMessage);
break;
case SecureCommunicationModes.Preferred:
flag = ConnectTemporaryEndpoint(passPhrase, text + "S", manageASBSecurityProxy, out errorMessage);
if (!flag)
{
flag = ConnectTemporaryEndpoint(passPhrase, text, manageASBSecurityProxy, out errorMessage);
}
break;
default:
flag = ConnectTemporaryEndpoint(passPhrase, text, manageASBSecurityProxy, out errorMessage);
break;
}
if (!flag)
{
errorMessage = "Registration(true) failed to connect to temporary endpoint: " + errorMessage;
}
CheckProxyState(manageASBSecurityProxy, isRegister, out errorMessage);
}
else
{
CheckProxyState(manageASBSecurityProxy, isRegister, out errorMessage);
}
}
else if (manageASBSecurityProxy == null)
{
manageASBSecurityProxy = new ManageASBSecurityProxy(srNode);
if (!manageASBSecurityProxy.Connect(passPhrase, out errorMessage))
{
errorMessage = "Registration(false) failed to connect to temporary endpoint: " + errorMessage;
}
CheckProxyState(manageASBSecurityProxy, isRegister, out errorMessage);
}
else
{
CheckProxyState(manageASBSecurityProxy, isRegister, out errorMessage);
}
if (string.IsNullOrEmpty(errorMessage))
{
SystemAuthenticationASBConfiguration ConfigurationData = default(SystemAuthenticationASBConfiguration);
string XMLExtraInfo = string.Empty;
ArchestrAResult serviceBusPlatformConfiguration = manageASBSecurityProxy.GetServiceBusPlatformConfiguration(out ConfigurationData, out XMLExtraInfo, default(Guid), string.IsNullOrEmpty(SolutionName) ? ("Register/" + srNode) : SolutionName);
errorMessage = ((serviceBusPlatformConfiguration.Status != 0) ? ("Failed to get SecurityConfiguration from SystemAuthentication service with Status = " + serviceBusPlatformConfiguration.Status) : RegisterSecurityConfiguration(ConfigurationData, XMLExtraInfo, srNode, isRegister));
}
return errorMessage;
}
private bool ConnectTemporaryEndpoint(string passPhrase, string endpoint, ManageASBSecurityProxy proxy, out string errorMessage)
{
return proxy.Connect(passPhrase, endpoint, out errorMessage);
}
private void CheckProxyState(ManageASBSecurityProxy Proxy, bool isRegister, out string errorMessage)
{
errorMessage = string.Empty;
if (Proxy.State != CommunicationState.Opened || !Proxy.SecureSessionEstablished)
{
errorMessage = $"Registration({isRegister.ToString().ToLower()}) proxy not connected to ASB endpoint";
}
}
public string UnRegistration(string repositoryNode)
{
string text = string.Empty;
string SRNodeName = repositoryNode;
if (string.IsNullOrEmpty(SRNodeName))
{
text = RegistryHandler.GetSrNode(out SRNodeName);
}
if (string.IsNullOrEmpty(SRNodeName))
{
text = "Node is currently not registed to service repository node";
}
if (!string.IsNullOrEmpty(ValidateSRNode(SRNodeName)))
{
text = "Invalid SRNode";
}
if (string.IsNullOrEmpty(ValidateSRNode(text)))
{
text = DeleteSecurityConfiguration(SRNodeName);
}
return text;
}
public string PairDefaultSRwithRemoteSR(string remoteRepositoryNode, string remoteRepositoryPairingPassphrase)
{
string empty = string.Empty;
ManageASBSecurityProxy DefaultProxy = null;
ManageASBSecurityProxy RemoteProxy = null;
try
{
empty = ConnectToDefaultAndRemoteSR(remoteRepositoryNode, remoteRepositoryPairingPassphrase, out DefaultProxy, out RemoteProxy);
if (string.IsNullOrEmpty(empty))
{
empty = ExchangeBetweenDefaultAndRemoteSR(remoteRepositoryNode, DefaultProxy, RemoteProxy);
}
}
catch (Exception ex)
{
empty = "Caught exception during pairing: " + ex.Message;
}
try
{
DefaultProxy?.Disconnect();
RemoteProxy?.Disconnect();
}
catch (Exception ex2)
{
empty = "Caught exception cleaning up after pairing: " + ex2.Message;
}
return empty;
}
private string ConnectToDefaultAndRemoteSR(string remoteRepositoryNode, string remoteRepositoryPairingPassphrase, out ManageASBSecurityProxy DefaultProxy, out ManageASBSecurityProxy RemoteProxy)
{
string empty = string.Empty;
DefaultProxy = null;
RemoteProxy = null;
empty = RegistryHandler.GetSrNode(out var SRNodeName);
if (!string.IsNullOrEmpty(empty))
{
return empty;
}
try
{
string text = SystemAuthenticationConstants.MakeTemporaryPairingEndpointAddress(remoteRepositoryNode);
RemoteProxy = new ManageASBSecurityProxy(remoteRepositoryNode);
bool flag;
switch (RegistryHandler.SecureCommunicationMode)
{
case SecureCommunicationModes.Required:
flag = ConnectTemporaryEndpoint(remoteRepositoryPairingPassphrase, text + "S", RemoteProxy, out empty);
break;
case SecureCommunicationModes.Preferred:
flag = ConnectTemporaryEndpoint(remoteRepositoryPairingPassphrase, text + "S", RemoteProxy, out empty);
if (!flag)
{
flag = ConnectTemporaryEndpoint(remoteRepositoryPairingPassphrase, text, RemoteProxy, out empty);
}
break;
default:
flag = ConnectTemporaryEndpoint(remoteRepositoryPairingPassphrase, text, RemoteProxy, out empty);
break;
}
if (!flag)
{
empty = "Failed to connect to SystemAuthentication service at remote SR " + remoteRepositoryNode;
}
}
catch (Exception ex)
{
empty = "ConnectToDefaultAndRemoteSR exception attempting to connect to temporary pairing endpoint on default SR: " + ex.Message;
}
if (string.IsNullOrEmpty(empty))
{
try
{
DefaultProxy = new ManageASBSecurityProxy(SRNodeName);
if (!DefaultProxy.Connect(string.Empty, out empty))
{
if (RemoteProxy != null)
{
RemoteProxy.Disconnect();
RemoteProxy = null;
}
empty = "Failed to connect to SystemAuthentication service at default SR ";
}
}
catch (Exception ex2)
{
empty = "ConnectToDefaultAndRemoteSR exception attempting to connect to ASB endpoint on SR " + SRNodeName + ": " + ex2.Message;
}
}
return empty;
}
private string ExchangeBetweenDefaultAndRemoteSR(string remoteRepositoryNode, ManageASBSecurityProxy DefaultProxy, ManageASBSecurityProxy RemoteProxy)
{
string text = string.Empty;
if (DefaultProxy == null)
{
return "ExchangeBetweenDefaultAndRemoteSR called without a connection to the default SR node";
}
if (RemoteProxy == null)
{
return "ExchangeBetweenDefaultAndRemoteSR called without a connection to the remote SR node";
}
RegistryHandler.GetSrNode(out var SRNodeName);
SystemAuthenticationASBConfiguration ConfigurationData = default(SystemAuthenticationASBConfiguration);
string XMLExtraInfo = string.Empty;
SystemAuthenticationASBConfiguration ConfigurationData2 = default(SystemAuthenticationASBConfiguration);
string XMLExtraInfo2 = string.Empty;
try
{
ArchestrAResult serviceBusPlatformConfiguration = RemoteProxy.GetServiceBusPlatformConfiguration(out ConfigurationData, out XMLExtraInfo, default(Guid), "Register/" + remoteRepositoryNode);
if (serviceBusPlatformConfiguration.Status != 0)
{
text = "Failed to get SecurityConfiguration from remote SR '" + remoteRepositoryNode + "' with status " + serviceBusPlatformConfiguration.Status;
}
}
catch (Exception ex)
{
text = "ExchangeBetweenDefaultAndRemoteSR exception reading default configuration from remote SR Node :" + ex.Message;
}
if (string.IsNullOrEmpty(text))
{
try
{
ArchestrAResult serviceBusPlatformConfiguration2 = DefaultProxy.GetServiceBusPlatformConfiguration(out ConfigurationData2, out XMLExtraInfo2, default(Guid), "Register/" + SRNodeName);
if (serviceBusPlatformConfiguration2.Status != 0)
{
text = "Failed to get SecurityConfiguration from default SR '" + SRNodeName + "' with status " + serviceBusPlatformConfiguration2.Status;
}
}
catch (Exception ex2)
{
text = "ExchangeBetweenDefaultAndRemoteSR exception reading default configuration from default SR Node :" + ex2.Message;
}
}
bool flag = false;
if (string.IsNullOrEmpty(text))
{
Dictionary<string, string> dictionary = RegistryHandler.ParseXMLExtraInfo(XMLExtraInfo);
Dictionary<string, string> dictionary2 = RegistryHandler.ParseXMLExtraInfo(XMLExtraInfo2);
if (dictionary.TryGetValue(RegistryHandler.PUDSEndPoint, out var value) && !string.IsNullOrEmpty(value))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "Remote PUDS endpoint is configured: {0}", value);
if (dictionary2.TryGetValue(RegistryHandler.PUDSEndPoint, out var value2) && string.IsNullOrEmpty(value2))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "Default PUDS endpoint is configured but empty, copying remote to default and settint writeback flag");
dictionary2[RegistryHandler.PUDSEndPoint] = dictionary[RegistryHandler.PUDSEndPoint];
flag = true;
}
else if (!dictionary2.TryGetValue(RegistryHandler.PUDSEndPoint, out value2))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "Default PUDS endpoint is NOT configured");
}
else if (!string.IsNullOrEmpty(value2))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "Default PUDS endpoint is configured: {0}", value2);
}
}
else if (!dictionary.TryGetValue(RegistryHandler.PUDSEndPoint, out value))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "Remote PUDS endpoint is NOT configured");
}
else if (string.IsNullOrEmpty(value))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "Remote PUDS endpoint is configured but empty");
}
if (dictionary.TryGetValue(RegistryHandler.SUDSEndPoint, out var value3) && !string.IsNullOrEmpty(value3) && dictionary2.TryGetValue(RegistryHandler.SUDSEndPoint, out var value4) && string.IsNullOrEmpty(value4))
{
dictionary2[RegistryHandler.SUDSEndPoint] = dictionary[RegistryHandler.SUDSEndPoint];
flag = true;
}
if (flag)
{
XMLExtraInfo2 = RegistryHandler.GenerateXMLExtraInfo(dictionary2.ToList());
}
}
if (string.IsNullOrEmpty(text))
{
try
{
ConfigurationData2.isDefault = "false";
ArchestrAResult serviceBusPlatformConfiguration = RemoteProxy.RegisterSystemAuthenticationConfiguration(ConfigurationData2, XMLExtraInfo2);
if (serviceBusPlatformConfiguration.Status != 0)
{
text = "Failed to register SecurityConfiguration to remote SR '" + remoteRepositoryNode + "' with status " + serviceBusPlatformConfiguration.Status;
}
}
catch (Exception ex3)
{
text = "ExchangeBetweenDefaultAndRemoteSR exception writing default SR configuration to remote SR Node :" + ex3.Message;
}
try
{
ConfigurationData.isDefault = "false";
ArchestrAResult serviceBusPlatformConfiguration2 = DefaultProxy.RegisterSystemAuthenticationConfiguration(ConfigurationData, XMLExtraInfo);
if (serviceBusPlatformConfiguration2.Status != 0)
{
if (!string.IsNullOrEmpty(text))
{
text += " and ";
}
text = text + "Failed to register SecurityConfiguration to default SR '" + SRNodeName + "' with status " + serviceBusPlatformConfiguration2.Status;
}
if (flag)
{
ConfigurationData2.isDefault = "true";
serviceBusPlatformConfiguration2 = DefaultProxy.RegisterSystemAuthenticationConfiguration(ConfigurationData2, XMLExtraInfo2);
if (serviceBusPlatformConfiguration2.Status != 0)
{
if (!string.IsNullOrEmpty(text))
{
text += " and ";
}
text = text + "Failed to re-register UDS-modified default SecurityConfiguration to default SR '" + SRNodeName + "' with status " + serviceBusPlatformConfiguration2.Status;
}
}
}
catch (Exception ex4)
{
text = "ExchangeBetweenDefaultAndRemoteSR exception writing remote SR configuration to default SR Node :" + ex4.Message;
}
}
return text;
}
public string UnpairDefaultSRfromRemoteSR(string remoteSolutionName)
{
string empty = string.Empty;
empty = RegistryHandler.GetDefaultSolutionName(out var DefaultSolutionName);
if (!string.IsNullOrEmpty(empty))
{
return empty;
}
RegistryHandler.GetSrNode(out var SRNodeName);
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"UnpairDefaultSRfromRemoteSR using default solution name {DefaultSolutionName}, default SR Node {SRNodeName} and remote solution name {remoteSolutionName}");
ManageASBSecurityProxy DefaultProxy = null;
ManageASBSecurityProxy RemoteProxy = null;
try
{
empty = ConnectToDefaultAndRemoteSR(remoteSolutionName, out var remoteRepositoryNode, out DefaultProxy, out RemoteProxy);
if (!string.IsNullOrEmpty(empty))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"UnpairDefaultSRfromRemoteSR: ConnectToDefaultAndRemoteSR returned error: {empty}");
}
else
{
empty = DisconnectBetweenDefaultAndRemoteSR(remoteRepositoryNode, DefaultProxy, RemoteProxy);
if (!string.IsNullOrEmpty(empty))
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"UnpairDefaultSRfromRemoteSR: DisconnectBetweenDefaultAndRemoteSR returned error: {empty}");
}
}
}
catch (Exception ex)
{
empty = "Caught exception during unpairing: " + ex.Message;
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"Caught exception during unpairing: {ex.Message} {ex.StackTrace.ToString()}");
}
finally
{
DefaultProxy?.Disconnect();
RemoteProxy?.Disconnect();
}
return empty;
}
private string ConnectToDefaultAndRemoteSR(string remoteSolutionName, out string remoteRepositoryNode, out ManageASBSecurityProxy DefaultProxy, out ManageASBSecurityProxy RemoteProxy)
{
string empty = string.Empty;
DefaultProxy = null;
RemoteProxy = null;
remoteRepositoryNode = string.Empty;
try
{
empty = RegistryHandler.GetSrNode(out var SRNodeName);
if (!string.IsNullOrEmpty(empty))
{
return empty;
}
string passphraseForSolution = GetPassphraseForSolution(remoteSolutionName);
if (string.IsNullOrEmpty(passphraseForSolution))
{
return "Unable to obtain solution configuration and passphrase for remote solution " + remoteSolutionName;
}
empty = RegistryHandler.GetSrNode(remoteSolutionName, out remoteRepositoryNode);
if (!string.IsNullOrEmpty(empty))
{
return empty;
}
RemoteProxy = new ManageASBSecurityProxy(remoteRepositoryNode);
if (!RemoteProxy.Connect(passphraseForSolution, out empty))
{
empty = "Failed to connect to SystemAuthentication service at remote SR " + remoteRepositoryNode;
}
if (string.IsNullOrEmpty(empty))
{
DefaultProxy = new ManageASBSecurityProxy(SRNodeName);
if (!DefaultProxy.Connect(string.Empty, out empty))
{
RemoteProxy.Disconnect();
RemoteProxy = null;
empty = "Failed to connect to SystemAuthentication service at default SR " + SRNodeName;
}
}
}
catch (Exception ex)
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"ConnectToDefaultAndRemoteSR exception: {ex.Message}");
empty = "ConnectToDefaultAndRemoteSR exception: " + ex.Message;
}
return empty;
}
private string ConnectToDefaultSR(string DefaultSRNodeName, out ManageASBSecurityProxy DefaultProxy)
{
DefaultProxy = null;
string errorMessage = string.Empty;
try
{
DefaultProxy = new ManageASBSecurityProxy(DefaultSRNodeName);
if (!DefaultProxy.Connect(string.Empty, out errorMessage))
{
errorMessage = "Failed to connect to SystemAuthentication service at default SR " + DefaultSRNodeName;
}
}
catch (Exception ex)
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"ConnectToDefaultSR exception: {ex.Message}");
errorMessage = "ConnectToDefaultSR exception: " + ex.Message;
}
return errorMessage;
}
private string DisconnectBetweenDefaultAndRemoteSR(string remoteRepositoryNode, ManageASBSecurityProxy DefaultProxy, ManageASBSecurityProxy RemoteProxy)
{
string text = string.Empty;
if (DefaultProxy == null)
{
return "DisconnectBetweenDefaultAndRemoteSR called without a connection to the default SR node";
}
if (RemoteProxy == null)
{
return "DisconnectBetweenDefaultAndRemoteSR called without a connection to the remote SR node";
}
RegistryHandler.GetSrNode(out var SRNodeName);
SystemAuthenticationASBConfiguration ConfigurationData = default(SystemAuthenticationASBConfiguration);
string XMLExtraInfo = string.Empty;
SystemAuthenticationASBConfiguration ConfigurationData2 = default(SystemAuthenticationASBConfiguration);
string XMLExtraInfo2 = string.Empty;
ArchestrAResult serviceBusPlatformConfiguration = RemoteProxy.GetServiceBusPlatformConfiguration(out ConfigurationData, out XMLExtraInfo, default(Guid), "Register/" + remoteRepositoryNode);
if (serviceBusPlatformConfiguration.Status != 0)
{
text = "Failed to get SecurityConfiguration from remote SR '" + remoteRepositoryNode + "' with status " + serviceBusPlatformConfiguration.Status;
}
else
{
ArchestrAResult serviceBusPlatformConfiguration2 = DefaultProxy.GetServiceBusPlatformConfiguration(out ConfigurationData2, out XMLExtraInfo2, default(Guid), "Register/" + SRNodeName);
if (serviceBusPlatformConfiguration2.Status != 0)
{
text = "Failed to get SecurityConfiguration from default SR '" + SRNodeName + "' with status " + serviceBusPlatformConfiguration2.Status;
}
}
if (string.IsNullOrEmpty(text))
{
serviceBusPlatformConfiguration = RemoteProxy.UnregisterSystemAuthenticationConfiguration(ConfigurationData2.solutionName);
if (serviceBusPlatformConfiguration.Status != 0)
{
text = "Failed to delete default SecurityConfiguration from remote SR '" + remoteRepositoryNode + "' with status " + serviceBusPlatformConfiguration.Status;
}
ArchestrAResult serviceBusPlatformConfiguration2 = DefaultProxy.UnregisterSystemAuthenticationConfiguration(ConfigurationData.solutionName);
if (serviceBusPlatformConfiguration2.Status != 0)
{
if (!string.IsNullOrEmpty(text))
{
text += " and ";
}
text = text + "Failed to delete SecurityConfiguration from remote SR '" + SRNodeName + "' with status " + serviceBusPlatformConfiguration2.Status;
}
}
return text;
}
private string DisconnectRemoteSR(string remoteSolutionName, string remoteRepositoryNode, ManageASBSecurityProxy DefaultProxy)
{
string text = string.Empty;
if (DefaultProxy == null)
{
return "DisconnectRemoteSR called without a connection to the default SR node";
}
RegistryHandler.GetSrNode(out var SRNodeName);
ArchestrAResult archestrAResult = DefaultProxy.UnregisterSystemAuthenticationConfiguration(remoteSolutionName);
if (archestrAResult.Status != 0)
{
if (!string.IsNullOrEmpty(text))
{
text += " and ";
}
text = text + "Failed to delete Remote Solution '" + remoteSolutionName + "' SecurityConfiguration from default SR '" + SRNodeName + "' with status " + archestrAResult.Status;
SvcTrace.DiagException.TraceEvent(TraceEventType.Information, 0, $"DisconnectRemoteSR: {text}");
}
return text;
}
private string DeleteSecurityConfiguration(string srNode)
{
string errorMessage = string.Empty;
using (ManageASBSecurityProxy manageASBSecurityProxy = new ManageASBSecurityProxy(srNode))
{
if (manageASBSecurityProxy.Connect(string.Empty, out errorMessage))
{
SystemAuthenticationASBConfiguration ConfigurationData = default(SystemAuthenticationASBConfiguration);
string XMLExtraInfo = string.Empty;
ArchestrAResult serviceBusPlatformConfiguration = manageASBSecurityProxy.GetServiceBusPlatformConfiguration(out ConfigurationData, out XMLExtraInfo, default(Guid), "Unregister/" + srNode);
if (serviceBusPlatformConfiguration.ErrorCode == EnumASBFactory.ArchestrAErrorToInt(ArchestrAError.Success))
{
if (string.Compare(srNode, Environment.MachineName, ignoreCase: true) != 0)
{
errorMessage = RegistryHandler.DeleteFromRegistry(ConfigurationData.solutionName);
Registry.LocalMachine.DeleteSubKeyTree(RegistryHandler.ASBNodeRegistraion);
}
}
else
{
errorMessage = "failed to get SecurityConfiguration from SystemAuthentication service with status " + EnumASBFactory.IntToArchestrAError(serviceBusPlatformConfiguration.ErrorCode);
}
}
}
return errorMessage;
}
public string GetRemoteSolutionName(string srNode, string remoteNode)
{
string empty = string.Empty;
string empty2 = string.Empty;
List<string> SolutionNames = new List<string>();
empty2 = GetSolutionsPairedWithSR(null, srNode, out SolutionNames);
if (!string.IsNullOrEmpty(empty2))
{
return empty2;
}
string remoteSlnName = "Archestra_" + remoteNode;
empty = SolutionNames.Find((string x) => x.ToString() == remoteSlnName);
if (string.IsNullOrEmpty(empty))
{
return "Unable to find Remote Solution Name";
}
return empty;
}
public string GetSolutionsPairedWithSR(string srNode, out List<string> SolutionNames)
{
return GetSolutionsPairedWithSR(null, srNode, out SolutionNames);
}
public string GetSolutionsPairedWithSR(ManageASBSecurityProxy AsbSecurityProxy, string srNode, out List<string> SolutionNames)
{
SolutionNames = new List<string>();
string errorMessage = string.Empty;
ManageASBSecurityProxy manageASBSecurityProxy = AsbSecurityProxy;
if (manageASBSecurityProxy == null)
{
using (manageASBSecurityProxy = new ManageASBSecurityProxy(srNode))
{
manageASBSecurityProxy.Connect(string.Empty, out errorMessage);
errorMessage = GetSolutions(manageASBSecurityProxy, SolutionNames);
}
}
else
{
errorMessage = GetSolutions(manageASBSecurityProxy, SolutionNames);
}
return errorMessage;
}
private string GetSolutions(ManageASBSecurityProxy Proxy, List<string> SolutionNames)
{
string result = string.Empty;
if (Proxy.State == CommunicationState.Opened && Proxy.SecureSessionEstablished)
{
if (Proxy.EnumerateSolutions(out var SolutionNames2).Status != 0)
{
result = "failed to get solution names from SystemAuthentication service";
}
else
{
RegistryHandler.GetDefaultSolutionName(out var DefaultSolutionName);
string[] array = SolutionNames2;
foreach (string text in array)
{
if (string.Compare(text, DefaultSolutionName, StringComparison.OrdinalIgnoreCase) != 0 && !text.ToUpperInvariant().StartsWith("UNIVERSAL_"))
{
SolutionNames.Add(text);
}
}
}
}
return result;
}
public string ValidateSRNode(string srNode)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(srNode))
{
result = "Please provide valid SR Node ";
try
{
if (Dns.GetHostEntry(srNode) != null)
{
result = string.Empty;
}
}
catch (ArgumentNullException)
{
}
catch (ArgumentOutOfRangeException)
{
}
catch (ArgumentException)
{
}
catch (SocketException)
{
}
}
return result;
}
public RegistrationResult UnPairRemoteSR(string remoteSolutionName, out string errorMessage)
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "ManageSecurityConfig::UnPairRemoteSR Entered");
RegistrationResult result = RegistrationResult.Success;
errorMessage = string.Empty;
errorMessage = RegistryHandler.GetDefaultSolutionName(out var DefaultSolutionName);
if (!string.IsNullOrEmpty(errorMessage))
{
return RegistrationResult.RepositoryNodeNotConfigured;
}
errorMessage = RegistryHandler.GetSrNode(out var SRNodeName);
if (!string.IsNullOrEmpty(errorMessage))
{
return RegistrationResult.RepositoryNodeNotConfigured;
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"UnPairRemoteSR using default solution name {DefaultSolutionName}, default SR Node {SRNodeName} and remote solution name {remoteSolutionName}");
ManageASBSecurityProxy DefaultProxy = null;
try
{
errorMessage = ConnectToDefaultSR(SRNodeName, out DefaultProxy);
if (!string.IsNullOrEmpty(errorMessage))
{
result = RegistrationResult.NodeInaccessible;
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"UnPairRemoteSR: ConnectToDefaultSR returned error: {errorMessage}");
}
else
{
string SRNodeName2 = string.Empty;
errorMessage = RegistryHandler.GetSrNode(remoteSolutionName, out SRNodeName2);
if (!string.IsNullOrEmpty(errorMessage))
{
result = RegistrationResult.RepositoryNotFoundOnTargetNode;
}
string remoteSolutionName2 = GetRemoteSolutionName(SRNodeName, SRNodeName2);
errorMessage = DisconnectRemoteSR(remoteSolutionName2, SRNodeName2, DefaultProxy);
if (!string.IsNullOrEmpty(errorMessage))
{
result = RegistrationResult.Unknown;
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"UnPairRemoteSR: DisconnectRemoteSR returned error: {errorMessage}");
}
else
{
result = RegistrationResult.Success;
}
}
}
catch (Exception ex)
{
errorMessage = "Caught exception during unpairing: " + ex.Message;
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 0, $"Caught exception during unpairing: {ex.Message} {ex.StackTrace.ToString()}");
result = RegistrationResult.Unknown;
}
finally
{
DefaultProxy?.Disconnect();
}
SvcTrace.DiagControl.TraceEvent(TraceEventType.Information, 0, "ManageSecurityConfig::UnPairRemoteSR Exit");
return result;
}
private static string ValidateSecurityConfiguration(byte[] ConfigurationData)
{
string empty = string.Empty;
if (ConfigurationData != null)
{
return Encoding.Default.GetString(ConfigurationData);
}
return string.Empty;
}
private static int ValidateSecurityConfiguration(int ConfigurationData)
{
int num = 0;
if (ConfigurationData != 0)
{
return ConfigurationData;
}
return 0;
}
}
@@ -0,0 +1,11 @@
namespace ASBClientAccessLayer;
public enum RegistrationResult
{
Success = 0,
NodeInaccessible = 1,
RepositoryNotFoundOnTargetNode = 2,
IncorrectPassphrase = 3,
RepositoryNodeNotConfigured = 4,
Unknown = 65535
}
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using ArchestrAServices.Common;
using ArchestrAServices.Proxy;
namespace ASBClientAccessLayer;
[Obsolete("This class is provided for backward compatibility only and will be removed in a future release. If you are using this, contact the ASB team.")]
public class SrConfigurationMonitor : IDisposable
{
private readonly double _pollIntervalmSec = 5000.0;
private Timer _timer = new Timer();
private bool disposed;
private ManageASBSecurityProxy _sysAuthProxy;
private string m_PreviousPayload = string.Empty;
private bool _authSvcConnected;
public event EventHandler PayLoadChanged;
private void PollSrConfigurationChanges()
{
try
{
if (_sysAuthProxy != null && _authSvcConnected)
{
_sysAuthProxy.QueryExtraInfoChanges(out var XMLExtraInfo, Environment.MachineName);
if (string.Compare(m_PreviousPayload, XMLExtraInfo) != 0 && !string.IsNullOrEmpty(XMLExtraInfo))
{
EventArgs e = new EventArgs();
Dictionary<string, string> source = RegistryHandler.ParseXMLExtraInfo(XMLExtraInfo);
m_PreviousPayload = XMLExtraInfo;
RegistryHandler.UpdateDiscoveryInfos(source.ToList());
OnPayLoadChanged(e);
}
}
}
catch (Exception)
{
}
}
private void TimerElapsed(object sender, EventArgs eventArgs)
{
PollSrConfigurationChanges();
}
protected virtual void OnPayLoadChanged(EventArgs e)
{
if (this.PayLoadChanged != null)
{
this.PayLoadChanged(this, e);
}
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
if (_sysAuthProxy != null)
{
_sysAuthProxy.Disconnect();
_sysAuthProxy.Dispose();
_sysAuthProxy = null;
}
if (_timer != null)
{
_timer.Elapsed -= TimerElapsed;
_timer.Stop();
_timer.Dispose();
_timer = null;
}
}
disposed = true;
}
public void StartMonitoring()
{
_timer.Start();
string errorMessage = string.Empty;
_authSvcConnected = _sysAuthProxy.Connect(string.Empty, out errorMessage);
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
public SrConfigurationMonitor(double pollInterval)
{
if (pollInterval > 1.0)
{
_pollIntervalmSec = pollInterval;
}
_timer.Interval = pollInterval;
_timer.Elapsed += TimerElapsed;
_sysAuthProxy = new ManageASBSecurityProxy("G2G_1");
}
}
@@ -0,0 +1,47 @@
using System.Collections.Generic;
using ArchestrAServices.Common;
using Microsoft.Win32;
namespace ASBClientAccessLayer;
public class TempRegistryHandler
{
public static void UpdateDiscoveryInfos(Dictionary<string, string> dicvoeryInfos)
{
RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(RegistryHandler.RegistryPath + "NodeRegistration", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.None);
if (registryKey == null)
{
return;
}
foreach (KeyValuePair<string, string> dicvoeryInfo in dicvoeryInfos)
{
switch (dicvoeryInfo.Key)
{
case "PrimaryGlobalDiscovery":
WriteRegistryValue(registryKey, RegistryHandler.PGDSEndPoint, dicvoeryInfo.Value);
break;
case "SecondaryGlobalDiscovery":
WriteRegistryValue(registryKey, RegistryHandler.SGDSEndPoint, dicvoeryInfo.Value);
break;
case "PrimaryUniversalDiscovery":
WriteRegistryValue(registryKey, RegistryHandler.PUDSEndPoint, dicvoeryInfo.Value);
break;
case "SecondaryUniversalDiscovery":
WriteRegistryValue(registryKey, RegistryHandler.SUDSEndPoint, dicvoeryInfo.Value);
break;
}
}
}
private static void WriteRegistryValue(RegistryKey solutionKey, string key, string value)
{
if (!string.IsNullOrEmpty(value))
{
solutionKey.SetValue(key, value);
}
else
{
solutionKey.SetValue(key, string.Empty);
}
}
}
@@ -0,0 +1,23 @@
using System;
namespace ArchestrAServices.ASBContract;
public static class ASBEnumFactory
{
public static DataType IntToDataType(ushort iValue)
{
try
{
return (DataType)iValue;
}
catch (Exception)
{
return DataType.TypeUnknown;
}
}
public static ushort DataTypeToInt(DataType eValue)
{
return (ushort)eValue;
}
}
@@ -0,0 +1,8 @@
using System;
namespace ArchestrAServices.ASBContract;
public struct ConnectionId
{
public Guid Id;
}
@@ -0,0 +1,53 @@
namespace ArchestrAServices.ASBContract;
public enum DataType : ushort
{
TypeByte = 0,
TypeChar = 1,
TypeInt16 = 2,
TypeUInt16 = 3,
TypeInt32 = 4,
TypeUInt32 = 5,
TypeInt64 = 6,
TypeUInt64 = 7,
TypeFloat = 8,
TypeDouble = 9,
TypeString = 10,
TypeDateTime = 11,
TypeDuration = 12,
TypeGuid = 13,
TypeByteString = 14,
TypeLocaleID = 15,
TypeLocalizedText = 16,
TypeBool = 17,
TypeSByte = 18,
TypeErrorStatus = 19,
TypeEnum = 20,
TypeDataType = 21,
TypeSecurityClassification = 22,
TypeDataQuality = 23,
TypeByteArray = 40,
TypeCharArray = 41,
TypeInt16Array = 42,
TypeUInt16Array = 43,
TypeInt32Array = 44,
TypeUInt32Array = 45,
TypeInt64Array = 46,
TypeUInt64Array = 47,
TypeFloatArray = 48,
TypeDoubleArray = 49,
TypeStringArray = 50,
TypeDateTimeArray = 51,
TypeDurationArray = 52,
TypeGuidArray = 53,
TypeByteStringArray = 54,
TypeLocaleIDArray = 55,
TypeLocalizedTextArray = 56,
TypeBoolArray = 57,
TypeSByteArray = 58,
TypeEnumArray = 60,
TypeDataTypeArray = 61,
TypeSecurityClassificationArray = 62,
TypeDataQualityArray = 63,
TypeUnknown = ushort.MaxValue
}
@@ -0,0 +1,137 @@
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
namespace ArchestrAServices.Contract;
public class ASBCustomSerializer : XmlObjectSerializer
{
protected string m_ASBPrefix = "ASB";
protected Type m_Type;
protected bool m_IsArray;
protected bool m_IsCustomSerialization;
protected XmlObjectSerializer m_FallbackSerializer;
public ASBCustomSerializer(Type type, XmlObjectSerializer fallbackSerializer)
{
Type c = type;
m_IsArray = false;
if (null != type && type.IsArray)
{
m_IsArray = true;
c = type.GetElementType();
}
m_Type = type;
m_IsCustomSerialization = typeof(IASBCustomSerializableType).IsAssignableFrom(c);
m_FallbackSerializer = fallbackSerializer;
}
public override bool IsStartObject(XmlDictionaryReader reader)
{
bool flag = false;
if (m_IsCustomSerialization && reader != null)
{
return string.Compare(reader.LocalName, m_ASBPrefix, StringComparison.CurrentCultureIgnoreCase) == 0;
}
return m_FallbackSerializer.IsStartObject(reader);
}
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
object obj = null;
if (m_IsCustomSerialization && reader != null)
{
using MemoryStream memoryStream = new MemoryStream(reader.ReadElementContentAsBase64());
if (memoryStream != null && memoryStream.Length > 0)
{
BinaryReader binaryReader = new BinaryReader(memoryStream);
if (m_IsArray)
{
int num = binaryReader.ReadInt32();
if (num > 0)
{
Type elementType = m_Type.GetElementType();
if (null != elementType && Activator.CreateInstance(elementType) is IASBCustomSerializableType iASBCustomSerializableType)
{
obj = iASBCustomSerializableType.InitializeArrayFromStream(binaryReader, num);
}
}
}
else
{
obj = Activator.CreateInstance(m_Type);
((IASBCustomSerializableType)obj).InitializeFromStream(binaryReader);
}
}
}
else
{
obj = m_FallbackSerializer.ReadObject(reader, verifyObjectName);
}
return obj;
}
public override void WriteEndObject(XmlDictionaryWriter writer)
{
if (m_IsCustomSerialization && writer != null)
{
writer.WriteEndElement();
}
else
{
m_FallbackSerializer.WriteEndObject(writer);
}
}
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
if (m_IsCustomSerialization && writer != null)
{
MemoryStream memoryStream = new MemoryStream();
try
{
BinaryWriter bw = new BinaryWriter(memoryStream);
if (m_IsArray)
{
if (graph != null)
{
Type elementType = m_Type.GetElementType();
if (null != elementType && Activator.CreateInstance(elementType) is IASBCustomSerializableType iASBCustomSerializableType)
{
iASBCustomSerializableType.WriteArrayToStream(graph, ref bw);
}
}
}
else
{
((IASBCustomSerializableType)graph).WriteToStream(bw);
}
byte[] array = memoryStream.ToArray();
writer.WriteBase64(array, 0, array.Length);
return;
}
finally
{
memoryStream.Dispose();
}
}
m_FallbackSerializer.WriteObjectContent(writer, graph);
}
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
if (m_IsCustomSerialization && writer != null)
{
writer.WriteStartElement(m_ASBPrefix);
}
else
{
m_FallbackSerializer.WriteStartObject(writer, graph);
}
}
}
@@ -0,0 +1,104 @@
#define TRACE
using System;
using System.Diagnostics;
using System.Globalization;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public class ASBCustomSerializerContractBehavior<T> : IContractBehavior
{
public virtual void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public virtual void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
ReplaceSerializerOperationBehavior(contractDescription);
}
public virtual void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
ReplaceSerializerOperationBehavior(contractDescription);
}
public virtual void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
if (contractDescription == null)
{
return;
}
foreach (OperationDescription operation in contractDescription.Operations)
{
foreach (MessageDescription message in operation.Messages)
{
ValidateMessagePartDescription(message.Body.ReturnValue);
foreach (MessagePartDescription part in message.Body.Parts)
{
ValidateMessagePartDescription(part);
}
foreach (MessageHeaderDescription header in message.Headers)
{
ValidateCustomSerializableType(header.Type);
}
}
}
}
protected virtual void ValidateMessagePartDescription(MessagePartDescription part)
{
if (part != null)
{
ValidateCustomSerializableType(part.Type);
}
}
protected virtual void ValidateCustomSerializableType(Type type)
{
Type type2 = type;
if (null != type && type.IsArray)
{
type2 = type.GetElementType();
}
if (typeof(IASBCustomSerializableType).IsAssignableFrom(type2))
{
if (!type2.IsPublic)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "ASBCustomSerializerContractBehaviorAttribute:ValidateCustomSerializableType- Custom serialization is supported in public types only"));
}
if (type2.IsClass && type2.GetConstructor(new Type[0]) == null)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Warning, 0, string.Format(CultureInfo.CurrentCulture, "ASBCustomSerializerContractBehaviorAttribute:ValidateCustomSerializableType- Custom serializable types must have a public, parameterless constructor"));
}
}
}
protected virtual void ReplaceSerializerOperationBehavior(ContractDescription contract)
{
if (contract == null)
{
return;
}
foreach (OperationDescription operation in contract.Operations)
{
for (int i = 0; i < operation.Behaviors.Count; i++)
{
if (operation.Behaviors[i] is DataContractSerializerOperationBehavior)
{
if (typeof(DataContractSerializerOperationBehavior).IsAssignableFrom(typeof(T)))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "Replacing the default serialization with ASB-Specific custom serialization"));
operation.Behaviors[i] = Activator.CreateInstance(typeof(T), operation) as DataContractSerializerOperationBehavior;
}
else
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Warning, 0, string.Format(CultureInfo.CurrentCulture, "ASBCustomSerializerOperationBehavior:CreateSerializer-failed to create instance for DataContractSerializerOperationBehavior. Invalid type <T> {0}", new object[1] { typeof(T).FullName }));
}
}
}
}
}
}
@@ -0,0 +1,108 @@
#define TRACE
using System;
using System.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public class ASBCustomSerializerContractBehaviorAttribute : Attribute, IContractBehavior
{
private Type _serializerOperationBehaviorType;
private ASBCustomSerializerContractBehaviorAttribute()
{
}
public ASBCustomSerializerContractBehaviorAttribute(Type SerializerOperationBehaviorType)
{
_serializerOperationBehaviorType = SerializerOperationBehaviorType;
}
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
ReplaceSerializerOperationBehavior(contractDescription);
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
ReplaceSerializerOperationBehavior(contractDescription);
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
foreach (OperationDescription operation in contractDescription.Operations)
{
foreach (MessageDescription message in operation.Messages)
{
ValidateMessagePartDescription(message.Body.ReturnValue);
foreach (MessagePartDescription part in message.Body.Parts)
{
ValidateMessagePartDescription(part);
}
foreach (MessageHeaderDescription header in message.Headers)
{
ValidateCustomSerializableType(header.Type);
}
}
}
}
protected void ValidateMessagePartDescription(MessagePartDescription part)
{
if (part != null)
{
ValidateCustomSerializableType(part.Type);
}
}
protected void ValidateCustomSerializableType(Type type)
{
Type type2 = type;
if (type.IsArray)
{
type2 = type.GetElementType();
}
if (typeof(IASBCustomSerializableType).IsAssignableFrom(type2))
{
if (!type2.IsPublic)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, $"ASBCustomSerializerContractBehaviorAttribute:ValidateCustomSerializableType- Custom serialization is supported in public types only");
}
if (type2.IsClass && type2.GetConstructor(new Type[0]) == null)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Warning, 0, $"ASBCustomSerializerContractBehaviorAttribute:ValidateCustomSerializableType- Custom serializable types must have a public, parameterless constructor");
}
}
}
protected void ReplaceSerializerOperationBehavior(ContractDescription contract)
{
if (contract == null)
{
return;
}
if (_serializerOperationBehaviorType == null || !typeof(DataContractSerializerOperationBehavior).IsAssignableFrom(_serializerOperationBehaviorType))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Warning, 0, "ASBCustomSerializerOperationBehavior:CreateSerializer-failed to create instance for DataContractSerializerOperationBehavior. Invalid type {0}", (_serializerOperationBehaviorType == null) ? "<null>" : _serializerOperationBehaviorType.FullName);
return;
}
foreach (OperationDescription operation in contract.Operations)
{
for (int i = 0; i < operation.Behaviors.Count; i++)
{
if (operation.Behaviors[i] is DataContractSerializerOperationBehavior)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, "Replacing the default serialization with ASB-Specific custom serialization");
operation.Behaviors[i] = Activator.CreateInstance(_serializerOperationBehaviorType, operation) as DataContractSerializerOperationBehavior;
}
}
}
}
}
@@ -0,0 +1,82 @@
using System;
namespace ArchestrAServices.Contract;
public static class ASBSerializer
{
public static ASBStatus ASBStatusFromArray(ASBStatusElement[] status)
{
ASBStatus result = new ASBStatus
{
Count = 0
};
if (status == null)
{
return result;
}
ushort num = 0;
ASBStatusElement[] array = status;
for (int i = 0; i < array.Length; i++)
{
num = ((array[i].statusValue != 0) ? ((ushort)(num + 3)) : ((ushort)(num + 1)));
}
if (num > 255)
{
throw new IndexOutOfRangeException("Too many ASBStatusElements in ASBStatusFromArray");
}
byte[] array2 = new byte[num];
num = 0;
array = status;
for (int i = 0; i < array.Length; i++)
{
ASBStatusElement aSBStatusElement = array[i];
if (aSBStatusElement.statusValue == 0)
{
array2[num++] = (byte)(((byte)aSBStatusElement.statusType & 0x7F) | 0x80);
continue;
}
array2[num++] = (byte)((byte)aSBStatusElement.statusType & 0x7F);
byte[] array3 = new byte[2];
array3 = BitConverter.GetBytes(aSBStatusElement.statusValue);
array2[num++] = array3[0];
array2[num++] = array3[1];
}
result.Count = (byte)num;
result.Payload = array2;
return result;
}
public static ASBStatusElement[] ASBStatusToArray(ASBStatus status)
{
if (status.Payload == null)
{
return new ASBStatusElement[0];
}
byte[] payload = status.Payload;
ushort num = 0;
ushort num2 = 0;
while (num2 < status.Count)
{
num2 = (((payload[num2] & 0x80) == 0) ? ((ushort)(num2 + 3)) : ((ushort)(num2 + 1)));
num++;
}
ASBStatusElement[] array = new ASBStatusElement[num];
num2 = 0;
for (ushort num3 = 0; num3 < num; num3++)
{
if ((payload[num2] & 0x80) != 0)
{
array[num3].statusType = (ASBStatusType)(payload[num2] & 0x7F);
array[num3].statusValue = 0;
num2++;
}
else
{
array[num3].statusType = (ASBStatusType)payload[num2++];
array[num3].statusValue = BitConverter.ToUInt16(payload, num2);
num2 += 2;
}
}
return array;
}
}
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Text;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public static class ASBSolutionUtilities
{
public static string WriteSecurityInformationInRegistry(SystemAuthenticationASBConfiguration ConfigurationData, string xmlExtraInfo)
{
string empty = string.Empty;
try
{
ASBConfigurationInformation obj = new ASBConfigurationInformation
{
EncryptedCertificate = ((ConfigurationData.EncryptedCertificate == null) ? string.Empty : Encoding.Default.GetString(ConfigurationData.EncryptedCertificate)),
EncryptedSharedSecret = ((ConfigurationData.EncryptedSharedSecret == null) ? string.Empty : Encoding.Default.GetString(ConfigurationData.EncryptedSharedSecret)),
Generator = ((ConfigurationData.generator == null) ? string.Empty : Encoding.Default.GetString(ConfigurationData.generator)),
HashAlgorithm = ((ConfigurationData.hashAlgorithm == null) ? string.Empty : ConfigurationData.hashAlgorithm),
InitializationVector = ((ConfigurationData.initializationVector == null) ? string.Empty : Encoding.Default.GetString(ConfigurationData.initializationVector)),
SolutionName = ((ConfigurationData.solutionName == null) ? string.Empty : ConfigurationData.solutionName),
KeySize = ConfigurationData.keySize,
PasswordDerivationIterations = ConfigurationData.passwordDerivationIterations,
Prime = ((ConfigurationData.prime == null) ? string.Empty : Encoding.Default.GetString(ConfigurationData.prime)),
SaltValue = ((ConfigurationData.saltValue == null) ? string.Empty : Encoding.Default.GetString(ConfigurationData.saltValue)),
IsDefault = "false",
SRNodeName = ((ConfigurationData.srNodeName == null) ? string.Empty : ConfigurationData.srNodeName)
};
Dictionary<string, string> dictionary = RegistryHandler.ParseXMLExtraInfo(xmlExtraInfo);
string value = string.Empty;
string value2 = string.Empty;
string value3 = string.Empty;
string value4 = string.Empty;
dictionary.TryGetValue("PrimaryGlobalDiscovery", out value);
dictionary.TryGetValue("SecondaryGlobalDiscovery", out value2);
dictionary.TryGetValue("PrimaryUniversalDiscovery", out value3);
dictionary.TryGetValue("SecondaryUniversalDiscovery", out value4);
obj.PrimaryGlobalDiscovery = value;
obj.SecondaryGlobalDiscovery = value2;
obj.PrimaryUniversalDiscovery = value3;
obj.SecondaryUniversalDiscovery = value4;
return RegistryHandler.CreateASBConfigInfoStructureInRegistry(obj, obj.SRNodeName, isRegister: false);
}
catch (Exception ex)
{
return ex.Message;
}
}
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ASBStatus
{
[DataMember]
public byte Count;
[DataMember]
public byte[] Payload;
}
@@ -0,0 +1,60 @@
using System;
namespace ArchestrAServices.Contract;
public struct ASBStatusElement
{
public ASBStatusType statusType;
public ushort statusValue;
public ASBStatus Status
{
get
{
byte b = 0;
byte[] array = null;
if (statusValue == 0)
{
b = 1;
array = new byte[b];
array[0] = (byte)(((byte)statusType & 0x7F) | 0x80);
}
else
{
b = 3;
array = new byte[b];
array[0] = (byte)((byte)statusType & 0x7F);
byte[] array2 = new byte[2];
array2 = BitConverter.GetBytes(statusValue);
array[1] = array2[0];
array[2] = array2[1];
}
return new ASBStatus
{
Count = b,
Payload = array
};
}
}
public ASBStatusElement(ASBStatus singleStatus)
{
if (singleStatus.Payload == null || singleStatus.Payload.Length < 1)
{
throw new IndexOutOfRangeException("ASBStatus payload contained no data in ASBStatusElement constructor");
}
if ((singleStatus.Payload[0] & 0x80) != 0)
{
statusType = (ASBStatusType)(singleStatus.Payload[0] & 0x7F);
statusValue = 0;
return;
}
if (singleStatus.Payload.Length < 3)
{
throw new IndexOutOfRangeException("ASBStatus payload contained insufficient data in ASBStatusElement constructor");
}
statusType = (ASBStatusType)singleStatus.Payload[0];
statusValue = BitConverter.ToUInt16(singleStatus.Payload, 1);
}
}
@@ -0,0 +1,15 @@
namespace ArchestrAServices.Contract;
public enum ASBStatusType : ushort
{
OPCDAStatus = 1,
OPCUAStatus = 2,
OPCUAVendorStatus = 3,
SCADAStatus = 4,
MXStatusCategory = 5,
MxStatusDetail = 6,
MxQuality = 7,
Reserved1Status = 125,
Reserved2Status = 126,
Reserved3Status = 127
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public class ActionResult
{
[DataMember]
public Status Status { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
}
@@ -0,0 +1,19 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ApplicationToken
{
[DataMember]
public string ApplicationName;
[DataMember]
public string DomainName;
[DataMember]
public string HostName;
[DataMember]
public byte[] X509Certificate;
}
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAAttribute
{
[DataMember(Name = "Name", Order = 0, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "ID", Order = 1, EmitDefaultValue = true)]
public ulong ID;
[DataMember(Name = "Properties", Order = 2, EmitDefaultValue = true)]
public ArchestrAProperty[] Properties;
}
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAAttributeEx
{
[DataMember(Name = "Name", Order = 0, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "ID", Order = 1, EmitDefaultValue = true)]
public ulong ID;
[DataMember(Name = "Properties", Order = 2, EmitDefaultValue = true)]
public ArchestrAPropertyEx[] Properties;
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAContainedName
{
[DataMember(Name = "Name", Order = 0, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "RelationshipID", Order = 1, EmitDefaultValue = true)]
public ulong RelationshipID;
}
@@ -0,0 +1,28 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAEntity
{
[DataMember(Name = "UniqueName", Order = 0, EmitDefaultValue = true)]
public string UniqueName;
[DataMember(Name = "ID", Order = 1, EmitDefaultValue = true)]
public ulong ID;
[DataMember(Name = "IsTemplate", Order = 2, EmitDefaultValue = true)]
public byte IsTemplate;
[DataMember(Name = "ContainedName", Order = 3, EmitDefaultValue = true)]
public ArchestrAContainedName[] ContainedName;
[DataMember(Name = "Properties", Order = 4, EmitDefaultValue = true)]
public ArchestrAProperty[] Properties;
[DataMember(Name = "Facets", Order = 5, EmitDefaultValue = true)]
public ArchestrAFacet[] Facets;
[DataMember(Name = "UserData", Order = 6, EmitDefaultValue = true)]
public string UserData;
}
@@ -0,0 +1,28 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAEntityEx
{
[DataMember(Name = "UniqueName", Order = 0, EmitDefaultValue = true)]
public string UniqueName;
[DataMember(Name = "ID", Order = 1, EmitDefaultValue = true)]
public ulong ID;
[DataMember(Name = "IsTemplate", Order = 2, EmitDefaultValue = true)]
public byte IsTemplate;
[DataMember(Name = "ContainedName", Order = 3, EmitDefaultValue = true)]
public ArchestrAContainedName[] ContainedName;
[DataMember(Name = "Properties", Order = 4, EmitDefaultValue = true)]
public ArchestrAPropertyEx[] Properties;
[DataMember(Name = "Facets", Order = 5, EmitDefaultValue = true)]
public ArchestrAFacetEx[] Facets;
[DataMember(Name = "UserData", Order = 6, EmitDefaultValue = true)]
public string UserData;
}
@@ -0,0 +1,50 @@
namespace ArchestrAServices.Contract;
public enum ArchestrAError : ushort
{
Success = 0,
InvalidConnectionId = 1,
ApplicationAuthenticationError = 2,
UserAuthenticationError = 3,
UserAuthorizationError = 4,
NotSupportedOperation = 5,
MonitoredItemsNotFound = 6,
InvalidSubscriptionID = 7,
ItemAlreadyRegistered = 8,
ItemAlreadyDeletedOrDoesNotExist = 9,
InvalidMonitoredItems = 10,
OperationFailed = 11,
SpecificError = 12,
BadNoCommunication = 13,
Bad_NothingToDo = 14,
Bad_TooManyOperations = 15,
Bad_NodeIdInvalid = 16,
BrowseFailed = 17,
WriteFailed_BadOutOfRange = 18,
WriteFailed_BadTypeMismatch = 19,
WriteFailed_BadDimensionMismatch = 20,
WriteFailed_AccessDenied = 21,
WriteFailed_SecuredWrite = 22,
WriteFailed_VerifiedWrite = 23,
IndexOutOfRange = 24,
RequestTimedOut = 25,
DataTypeConversionNotSupported = 26,
ItemCannotBeRegistered_NoName = 27,
ItemCannotBeRegistered_NoId = 28,
ItemAlreadyBeingMonitored = 29,
SubscriptionIDAlreadyExist = 30,
OperationWouldBlock = 31,
PublishComplete = 32,
WriteFailed_UserNotHavingAccessRights = 33,
WriteFailed_VerifierNotHavingVerifyRights = 34,
ObjectNotInitialized = 128,
EndPointNotFound = 129,
ConnectionClosed = 130,
InvalidParameter = 131,
MemoryAllocationError = 132,
OperationNotComplete = 133,
FileOperationFailed = 256,
InvalidXMLFile = 272,
RecordLookupError = 288,
Unknown = ushort.MaxValue
}
@@ -0,0 +1,22 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAFacet
{
[DataMember(Name = "Name", Order = 0, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "Id", Order = 1, EmitDefaultValue = true)]
public ulong Id;
[DataMember(Name = "HasNamespace", Order = 2, EmitDefaultValue = true)]
public byte HasNamespace;
[DataMember(Name = "Properties", Order = 3, EmitDefaultValue = true)]
public ArchestrAProperty[] Properties;
[DataMember(Name = "Attributes", Order = 4, EmitDefaultValue = true)]
public ArchestrAAttribute[] Attributes;
}
@@ -0,0 +1,22 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAFacetEx
{
[DataMember(Name = "Name", Order = 0, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "Id", Order = 1, EmitDefaultValue = true)]
public ulong Id;
[DataMember(Name = "HasNamespace", Order = 2, EmitDefaultValue = true)]
public byte HasNamespace;
[DataMember(Name = "Properties", Order = 3, EmitDefaultValue = true)]
public ArchestrAPropertyEx[] Properties;
[DataMember(Name = "Attributes", Order = 4, EmitDefaultValue = true)]
public ArchestrAAttributeEx[] Attributes;
}
@@ -0,0 +1,22 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAProperty
{
[DataMember(Name = "ID", Order = 0, EmitDefaultValue = true)]
public ulong ID;
[DataMember(Name = "IsDefault", Order = 1, EmitDefaultValue = true)]
public byte IsDefault;
[DataMember(Name = "Name", Order = 2, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "Value", Order = 3, EmitDefaultValue = true)]
public object Value;
[DataMember(Name = "Type", Order = 4, EmitDefaultValue = true)]
public string Type;
}
@@ -0,0 +1,22 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAPropertyEx
{
[DataMember(Name = "ID", Order = 0, EmitDefaultValue = true)]
public ulong ID;
[DataMember(Name = "IsDefault", Order = 1, EmitDefaultValue = true)]
public byte IsDefault;
[DataMember(Name = "Name", Order = 2, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "Value", Order = 3, EmitDefaultValue = true)]
public object Value;
[DataMember(Name = "Type", Order = 4, EmitDefaultValue = true)]
public string Type;
}
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestrAResult
{
[DataMember]
public uint Status;
[DataMember]
public uint SpecificErrorCode;
[DataMember]
public ushort ErrorCode;
}
@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Name = "ArchestraBrowseDirection", Namespace = "http://ArchestrAServices.Contract")]
public enum ArchestraBrowseDirection
{
[EnumMember]
ForwardOrDown = 0,
[EnumMember]
ReverseOrUp = 1,
[EnumMember]
Unknown = 65535
}
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestraBrowseNode
{
[DataMember(Name = "RelationshipId", Order = 0, EmitDefaultValue = true)]
public ulong RelationshipId;
[DataMember(Name = "Direction", Order = 1, EmitDefaultValue = true)]
public ArchestraBrowseDirection Direction;
[DataMember(Name = "NodeID", Order = 2, EmitDefaultValue = true)]
public ulong NodeID;
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestraBrowseResult
{
[DataMember(Name = "ContinuationPoint", Order = 0, EmitDefaultValue = true)]
public ulong ContinuationPoint;
[DataMember(Name = "TargetNodes", Order = 1, EmitDefaultValue = true)]
public ArchestraNode[] TargetNodes;
}
@@ -0,0 +1,19 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestraNode
{
[DataMember(Name = "UniqueName", Order = 0, EmitDefaultValue = true)]
public string UniqueName;
[DataMember(Name = "ContainedName", Order = 1, EmitDefaultValue = true)]
public string ContainedName;
[DataMember(Name = "BrowseNode", Order = 2, EmitDefaultValue = true)]
public ArchestraBrowseNode Node;
[DataMember(Name = "UserData", Order = 3, EmitDefaultValue = true)]
public string UserData;
}
@@ -0,0 +1,19 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ArchestraRelationship
{
[DataMember]
public ulong Id;
[DataMember]
public ArchestraRelationshipType Type;
[DataMember]
public string NamespaceIdentifier;
[DataMember]
public string Name;
}
@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public enum ArchestraRelationshipType
{
[EnumMember]
Hierarchical = 0,
[EnumMember]
Network = 1,
[EnumMember]
Unknown = 65535
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
namespace ArchestrAServices.Contract;
public class AsbBaseSettings : IAsbInterfaceSettings
{
private static Dictionary<string, object> settings = new Dictionary<string, object>();
public T GetSetting<T>(string settingName, T defaultSetting)
{
object value = null;
if (settings.TryGetValue(settingName.ToLower(), out value))
{
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch (Exception)
{
}
}
return defaultSetting;
}
public void SetSetting(string settingName, object setting)
{
settings[settingName.ToLower()] = setting;
}
}
@@ -0,0 +1,11 @@
namespace ArchestrAServices.Contract;
public class AsbIntouchSettings : AsbBaseSettings
{
public AsbIntouchSettings()
{
SetSetting("ArrayBase", 1);
SetSetting("PreferCustomSerialization", true);
SetSetting("IDataMaxPublishCount", 4);
}
}
@@ -0,0 +1,11 @@
namespace ArchestrAServices.Contract;
public class AsbMxDataSettings : AsbBaseSettings
{
public AsbMxDataSettings()
{
SetSetting("ArrayBase", 1);
SetSetting("PreferCustomSerialization", true);
SetSetting("IDataMaxPublishCount", 10);
}
}
@@ -0,0 +1,12 @@
namespace ArchestrAServices.Contract;
public class AsbOpcuaSettings : AsbBaseSettings
{
public AsbOpcuaSettings()
{
SetSetting("ArrayBase", 0);
SetSetting("PreferCustomSerialization", true);
SetSetting("IDataMaxPublishCount", 10);
SetSetting("IBrowseMaxBrowseObject", 10000);
}
}
@@ -0,0 +1,130 @@
#define TRACE
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
internal static class AuthenticationCryptography
{
public static byte[] DeriveKey(byte[] passPhrase, byte[] saltValue, string hashAlgorithm, int passwordIterations, int keySize)
{
if (passPhrase == null || passPhrase.Length == 0)
{
throw new ArgumentNullException("passPhrase");
}
if (saltValue == null || saltValue.Length == 0)
{
throw new ArgumentNullException("saltValue");
}
if (string.IsNullOrEmpty(hashAlgorithm))
{
throw new ArgumentNullException("hashAlgorithm");
}
byte[] array = new byte[passPhrase.Length + saltValue.Length];
Buffer.BlockCopy(passPhrase, 0, array, 0, passPhrase.Length);
Buffer.BlockCopy(saltValue, 0, array, passPhrase.Length, saltValue.Length);
using MD5 mD = new MD5CryptoServiceProvider();
for (int i = 0; i < passwordIterations; i++)
{
array = mD.ComputeHash(array);
}
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < array.Length; j++)
{
stringBuilder.Append(array[j].ToString("x2"));
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "SvcAuth: DeriveKey generated '{0}' from '{1}'", new object[2]
{
stringBuilder.ToString(),
passPhrase[0].ToString("x2")
}));
return Encoding.UTF8.GetBytes(stringBuilder.ToString());
}
public static byte[] Encrypt(byte[] PlainPayload, byte[] passPhrase, byte[] saltValue, string hashAlgorithm, int passwordIterations, byte[] initVector, int keySize)
{
if (PlainPayload == null)
{
throw new ArgumentNullException("value");
}
if (passPhrase == null || passPhrase.Length == 0)
{
throw new ArgumentNullException("passPhrase");
}
if (saltValue == null || saltValue.Length == 0)
{
throw new ArgumentNullException("saltValue");
}
if (string.IsNullOrEmpty(hashAlgorithm))
{
throw new ArgumentNullException("hashAlgorithm");
}
if (initVector == null || initVector.Length == 0)
{
throw new ArgumentNullException("initVector");
}
byte[] rgbKey = DeriveKey(passPhrase, saltValue, hashAlgorithm, passwordIterations, 32);
byte[] array = null;
using RijndaelManaged rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Mode = CipherMode.CBC;
ICryptoTransform transform = rijndaelManaged.CreateEncryptor(rgbKey, initVector);
using MemoryStream memoryStream = new MemoryStream();
using CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
cryptoStream.Write(PlainPayload, 0, PlainPayload.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
public static byte[] Decrypt(byte[] CypherPayload, byte[] passPhrase, byte[] saltValue, string hashAlgorithm, int passwordIterations, byte[] initVector, int keySize)
{
if (CypherPayload == null)
{
throw new ArgumentNullException("value");
}
if (passPhrase == null || passPhrase.Length == 0)
{
throw new ArgumentNullException("passPhrase");
}
if (saltValue == null || saltValue.Length == 0)
{
throw new ArgumentNullException("saltValue");
}
if (string.IsNullOrEmpty(hashAlgorithm))
{
throw new ArgumentNullException("hashAlgorithm");
}
if (initVector == null || initVector.Length == 0)
{
throw new ArgumentNullException("initVector");
}
byte[] rgbKey = DeriveKey(passPhrase, saltValue, hashAlgorithm, passwordIterations, 32);
byte[] array = null;
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.Mode = CipherMode.CBC;
ICryptoTransform transform = rijndaelManaged.CreateDecryptor(rgbKey, initVector);
using MemoryStream stream = new MemoryStream(CypherPayload);
using CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Read);
array = new byte[CypherPayload.Length];
int num = 0;
try
{
num = cryptoStream.Read(array, 0, array.Length);
}
catch (Exception)
{
num = array.Length;
for (int i = 0; i < num; i++)
{
array[i] = 0;
}
}
}
return array;
}
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct BrowseFilter
{
[DataMember(Name = "FilterName", Order = 0, EmitDefaultValue = true)]
public string FilterName;
[DataMember(Name = "Filters", Order = 1, EmitDefaultValue = true)]
public BrowseFilterElement[] Filters;
}
@@ -0,0 +1,19 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct BrowseFilterElement
{
[DataMember(Name = "AppliesTo", Order = 0, EmitDefaultValue = true)]
public FilterType AppliesTo;
[DataMember(Name = "Type", Order = 1, EmitDefaultValue = true)]
public ElementType Type;
[DataMember(Name = "Name", Order = 2, EmitDefaultValue = true)]
public string Name;
[DataMember(Name = "FilterValue", Order = 3, EmitDefaultValue = true)]
public BrowseFilterValue[] FilterValue;
}
@@ -0,0 +1,34 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public enum BrowseFilterOperator
{
[EnumMember]
Equal = 1,
[EnumMember]
NotEqual,
[EnumMember]
LessThan,
[EnumMember]
LessThanOrEqual,
[EnumMember]
GreaterThan,
[EnumMember]
GreaterThanOrEqual,
[EnumMember]
Like,
[EnumMember]
NotLike,
[EnumMember]
Between,
[EnumMember]
NotBetween,
[EnumMember]
In,
[EnumMember]
NotIn,
[EnumMember]
Match
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct BrowseFilterValue
{
[DataMember(Name = "Operator", Order = 0, EmitDefaultValue = true)]
public BrowseFilterOperator Operator;
[DataMember(Name = "Value", Order = 1, EmitDefaultValue = true)]
public Variant[] Value;
}
@@ -0,0 +1,19 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct BrowseNode
{
[DataMember]
public string DisplayName;
[DataMember]
public string ContainedName;
[DataMember]
public string HierachicalName;
[DataMember]
public ulong ID;
}
@@ -0,0 +1,210 @@
#define TRACE
using System;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public class ClientAuthentication : EncryptionBase
{
private RNGCryptoServiceProvider m_Random = new RNGCryptoServiceProvider();
public ulong Timeout { get; set; }
public ConnectionId connectionId { get; private set; }
public bool SecureSessionEstablished { get; private set; }
public string ReasonSecureSessionNotEstablished { get; private set; }
public BigInteger ClientPrivateKey { get; private set; }
public BigInteger ClientPublicKey { get; private set; }
public BigInteger ServicePublicKey { get; private set; }
public ClientAuthentication()
{
Reset();
ReasonSecureSessionNotEstablished = "Constructed";
base.DH_passphrase = Constants.GetDHPassphrase();
base.hashAlgorithm = Constants.hashAlgorithm;
}
public void EstablishSecureSession(string application, string domain, string host, MakeCallToServiceConnect ConnectDelegate, MakeCallToServiceActivate ActivateDelegate)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "ClientAuth: EstablishSecureSession '{0}', '{1}', '{2}' entering", new object[3] { application, domain, host }));
SecureSessionEstablished = false;
InitializeAuthentication();
PublicKey clientToken = new PublicKey
{
ApplicationName = application,
DomainName = domain,
HostName = host,
KeyValue = ClientPublicKey.ToByteArray()
};
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "ClientAuth: Sending Connect() with client public key of {0} bits", new object[1] { clientToken.KeyValue.Length * 8 }));
Connection connection = default(Connection);
ArchestrAResult archestrAResult = ConnectDelegate(out connection, application, domain, host, clientToken);
if (archestrAResult.ErrorCode == EnumASBFactory.ArchestrAErrorToInt(ArchestrAError.Success))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "ClientAuth: Received successful response from service Connect() with service public key of {0} bits", new object[1] { connection.serviceKeyField.KeyValue.Length * 8 }));
connectionId = connection.idField;
ServicePublicKey = new BigInteger(connection.serviceKeyField.KeyValue);
byte[] ClientValidationData = null;
if (ProcessServiceNegotiation(connection.authenticationDataField.AuthenticationData, out ClientValidationData))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "ClientAuth: Returning client validation data in call to service ActivateSession()");
archestrAResult = ActivateDelegate(Authentication: new ConnectionAuthenticationData
{
AuthenticationData = ClientValidationData
}, ConnectionId: connectionId, Timeout: Timeout);
if (archestrAResult.ErrorCode == EnumASBFactory.ArchestrAErrorToInt(ArchestrAError.Success))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "ClientAuth: Service returned good result from ActivateSession(), secure session established"));
SecureSessionEstablished = true;
ReasonSecureSessionNotEstablished = "Secure session established";
}
else
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "ClientAuth: Service returned bad result from ActivateSession(), no secure session established"));
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, string.Format(CultureInfo.CurrentCulture, "ClientAuth: Service returned bad result from ActivateSession(), no secure session established"));
SecureSessionEstablished = false;
ReasonSecureSessionNotEstablished = $"Service ActivateSession() returned ArchestrAError '{EnumASBFactory.IntToArchestrAError(archestrAResult.ErrorCode).ToString()}'";
}
}
else
{
SvcTrace.DiagControl.TraceEvent(TraceEventType.Warning, 100, "ClientAuth: Service validation data could not be verified, no secure session established");
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "ClientAuth: Service validation data could not be verified, no secure session established");
Reset();
SecureSessionEstablished = false;
ReasonSecureSessionNotEstablished = "Service validation data returned from Connect() was invalid";
}
}
else
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "ClientAuth: Service returned bad result from Connect(), no secure session established");
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "ClientAuth: Service returned bad result from Connect(), no secure session established");
SecureSessionEstablished = false;
ReasonSecureSessionNotEstablished = $"Service Connect() returned ArchestrAError '{EnumASBFactory.IntToArchestrAError(archestrAResult.ErrorCode).ToString()}'";
}
}
public void AbortSession()
{
Reset();
ReasonSecureSessionNotEstablished = "Session Aborted";
}
public void DisconnectSecureSession(MakeCallToServiceDisconnect DisconnectDelegate)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "ClientAuth: Calling service Disconnect(), ending secure session");
DisconnectDelegate(connectionId);
Reset();
ReasonSecureSessionNotEstablished = "Session Disconnected normally";
}
private void Reset()
{
Timeout = 10000uL;
connectionId = new ConnectionId
{
Id = default(Guid)
};
SecureSessionEstablished = false;
ReasonSecureSessionNotEstablished = "Reset";
ClientPrivateKey = BigInteger.MinusOne;
ClientPublicKey = BigInteger.Zero;
base.NegotiatedKey = new byte[200];
m_Random.GetBytes(base.NegotiatedKey);
ServicePublicKey = BigInteger.Zero;
}
private void InitializeAuthentication()
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "ClientAuth: Generating D-H keys with size = {0}", new object[1] { Constants.DH_KeySize }));
Constants.GenerateKey(Constants.DH_KeySize, out DH_p, out DH_g);
BigInteger bigInteger = DH_p - new BigInteger(1);
ClientPrivateKey = new BigInteger(0);
while (ClientPrivateKey >= bigInteger || ClientPrivateKey <= 0L)
{
byte[] array = new byte[Constants.DH_SecretSize / 8];
m_Random.GetBytes(array);
ClientPrivateKey = new BigInteger(array);
}
ClientPublicKey = BigInteger.ModPow(DH_g, ClientPrivateKey, DH_p);
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "ClientAuth: Generated Client private key and public key");
}
private bool ProcessServiceNegotiation(byte[] ServiceValidationData, out byte[] ClientValidationData)
{
base.NegotiatedKey = Encoding.UTF8.GetBytes(base.DH_passphrase);
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "ClientAuth: Computed negotiated key [{0} {1} {2} {3} .. {4} {5}] {6} bytes", base.NegotiatedKey[0], base.NegotiatedKey[1], base.NegotiatedKey[2], base.NegotiatedKey[3], base.NegotiatedKey[base.NegotiatedKey.Length - 2], base.NegotiatedKey[base.NegotiatedKey.Length - 1], base.NegotiatedKey.Length));
byte[] array = ServicePublicKey.ToByteArray();
byte[] array2 = ClientPublicKey.ToByteArray();
byte[] array3 = new byte[array.Length + array2.Length];
Array.Copy(array, array3, array.Length);
Array.Copy(array2, 0, array3, array.Length, array2.Length);
byte[] array4 = Decrypt(ServiceValidationData, base.NegotiatedKey);
byte[] array5 = new byte[array4[0] + (array4[1] << 8)];
for (int i = 0; i < array5.Length; i++)
{
array5[i] = 0;
}
Array.Copy(array4, 2, array5, 0, array4.Length - 2);
byte[] bytes = Encoding.UTF8.GetBytes(base.DH_passphrase);
byte[] array6 = Decrypt(array5, bytes);
byte[] array7 = new byte[array6[0] + (array6[1] << 8)];
for (int j = 0; j < array7.Length; j++)
{
array7[j] = 0;
}
Array.Copy(array6, 2, array7, 0, array6.Length - 2);
bool flag = array3.Length == array7.Length;
if (flag)
{
for (int k = 0; k < array7.Length; k++)
{
if (array3[k] != array7[k])
{
flag = false;
break;
}
}
}
bool flag2 = false;
ClientValidationData = null;
if (flag)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "ClientAuth: Decrypted and confirmed service validation data");
SecureSessionEstablished = true;
ReasonSecureSessionNotEstablished = "Secure session established";
array3 = new byte[array2.Length + array.Length + 2];
int num = array3.Length - 2;
array3[0] = (byte)((ulong)num & 0xFFuL);
array3[1] = (byte)(((ulong)num >> 8) & 0xFF);
Array.Copy(array2, 0, array3, 2, array2.Length);
Array.Copy(array, 0, array3, array2.Length + 2, array.Length);
byte[] array8 = Encrypt(array3, bytes);
byte[] array9 = new byte[array8.Length + 2];
int num2 = array9.Length - 2;
array9[0] = (byte)((ulong)num2 & 0xFFuL);
array9[1] = (byte)(((ulong)num2 >> 8) & 0xFF);
Array.Copy(array8, 0, array9, 2, array8.Length);
ClientValidationData = Encrypt(array9, base.NegotiatedKey);
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "ClientAuth: Generated and encrypted return client validation data");
return true;
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "ClientAuth: Service validation data is incorrect, cannot authenticate");
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "ClientAuth: Service validation data is incorrect, cannot authenticate");
SecureSessionEstablished = false;
ReasonSecureSessionNotEstablished = "Service validation payload incorrect";
ClientValidationData = ServiceValidationData;
return false;
}
}
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct Connection
{
[DataMember]
public ConnectionId idField;
[DataMember]
public PublicKey serviceKeyField;
[DataMember]
public ConnectionAuthenticationData authenticationDataField;
}
@@ -0,0 +1,10 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ConnectionAuthenticationData
{
[DataMember]
public byte[] AuthenticationData;
}
@@ -0,0 +1,27 @@
using System;
namespace ArchestrAServices.Contract;
public static class ConnectionFactory
{
public static ConnectionId MakeConnection()
{
return new ConnectionId
{
Id = Guid.NewGuid()
};
}
public static ConnectionId MakeInvalidConnection()
{
return new ConnectionId
{
Id = Guid.Empty
};
}
public static bool IsEqual(ConnectionId id1, ConnectionId id2)
{
return id1.Id == id2.Id;
}
}
@@ -0,0 +1,11 @@
using System;
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ConnectionId
{
[DataMember]
public Guid Id;
}
@@ -0,0 +1,112 @@
using System;
using System.Numerics;
using System.Security.Cryptography;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public static class Constants
{
public static int DH_KeySize = 1024;
public static int DH_SecretSize = 160;
public static string DH_passphrase = "Pas5pr@se";
public static string SaltValue = "s@1tValue";
public static string hashAlgorithm = CngAlgorithm.MD5.ToString();
public static int PasswordIterations = 1;
public static string InitialVector = "ba172e9941be138b";
public static int KeySize = 256;
private static string s_DECIMAL768 = "1552518092300708935130918131258481755631334049434514313202351194902966239949102107258669453876591642442910007680288864229150803718918046342632727613031282983744380820890196288509170691316593175367469551763119843371637221007210577919";
private static byte[] s_OAKLEY768 = new byte[96]
{
255, 255, 255, 255, 255, 255, 255, 255, 201, 15,
218, 162, 33, 104, 194, 52, 196, 198, 98, 139,
128, 220, 28, 209, 41, 2, 78, 8, 138, 103,
204, 116, 2, 11, 190, 166, 59, 19, 155, 34,
81, 74, 8, 121, 142, 52, 4, 221, 239, 149,
25, 179, 205, 58, 67, 27, 48, 43, 10, 109,
242, 95, 20, 55, 79, 225, 53, 109, 109, 81,
194, 69, 228, 133, 181, 118, 98, 94, 126, 198,
244, 76, 66, 233, 166, 58, 54, 32, 255, 255,
255, 255, 255, 255, 255, 255
};
private static string s_DECIMAL1024 = "179769313486231590770839156793787453197860296048756011706444423684197180216158519368947833795864925541502180565485980503646440548199239100050792877003355816639229553136239076508735759914822574862575007425302077447712589550957937778424442426617334727629299387668709205606050270810842907692932019128194";
private static byte[] s_OAKLEY1024 = new byte[128]
{
255, 255, 255, 255, 255, 255, 255, 255, 201, 15,
218, 162, 33, 104, 194, 52, 196, 198, 98, 139,
128, 220, 28, 209, 41, 2, 78, 8, 138, 103,
204, 116, 2, 11, 190, 166, 59, 19, 155, 34,
81, 74, 8, 121, 142, 52, 4, 221, 239, 149,
25, 179, 205, 58, 67, 27, 48, 43, 10, 109,
242, 95, 20, 55, 79, 225, 53, 109, 109, 81,
194, 69, 228, 133, 181, 118, 98, 94, 126, 198,
244, 76, 66, 233, 166, 55, 237, 107, 11, 255,
92, 182, 244, 6, 183, 237, 238, 56, 107, 251,
90, 137, 159, 165, 174, 159, 36, 17, 124, 75,
31, 230, 73, 40, 102, 81, 236, 230, 83, 129,
255, 255, 255, 255, 255, 255, 255, 255
};
private static string s_DECIMAL1536 = "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919";
private static byte[] s_OAKLEY1536 = new byte[192]
{
255, 255, 255, 255, 255, 255, 255, 255, 201, 15,
218, 162, 33, 104, 194, 52, 196, 198, 98, 139,
128, 220, 28, 209, 41, 2, 78, 8, 138, 103,
204, 116, 2, 11, 190, 166, 59, 19, 155, 34,
81, 74, 8, 121, 142, 52, 4, 221, 239, 149,
25, 179, 205, 58, 67, 27, 48, 43, 10, 109,
242, 95, 20, 55, 79, 225, 53, 109, 109, 81,
194, 69, 228, 133, 181, 118, 98, 94, 126, 198,
244, 76, 66, 233, 166, 55, 237, 107, 11, 255,
92, 182, 244, 6, 183, 237, 238, 56, 107, 251,
90, 137, 159, 165, 174, 159, 36, 17, 124, 75,
31, 230, 73, 40, 102, 81, 236, 228, 91, 61,
194, 0, 124, 184, 161, 99, 191, 5, 152, 218,
72, 54, 28, 85, 211, 154, 105, 22, 63, 168,
253, 36, 207, 95, 131, 101, 93, 35, 220, 163,
173, 150, 28, 98, 243, 86, 32, 133, 82, 187,
158, 213, 41, 7, 112, 150, 150, 109, 103, 12,
53, 78, 74, 188, 152, 4, 241, 116, 108, 8,
202, 35, 115, 39, 255, 255, 255, 255, 255, 255,
255, 255
};
public static string GetDHPassphrase()
{
string passphrase = string.Empty;
RegistryHandler.GetSolutionPassphrase(string.Empty, out passphrase);
return passphrase;
}
public static void GenerateKey(int bitlen, out BigInteger DH_p, out BigInteger DH_g)
{
switch (bitlen)
{
case 768:
BigInteger.TryParse(s_DECIMAL768, out DH_p);
break;
case 1024:
BigInteger.TryParse(s_DECIMAL1024, out DH_p);
break;
case 1536:
BigInteger.TryParse(s_DECIMAL1536, out DH_p);
break;
default:
throw new ArgumentException("Invalid bit size.");
}
DH_g = new BigInteger(22);
}
}
@@ -0,0 +1,9 @@
namespace ArchestrAServices.Contract;
public enum CredentialType : ushort
{
UsernamePassword = 0,
X509Certificate = 1,
SamlToken = 2,
Other = ushort.MaxValue
}
@@ -0,0 +1,12 @@
namespace ArchestrAServices.Contract;
public enum CredentialValidity : ushort
{
UserIdentityValid = 0,
UserIdentityInvalid_BadPassword = 1,
UserIdentityInvalid_NoUser = 2,
UserIdentityInvalid_CannotAuthenticate = 3,
UserIdentityInvalid_AccountDisabled = 4,
UserIdentityInvalid_AccountLocked = 5,
UesrIdentityValidityUnknown = ushort.MaxValue
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct CustomEnum
{
[DataMember]
public short ordinal;
[DataMember]
public string OrdinalValue;
}
@@ -0,0 +1,9 @@
namespace ArchestrAServices.Contract;
public enum DataQualityType : ushort
{
Good = 0,
Uncertain = 16,
Bad = 1,
Other = ushort.MaxValue
}
@@ -0,0 +1,53 @@
namespace ArchestrAServices.Contract;
public enum DataType : ushort
{
TypeByte = 0,
TypeChar = 1,
TypeInt16 = 2,
TypeUInt16 = 3,
TypeInt32 = 4,
TypeUInt32 = 5,
TypeInt64 = 6,
TypeUInt64 = 7,
TypeFloat = 8,
TypeDouble = 9,
TypeString = 10,
TypeDateTime = 11,
TypeDuration = 12,
TypeGuid = 13,
TypeByteString = 14,
TypeLocaleID = 15,
TypeLocalizedText = 16,
TypeBool = 17,
TypeSByte = 18,
TypeErrorStatus = 19,
TypeEnum = 20,
TypeDataType = 21,
TypeSecurityClassification = 22,
TypeDataQuality = 23,
TypeByteArray = 40,
TypeCharArray = 41,
TypeInt16Array = 42,
TypeUInt16Array = 43,
TypeInt32Array = 44,
TypeUInt32Array = 45,
TypeInt64Array = 46,
TypeUInt64Array = 47,
TypeFloatArray = 48,
TypeDoubleArray = 49,
TypeStringArray = 50,
TypeDateTimeArray = 51,
TypeDurationArray = 52,
TypeGuidArray = 53,
TypeByteStringArray = 54,
TypeLocaleIDArray = 55,
TypeLocalizedTextArray = 56,
TypeBoolArray = 57,
TypeSByteArray = 58,
TypeEnumArray = 60,
TypeDataTypeArray = 61,
TypeSecurityClassificationArray = 62,
TypeDataQualityArray = 63,
TypeUnknown = ushort.MaxValue
}
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public enum ElementType
{
[EnumMember]
Entity = 1,
[EnumMember]
Facet,
[EnumMember]
Method,
[EnumMember]
Attribute
}
@@ -0,0 +1,98 @@
using System;
using System.Numerics;
using System.Text;
namespace ArchestrAServices.Contract;
public class EncryptionBase
{
protected BigInteger DH_p = BigInteger.Zero;
protected BigInteger DH_g = BigInteger.Zero;
public string DH_passphrase { get; set; }
public string hashAlgorithm { get; set; }
public byte[] NegotiatedKey { get; protected set; }
public byte[] Encrypt(byte[] PlainPayload, byte[] EncryptionKey)
{
if (PlainPayload == null)
{
throw new ArgumentNullException("PlainPayload");
}
if (EncryptionKey == null)
{
throw new ArgumentNullException("EncryptionKey");
}
byte[] bytes = Encoding.UTF8.GetBytes(Constants.SaltValue);
byte[] bytes2 = Encoding.UTF8.GetBytes(Constants.InitialVector);
return AuthenticationCryptography.Encrypt(PlainPayload, EncryptionKey, bytes, Constants.hashAlgorithm, Constants.PasswordIterations, bytes2, Constants.KeySize);
}
public byte[] Decrypt(byte[] EncryptedPayload, byte[] EncryptionKey)
{
if (EncryptedPayload == null)
{
throw new ArgumentNullException("EncryptedPayload");
}
if (EncryptionKey == null)
{
throw new ArgumentNullException("EncryptionKey");
}
byte[] bytes = Encoding.UTF8.GetBytes(Constants.SaltValue);
byte[] bytes2 = Encoding.UTF8.GetBytes(Constants.InitialVector);
byte[] array = AuthenticationCryptography.Decrypt(EncryptedPayload, EncryptionKey, bytes, Constants.hashAlgorithm, Constants.PasswordIterations, bytes2, Constants.KeySize);
int num = array.Length;
int num2 = array.Length - 1;
while (num2 > 1 && array[num2] == 0)
{
num--;
num2--;
}
byte[] array2 = new byte[num];
Array.Copy(array, array2, num);
return array2;
}
public byte[] Encrypt(string PlainPayloadString, string EncryptionPassphrase)
{
if (string.IsNullOrEmpty(PlainPayloadString))
{
throw new ArgumentException("PlainPayloadString");
}
if (string.IsNullOrEmpty(EncryptionPassphrase))
{
throw new ArgumentException("EncryptionPassphrase");
}
byte[] bytes = Encoding.UTF8.GetBytes(Constants.SaltValue);
byte[] bytes2 = Encoding.UTF8.GetBytes(Constants.InitialVector);
byte[] bytes3 = Encoding.UTF8.GetBytes(EncryptionPassphrase);
return AuthenticationCryptography.Encrypt(Encoding.UTF8.GetBytes(PlainPayloadString), bytes3, bytes, Constants.hashAlgorithm, Constants.PasswordIterations, bytes2, Constants.KeySize);
}
public string Decrypt(byte[] EncryptedPayload, string EncryptionPassphrase)
{
if (EncryptedPayload == null)
{
throw new ArgumentNullException("EncryptedPayload");
}
if (string.IsNullOrEmpty(EncryptionPassphrase))
{
throw new ArgumentException("EncryptionPassphrase");
}
byte[] bytes = Encoding.UTF8.GetBytes(Constants.SaltValue);
byte[] bytes2 = Encoding.UTF8.GetBytes(Constants.InitialVector);
byte[] bytes3 = Encoding.UTF8.GetBytes(EncryptionPassphrase);
byte[] array = AuthenticationCryptography.Decrypt(EncryptedPayload, bytes3, bytes, Constants.hashAlgorithm, Constants.PasswordIterations, bytes2, Constants.KeySize);
int num = array.Length;
int num2 = array.Length - 1;
while (num2 > 1 && array[num2] == 0)
{
num--;
num2--;
}
return Encoding.UTF8.GetString(array, 0, num);
}
}
@@ -0,0 +1,6 @@
namespace ArchestrAServices.Contract;
public enum EncryptionType : ushort
{
None
}
@@ -0,0 +1,74 @@
using System;
namespace ArchestrAServices.Contract;
public static class EnumASBFactory
{
public static ArchestrAError IntToArchestrAError(ushort iValue)
{
try
{
return (ArchestrAError)iValue;
}
catch (Exception)
{
return ArchestrAError.Unknown;
}
}
public static ushort ArchestrAErrorToInt(ArchestrAError eValue)
{
return (ushort)eValue;
}
public static CredentialType IntToCredentialType(ushort iValue)
{
try
{
return (CredentialType)iValue;
}
catch (Exception)
{
return CredentialType.Other;
}
}
public static ushort CredentialTypeToInt(CredentialType eValue)
{
return (ushort)eValue;
}
public static EncryptionType IntToEncryptionType(ushort iValue)
{
try
{
return (EncryptionType)iValue;
}
catch (Exception)
{
return EncryptionType.None;
}
}
public static ushort EncryptionTypeToInt(EncryptionType eValue)
{
return (ushort)eValue;
}
public static CredentialValidity IntToCredentialValidity(ushort iValue)
{
try
{
return (CredentialValidity)iValue;
}
catch (Exception)
{
return CredentialValidity.UesrIdentityValidityUnknown;
}
}
public static ushort CredentialValidityToInt(CredentialValidity eValue)
{
return (ushort)eValue;
}
}
@@ -0,0 +1,143 @@
using System;
namespace ArchestrAServices.Contract;
public static class EnumFactory
{
public static DataType IntToDataType(ushort iValue)
{
try
{
return (DataType)iValue;
}
catch (Exception)
{
return DataType.TypeUnknown;
}
}
public static ushort DataTypeToInt(DataType eValue)
{
return (ushort)eValue;
}
public static DataQualityType IntToDataQualityType(ushort iValue)
{
try
{
return (DataQualityType)iValue;
}
catch (Exception)
{
return DataQualityType.Uncertain;
}
}
public static ushort DataQualityTypeToInt(DataQualityType eValue)
{
return (ushort)eValue;
}
public static ItemIdentityType IntToItemIdentityType(ushort iValue)
{
try
{
return (ItemIdentityType)iValue;
}
catch (Exception)
{
return ItemIdentityType.Other;
}
}
public static ushort ItemIdentityTypeToInt(ItemIdentityType eValue)
{
return (ushort)eValue;
}
public static ItemReferenceType IntToItemReferenceType(ushort iValue)
{
try
{
return (ItemReferenceType)iValue;
}
catch (Exception)
{
return ItemReferenceType.Other;
}
}
public static ushort ItemReferenceTypeToInt(ItemReferenceType eValue)
{
return (ushort)eValue;
}
public static SubscriptionStateType IntToSubscriptionStateType(ushort iValue)
{
try
{
return (SubscriptionStateType)iValue;
}
catch (Exception)
{
return SubscriptionStateType.SubsUnknown;
}
}
public static ushort SubscriptionStateTypeToInt(SubscriptionStateType eValue)
{
return (ushort)eValue;
}
public static WriteCapabilityType IntToWriteCapabilityType(ushort iValue)
{
try
{
return (WriteCapabilityType)iValue;
}
catch (Exception)
{
return WriteCapabilityType.WriteUnknown;
}
}
public static ushort WriteCapabilityTypeToInt(WriteCapabilityType eValue)
{
return (ushort)eValue;
}
public static OpcQualityMask IntToOpcQualityMask(ushort iValue)
{
try
{
return (OpcQualityMask)iValue;
}
catch (Exception)
{
return OpcQualityMask.MAGELLAN_QUALITY_INITIALIZING;
}
}
public static ushort OpcQualityMaskToInt(OpcQualityMask eValue)
{
return (ushort)eValue;
}
public static MonitoredItem MakeDeleteMonitoredItem(ItemIdentity Item)
{
MonitoredItem result = default(MonitoredItem);
result.Item = Item;
result.SampleInterval = 0uL;
result.Active = 0;
result.TimeDeadband = 0uL;
result.ValueDeadband = default(Variant);
result.ValueDeadband.Type = DataTypeToInt(DataType.TypeUnknown);
result.ValueDeadband.Length = 0;
result.ValueDeadband.Payload = null;
result.UserData = default(Variant);
result.UserData.Type = DataTypeToInt(DataType.TypeUnknown);
result.UserData.Length = 0;
result.UserData.Payload = null;
return result;
}
}
@@ -0,0 +1,12 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public enum FilterType
{
[EnumMember]
Entity = 1,
[EnumMember]
Attribute
}
@@ -0,0 +1,14 @@
using System.IO;
namespace ArchestrAServices.Contract;
public interface IASBCustomSerializableType
{
void WriteToStream(BinaryWriter writer);
void InitializeFromStream(BinaryReader reader);
object InitializeArrayFromStream(BinaryReader reader, int arrayLength);
void WriteArrayToStream(object graph, ref BinaryWriter bw);
}
@@ -0,0 +1,8 @@
namespace ArchestrAServices.Contract;
public interface IAsbInterfaceSettings
{
T GetSetting<T>(string settingName, T defaultSetting);
void SetSetting(string settingName, object setting);
}
@@ -0,0 +1,30 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Name = "IBrowseStatus", Namespace = "http://ArchestrAServices.Contract")]
public enum IBrowseStatus : ushort
{
[EnumMember]
OK = 0,
[EnumMember]
IncorrectClientToken = 1,
[EnumMember]
IncorrectConnectionId = 2,
[EnumMember]
ClientSessionNotCreated = 32,
[EnumMember]
InvalidUsernameOrPassword = 49,
[EnumMember]
InvalidUserCert = 50,
[EnumMember]
CannotFindGR = 51,
[EnumMember]
CatchedException = 52,
[EnumMember]
InvalidContinuationPoint = 64,
[EnumMember]
CannotGetResult = 65,
[EnumMember]
UnKnown = 255
}
@@ -0,0 +1,32 @@
using System;
using System.ServiceModel;
namespace ArchestrAServices.Contract;
[ServiceContract(SessionMode = SessionMode.Required, Namespace = "http://ArchestrAServices.Contract")]
public interface IManageASBSecurity : ISecureSession
{
[OperationContract]
ArchestrAResult RegisterSystemAuthenticationConfiguration(ConnectionId Id, SystemAuthenticationASBConfiguration ConfigurationData, string XMLExtraInfo);
[OperationContract]
ArchestrAResult UnregisterSystemAuthenticationConfiguration(ConnectionId Id, string SolutionName);
[OperationContract]
ArchestrAResult RegisterServiceBusPlatformId(ConnectionId Id, Guid NodeId);
[OperationContract]
ArchestrAResult GetServiceBusPlatformConfiguration(out SystemAuthenticationASBConfiguration ConfigurationData, out string XMLExtraInfo, ConnectionId Id, Guid NodeId, string SolutionName);
[OperationContract]
ArchestrAResult RegisterServiceBusEnable(ConnectionId Id, SystemAuthenticationASBConfiguration ConfigurationData);
[OperationContract]
ArchestrAResult GetRegistrationEndpointStatus(out StatusTemporaryEndpoint[] ConfigurationData, ConnectionId Id);
[OperationContract]
ArchestrAResult QueryExtraInfoChanges(out string XMLExtraInfo, ConnectionId Id, string NodeId);
[OperationContract]
ArchestrAResult EnumerateSolutions(out string[] SolutionNames, ConnectionId Id);
}
@@ -0,0 +1,22 @@
using System.ServiceModel;
namespace ArchestrAServices.Contract;
[ServiceContract(SessionMode = SessionMode.Required, Namespace = "http://ArchestrAServices.Contract")]
public interface ISecureSession
{
[OperationContract(IsInitiating = true)]
ArchestrAResult Connect(out Connection ConnectionDescription, string Application, string Domain, string Host, PublicKey ClientToken);
[OperationContract(IsInitiating = false)]
ArchestrAResult ActivateSession(ConnectionId Id, ConnectionAuthenticationData Authentication, ulong Timeout);
[OperationContract(IsInitiating = false)]
ArchestrAResult ActivateUser(ConnectionId Id, UserToken UserToken);
[OperationContract(IsInitiating = false)]
ArchestrAResult KeepAlive(ConnectionId Id);
[OperationContract(IsInitiating = false, IsTerminating = true)]
ArchestrAResult Disconnect(ConnectionId ConnectionID);
}
@@ -0,0 +1,22 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ItemIdentity
{
[DataMember]
public ushort Type;
[DataMember]
public ushort ReferenceType;
[DataMember]
public string Name;
[DataMember]
public string ContextName;
[DataMember]
public ulong Id;
}
@@ -0,0 +1,9 @@
namespace ArchestrAServices.Contract;
public enum ItemIdentityType : ushort
{
Name = 0,
Id = 1,
NameAndId = 2,
Other = ushort.MaxValue
}
@@ -0,0 +1,10 @@
namespace ArchestrAServices.Contract;
public enum ItemReferenceType : ushort
{
None = 0,
Absolute = 1,
Hierarchical = 2,
Relative = 3,
Other = ushort.MaxValue
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ItemRegistration
{
[DataMember]
public ushort WriteCapability;
[DataMember]
public ulong Id;
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ItemStatus
{
[DataMember]
public ItemIdentity Item;
[DataMember]
public ushort ErrorCode;
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct ItemWriteComplete
{
[DataMember]
public uint WriteHandle;
[DataMember]
public ItemStatus[] Status;
}
@@ -0,0 +1,3 @@
namespace ArchestrAServices.Contract;
public delegate ArchestrAResult MakeCallToServiceActivate(ConnectionId ConnectionId, ConnectionAuthenticationData Authentication, ulong Timeout);
@@ -0,0 +1,3 @@
namespace ArchestrAServices.Contract;
public delegate ArchestrAResult MakeCallToServiceConnect(out Connection connection, string Application, string Domain, string Host, PublicKey ClientToken);
@@ -0,0 +1,3 @@
namespace ArchestrAServices.Contract;
public delegate ArchestrAResult MakeCallToServiceDisconnect(ConnectionId ConnectionId);
@@ -0,0 +1,25 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct MonitoredItem
{
[DataMember]
public ItemIdentity Item;
[DataMember]
public ulong SampleInterval;
[DataMember]
public byte Active;
[DataMember]
public ulong TimeDeadband;
[DataMember]
public Variant ValueDeadband;
[DataMember]
public Variant UserData;
}
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct MonitoredItemValue
{
[DataMember]
public ItemIdentity Item;
[DataMember]
public RuntimeValue Value;
[DataMember]
public Variant UserData;
}
@@ -0,0 +1,28 @@
namespace ArchestrAServices.Contract;
public enum OpcQualityMask : ushort
{
OPC_LIMIT_OK = 0,
OPC_QUALITY_BAD = 0,
OPC_LIMIT_LOW = 1,
OPC_LIMIT_HIGH = 2,
OPC_LIMIT_MASK = 3,
OPC_LIMIT_CONST = 3,
OPC_QUALITY_CONFIG_ERROR = 4,
OPC_QUALITY_NOT_CONNECTED = 8,
OPC_QUALITY_DEVICE_FAILURE = 12,
OPC_QUALITY_SENSOR_FAILURE = 16,
OPC_QUALITY_LAST_KNOWN = 20,
OPC_QUALITY_COMM_FAILURE = 24,
OPC_QUALITY_OUT_OF_SERVICE = 28,
MAGELLAN_QUALITY_INITIALIZING = 32,
OPC_QUALITY_UNCERTAIN = 64,
OPC_QUALITY_LAST_USABLE = 68,
OPC_QUALITY_SENSOR_CAL = 80,
OPC_QUALITY_EGU_EXCEEDED = 84,
OPC_QUALITY_SUB_NORMAL = 88,
OPC_QUALITY_GOOD = 192,
OPC_QUALITY_MASK = 192,
OPC_QUALITY_LOCAL_OVERRIDE = 216,
OPC_STATUS_MASK = 252
}
@@ -0,0 +1,19 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct PublicKey
{
[DataMember]
public string ApplicationName;
[DataMember]
public string DomainName;
[DataMember]
public string HostName;
[DataMember]
public byte[] KeyValue;
}
@@ -0,0 +1,23 @@
namespace ArchestrAServices.Contract;
public static class ResultFactory
{
public static ArchestrAResult MakeGoodResult()
{
return new ArchestrAResult
{
ErrorCode = EnumASBFactory.ArchestrAErrorToInt(ArchestrAError.Success),
Status = 0u,
SpecificErrorCode = 0u
};
}
public static ArchestrAResult MakeResult(ArchestrAError error, ushort status)
{
return new ArchestrAResult
{
ErrorCode = EnumASBFactory.ArchestrAErrorToInt(error),
Status = status
};
}
}
@@ -0,0 +1,17 @@
using System;
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct RuntimeValue
{
[DataMember]
public DateTime Timestamp;
[DataMember]
public Variant Value;
[DataMember]
public ASBStatus Status;
}
@@ -0,0 +1,151 @@
#define TRACE
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IdentityModel.Claims;
using System.IdentityModel.Tokens;
using System.Linq;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public class SamlClaimsCheck
{
public static bool CheckSamlTokenForAttributeClaim(SamlSecurityToken SamlToken, string ClaimValue)
{
if (SamlToken == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForAttributeClaim: SamlToken cannot be null");
return false;
}
if (string.IsNullOrEmpty(ClaimValue))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForAttributeClaim: ClaimValue cannot be null or empty");
return false;
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "SAML assertion contains {0} statements", new object[1] { SamlToken.Assertion.Statements.Count() }));
foreach (SamlStatement statement in SamlToken.Assertion.Statements)
{
if (!(statement is SamlAttributeStatement))
{
continue;
}
SamlAttributeStatement samlAttributeStatement = statement as SamlAttributeStatement;
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "SamlAttributeStatement has {0} attributes", new object[1] { samlAttributeStatement.Attributes.Count() }));
foreach (SamlAttribute attribute in samlAttributeStatement.Attributes)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "Attribute '{0}' has {1} claims", new object[2]
{
attribute.Name,
attribute.ExtractClaims().Count()
}));
foreach (Claim item in attribute.ExtractClaims())
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "Claim type '{0}', Right: '{1}'", new object[2] { item.ClaimType, item.Right }));
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "Attribute '{0}' has {1} values", new object[2]
{
attribute.Name,
attribute.AttributeValues.Count()
}));
foreach (string attributeValue in attribute.AttributeValues)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "Value: '{0}'", new object[1] { attributeValue }));
if (attributeValue == ClaimValue)
{
return true;
}
}
}
}
return false;
}
public static List<string> ExtractAllAttributeClaims(SamlSecurityToken SamlToken)
{
return ExtractAllAttributeClaims(SamlToken);
}
public static List<string> ExtractAllAttributeClaims(SamlSecurityToken SamlToken, string AttributeName)
{
List<string> list = new List<string>();
if (SamlToken == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "ExtractAllAttributeClaims: SamlToken cannot be null");
return list;
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "ExtractAllAttributeClaims extracting '{0}' attributes", new object[1] { AttributeName }));
foreach (SamlStatement statement in SamlToken.Assertion.Statements)
{
if (!(statement is SamlAttributeStatement))
{
continue;
}
foreach (SamlAttribute attribute in (statement as SamlAttributeStatement).Attributes)
{
if (!string.IsNullOrEmpty(AttributeName) && !(attribute.Name == AttributeName))
{
continue;
}
foreach (Claim item in attribute.ExtractClaims())
{
if (!(item.ClaimType == ClaimTypes.Name) || !(item.Right == Rights.PossessProperty))
{
continue;
}
foreach (string attributeValue in attribute.AttributeValues)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "Adding '{0} attribute's value '{1}' to return list", new object[2] { attribute.Name, attributeValue }));
list.Add(attributeValue);
}
}
}
}
return list;
}
public static bool CheckSamlTokenForAuthenticationClaim(SamlSecurityToken SamlToken, string ClaimValue)
{
if (SamlToken == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForAuthenticationClaim: SamlToken cannot be null");
return false;
}
if (string.IsNullOrEmpty(ClaimValue))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForAuthenticationClaim: ClaimValue cannot be null or empty");
return false;
}
return false;
}
public static bool CheckSamlTokenForAuthorizationClaim(SamlSecurityToken SamlToken, string ClaimValue)
{
if (SamlToken == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForAuthorizationClaim: SamlToken cannot be null");
return false;
}
if (string.IsNullOrEmpty(ClaimValue))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForAuthorizationClaim: ClaimValue cannot be null or empty");
return false;
}
return false;
}
public static bool CheckSamlTokenForSubjectClaim(SamlSecurityToken SamlToken, string ClaimValue)
{
if (SamlToken == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForSubjectClaim: SamlToken cannot be null");
return false;
}
if (string.IsNullOrEmpty(ClaimValue))
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "CheckSamlTokenForSubjectClaim: ClaimValue cannot be null or empty");
return false;
}
return false;
}
}
@@ -0,0 +1,169 @@
#define TRACE
using System;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public class ServiceAuthentication : EncryptionBase
{
private RNGCryptoServiceProvider m_Random = new RNGCryptoServiceProvider();
public ConnectionId connectionId { get; private set; }
public bool SecureSessionEstablished { get; private set; }
public string ReasonSecureSessionNotEstablished { get; private set; }
public BigInteger ClientPublicKey { get; private set; }
public BigInteger ServicePrivateKey { get; private set; }
public BigInteger ServicePublicKey { get; private set; }
public ServiceAuthentication()
{
Reset();
ReasonSecureSessionNotEstablished = "Constructed";
base.DH_passphrase = Constants.GetDHPassphrase();
base.hashAlgorithm = Constants.hashAlgorithm;
}
public ArchestrAResult ProcessClientConnection(string application, string domain, string host, PublicKey ClientToken, out Connection connectionDescription)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "SvcAuth: Processing client Connect() call '{0}', '{1}', '{2}'", new object[3] { application, domain, host }));
connectionId = new ConnectionId
{
Id = Guid.NewGuid()
};
ClientPublicKey = new BigInteger(ClientToken.KeyValue);
Constants.GenerateKey(Constants.DH_KeySize, out DH_p, out DH_g);
BigInteger bigInteger = DH_p - new BigInteger(1);
ServicePrivateKey = new BigInteger(0);
while (ServicePrivateKey >= bigInteger || ServicePrivateKey <= 0L)
{
byte[] array = new byte[Constants.DH_SecretSize / 8];
m_Random.GetBytes(array);
ServicePrivateKey = new BigInteger(array);
}
ServicePublicKey = BigInteger.ModPow(DH_g, ServicePrivateKey, DH_p);
base.NegotiatedKey = Encoding.UTF8.GetBytes(base.DH_passphrase);
connectionDescription = default(Connection);
connectionDescription.idField = connectionId;
connectionDescription.serviceKeyField.ApplicationName = application;
connectionDescription.serviceKeyField.DomainName = domain;
connectionDescription.serviceKeyField.HostName = host;
connectionDescription.serviceKeyField.KeyValue = ServicePublicKey.ToByteArray();
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "SvcAuth: Captured {0}-bit client public key, generated {1}-bit service public key, computed {2}-bit negotiated private key", new object[3]
{
ClientToken.KeyValue.Length * 8,
connectionDescription.serviceKeyField.KeyValue.Length * 8,
base.NegotiatedKey.Length * 8
}));
byte[] array2 = ServicePublicKey.ToByteArray();
byte[] array3 = ClientPublicKey.ToByteArray();
byte[] array4 = new byte[array2.Length + array3.Length + 2];
int num = array4.Length - 2;
array4[0] = (byte)((ulong)num & 0xFFuL);
array4[1] = (byte)(((ulong)num >> 8) & 0xFF);
Array.Copy(array2, 0, array4, 2, array2.Length);
Array.Copy(array3, 0, array4, array2.Length + 2, array3.Length);
byte[] bytes = Encoding.UTF8.GetBytes(base.DH_passphrase);
byte[] array5 = Encrypt(array4, bytes);
byte[] array6 = new byte[array5.Length + 2];
int num2 = array6.Length - 2;
array6[0] = (byte)((ulong)num2 & 0xFFuL);
array6[1] = (byte)(((ulong)num2 >> 8) & 0xFF);
Array.Copy(array5, 0, array6, 2, array5.Length);
byte[] array7 = Encrypt(array6, base.NegotiatedKey);
connectionDescription.authenticationDataField.AuthenticationData = array7;
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "SvcAuth: Generated {0}-bit service validation data, returning to client", new object[1] { array7.Length * 8 }));
return ResultFactory.MakeGoodResult();
}
public ArchestrAResult ProcessClientActivate(ConnectionId Id, ConnectionAuthenticationData Authentication, ulong Timeout)
{
if (Id.Id != connectionId.Id)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, "SvcAuth: Client called ActivateSession() with invalid connection ID, no secure session created");
Reset();
ReasonSecureSessionNotEstablished = "ProcessClientActivate called with bad connection id";
return ResultFactory.MakeResult(ArchestrAError.ApplicationAuthenticationError, 0);
}
byte[] array = ClientPublicKey.ToByteArray();
byte[] array2 = ServicePublicKey.ToByteArray();
byte[] array3 = new byte[array.Length + array2.Length];
Array.Copy(array, array3, array.Length);
Array.Copy(array2, 0, array3, array.Length, array2.Length);
byte[] array4 = Decrypt(Authentication.AuthenticationData, base.NegotiatedKey);
byte[] array5 = new byte[array4[0] + (array4[1] << 8)];
for (int i = 0; i < array5.Length; i++)
{
array5[i] = 0;
}
Array.Copy(array4, 2, array5, 0, array4.Length - 2);
byte[] bytes = Encoding.UTF8.GetBytes(base.DH_passphrase);
byte[] array6 = Decrypt(array5, bytes);
byte[] array7 = new byte[array6[0] + (array6[1] << 8)];
for (int j = 0; j < array7.Length; j++)
{
array7[j] = 0;
}
Array.Copy(array6, 2, array7, 0, array6.Length - 2);
bool flag = array3.Length == array7.Length;
if (flag)
{
for (int k = 0; k < array7.Length; k++)
{
if (array3[k] != array7[k])
{
flag = false;
break;
}
}
}
ArchestrAResult result = ResultFactory.MakeGoodResult();
if (flag)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "SvcAuth: Confirmed {0}-bit client validation data, secure session established", new object[1] { array7.Length * 8 }));
SecureSessionEstablished = true;
ReasonSecureSessionNotEstablished = "Secure session established";
}
else
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, string.Format(CultureInfo.CurrentCulture, "SvcAuth: Could not confirm {0}-bit client validation data, secure session not established", new object[1] { array7.Length * 8 }));
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, string.Format(CultureInfo.CurrentCulture, "SvcAuth: Could not confirm {0}-bit client validation data, secure session not established", new object[1] { array7.Length * 8 }));
SecureSessionEstablished = false;
ReasonSecureSessionNotEstablished = "Client validation payload incorrect";
result = ResultFactory.MakeResult(ArchestrAError.ApplicationAuthenticationError, 0);
}
return result;
}
public ArchestrAResult ProcessClientDisconnect(ConnectionId Id)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 100, "SvcAuth: Processing Disconnect() call from client");
Reset();
ReasonSecureSessionNotEstablished = "Client disconnected";
return ResultFactory.MakeGoodResult();
}
private void Reset()
{
connectionId = new ConnectionId
{
Id = default(Guid)
};
SecureSessionEstablished = false;
ReasonSecureSessionNotEstablished = "Reset";
ClientPublicKey = BigInteger.Zero;
ServicePrivateKey = BigInteger.MinusOne;
ServicePublicKey = BigInteger.Zero;
base.NegotiatedKey = new byte[200];
m_Random.GetBytes(base.NegotiatedKey);
}
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract]
public class ServiceDiagnostic
{
[DataMember]
public string DiagnosticName { get; set; }
[DataMember]
public string DiagnosticValue { get; set; }
}
@@ -0,0 +1,37 @@
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract]
public class ServiceDiagnosticList
{
[DataMember]
private Collection<ServiceDiagnostic> diagnosticData = new Collection<ServiceDiagnostic>();
[DataMember]
public string ServiceInstance { get; set; }
[DataMember]
public string ServiceType { get; set; }
public void ClearDiagnosticData()
{
diagnosticData.Clear();
}
public Collection<ServiceDiagnostic> FetchDiagnosticData()
{
return diagnosticData;
}
public void AddServiceDiagnostic(ServiceDiagnostic serviceDiagnostic)
{
diagnosticData.Add(serviceDiagnostic);
}
public bool RemoveServiceDiagnostic(ServiceDiagnostic serviceDiagnostic)
{
return diagnosticData.Remove(serviceDiagnostic);
}
}
@@ -0,0 +1,76 @@
using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract]
public class ServiceInfo
{
[DataMember]
private Collection<ServiceDiagnostic> diagnosticList = new Collection<ServiceDiagnostic>();
[DataMember]
public string ServiceInstanceName { get; set; }
[DataMember]
public string ServiceConfig { get; set; }
[DataMember]
public string ServiceHostName { get; set; }
[DataMember]
public string ServiceDllName { get; set; }
[DataMember]
public string ContractTypeName { get; set; }
[DataMember]
public string BaseAddress { get; set; }
[DataMember]
public string MexAddress { get; set; }
[DataMember]
public DateTime ReregistrationTime { get; set; }
[DataMember]
public double RegistrationPeriod { get; set; }
[DataMember]
public DateTime PingTime { get; set; }
[DataMember]
public double PingPeriod { get; set; }
[DataMember]
public DateTime NextPingTime { get; set; }
public long PingIntervalCounter { get; set; }
[DataMember]
public bool PublishWcfEndpoints { get; set; }
[DataMember]
public bool IsRunning { get; set; }
public void ClearServiceDiagnostic()
{
diagnosticList.Clear();
}
public Collection<ServiceDiagnostic> FetchDiagnosticList()
{
return diagnosticList;
}
public void AddServiceDiagnostic(ServiceDiagnostic serviceDiagnostic)
{
diagnosticList.Add(serviceDiagnostic);
}
public bool RemoveServiceDiagnostic(ServiceDiagnostic serviceDiagnostic)
{
return diagnosticList.Remove(serviceDiagnostic);
}
}
@@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public enum Status
{
[EnumMember]
Success,
[EnumMember]
Failure,
[EnumMember]
Unknown
}
@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct StatusTemporaryEndpoint
{
[DataMember]
public string EndpointName;
[DataMember]
public string EndpointState;
}
@@ -0,0 +1,9 @@
namespace ArchestrAServices.Contract;
public enum SubscriptionStateType : ushort
{
SubsEnableState = 1,
SubsSampleInterval = 2,
SubsMaxQueueSize = 3,
SubsUnknown = ushort.MaxValue
}
@@ -0,0 +1,43 @@
using System.Runtime.Serialization;
namespace ArchestrAServices.Contract;
[DataContract(Namespace = "http://ArchestrAServices.Contract")]
public struct SystemAuthenticationASBConfiguration
{
[DataMember]
public string solutionName;
[DataMember]
public byte[] generator;
[DataMember]
public byte[] prime;
[DataMember]
public string hashAlgorithm;
[DataMember]
public byte[] initializationVector;
[DataMember]
public byte[] saltValue;
[DataMember]
public int passwordDerivationIterations;
[DataMember]
public int keySize;
[DataMember]
public byte[] EncryptedSharedSecret;
[DataMember]
public byte[] EncryptedCertificate;
[DataMember]
public string isDefault;
[DataMember]
public string srNodeName;
}
@@ -0,0 +1,24 @@
using System;
namespace ArchestrAServices.Contract;
public static class SystemAuthenticationConstants
{
public static string MakeTemporaryRegistrationEndpointAddress(string SRNode)
{
if (SRNode.ToLower() == "localhost")
{
SRNode = Environment.MachineName;
}
return "net.tcp://" + SRNode + ":7084/SystemAuthentication/Registration";
}
public static string MakeTemporaryPairingEndpointAddress(string SRNode)
{
if (SRNode.ToLower() == "localhost")
{
SRNode = Environment.MachineName;
}
return "net.tcp://" + SRNode + ":7085/SystemAuthentication/Pairing";
}
}
@@ -0,0 +1,9 @@
namespace ArchestrAServices.Contract;
public enum TemporaryEndpointState
{
EndpointOpen = 0,
EndpointClosed = 1,
EndpointFaulted = 2,
EndpointUnknown = 32767
}
@@ -0,0 +1,8 @@
namespace ArchestrAServices.Contract;
public struct TemporaryEndpointStatus
{
public string EndpointName;
public TemporaryEndpointState EndpointState;
}
@@ -0,0 +1,162 @@
#define TRACE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Xml;
using ArchestrAServices.Common;
namespace ArchestrAServices.Contract;
public class TokenManager
{
public static UserToken RepackageSamlToken(UserToken userAuthentication, byte[] incomingSharedSecret, byte[] outgoingSharedSecret)
{
SamlSecurityToken samlReadToken = ExtractIncomingSamlToken(userAuthentication, incomingSharedSecret);
string tokenId = string.Empty;
return SerializeSamlToken(PackageOutgoingSamlToken(samlReadToken, outgoingSharedSecret, out tokenId), tokenId);
}
public static SamlSecurityToken ExtractIncomingSamlToken(UserToken userAuthentication, byte[] incomingSharedSecret)
{
if (incomingSharedSecret == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, "ExtractIncomingSamlToken: incomingSharedSecret cannot be null");
return null;
}
SamlSecurityToken samlSecurityToken = null;
try
{
SecurityToken item = new BinarySecretSecurityToken(userAuthentication.Password, incomingSharedSecret);
WSSecurityTokenSerializer wSSecurityTokenSerializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11, emitBspRequiredAttributes: false, new SamlSerializer());
XmlReader reader = XmlReader.Create(new MemoryStream(userAuthentication.SamlToken));
if (wSSecurityTokenSerializer.CanReadToken(reader))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, "Serializer is capable of reading SAML token from XML");
SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new List<SecurityToken> { item }.AsReadOnly(), canMatchLocalId: true);
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, "Serializer is reading token");
SecurityToken securityToken = wSSecurityTokenSerializer.ReadToken(reader, tokenResolver);
if (securityToken != null)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, "Serializer successfully read a token");
samlSecurityToken = securityToken as SamlSecurityToken;
if (samlSecurityToken == null)
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, "Serializer could not read a SAML token");
}
}
else
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, "Serializer could not read the token");
}
}
else
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, "Serializer is NOT capable of reading SAML token to XML");
}
}
catch (Exception ex)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, string.Format(CultureInfo.CurrentCulture, "Exception deserializing SAML token: {0}", new object[1] { ex.Message }));
Exception innerException = ex.InnerException;
if (innerException != null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, string.Format(CultureInfo.CurrentCulture, "--> {0}", new object[1] { innerException.Message }));
Exception innerException2 = innerException.InnerException;
if (innerException2 != null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, string.Format(CultureInfo.CurrentCulture, "--> {0}", new object[1] { innerException2.Message }));
}
}
}
return samlSecurityToken;
}
private static SamlSecurityToken PackageOutgoingSamlToken(SamlSecurityToken samlReadToken, byte[] outgoingSharedSecret, out string tokenId)
{
tokenId = string.Empty;
if (samlReadToken == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, "PackageOutgoingSamlToken: samlReadToken cannot be null");
return null;
}
if (outgoingSharedSecret == null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Warning, 0, "PackageOutgoingSamlToken: outgoingSharedSecret cannot be null");
return null;
}
SamlSecurityToken result = null;
try
{
SecurityToken securityToken = new BinarySecretSecurityToken(outgoingSharedSecret);
tokenId = securityToken.Id;
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Information, 0, string.Format(CultureInfo.CurrentCulture, "PackageOutgoingSamlToken: creating skic from id='{0}'", new object[1] { securityToken.Id }));
SecurityKeyIdentifierClause securityKeyIdentifierClause = securityToken.CreateKeyIdentifierClause<LocalIdKeyIdentifierClause>();
SecurityKeyIdentifier signingKeyIdentifier = new SecurityKeyIdentifier(securityKeyIdentifierClause);
List<string> list = new List<string>(1);
SecurityKeyIdentifier securityKeyIdentifier = null;
list.Add(SamlConstants.SenderVouches);
new SamlSubject(null, null, null, list, null, securityKeyIdentifier);
SigningCredentials signingCredentials = new SigningCredentials(securityToken.SecurityKeys[0], "http://www.w3.org/2000/09/xmldsig#hmac-sha1", "http://www.w3.org/2000/09/xmldsig#sha1", signingKeyIdentifier);
SamlAssertion assertion = samlReadToken.Assertion;
result = new SamlSecurityToken(new SamlAssertion(assertion.AssertionId, assertion.Issuer, assertion.IssueInstant, assertion.Conditions, assertion.Advice, assertion.Statements)
{
SigningCredentials = signingCredentials
});
}
catch (Exception ex)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, string.Format(CultureInfo.CurrentCulture, "Exception caught in CreateSamlToken: '{0}'", new object[1] { ex.Message }));
}
return result;
}
public static UserToken SerializeSamlToken(SamlSecurityToken samlToken, string tokenId)
{
UserToken result = default(UserToken);
if (samlToken != null)
{
WSSecurityTokenSerializer wSSecurityTokenSerializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11, emitBspRequiredAttributes: true, new SamlSerializer());
if (wSSecurityTokenSerializer.CanWriteToken(samlToken))
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Verbose, 0, "Serializer is capable of writing SAML token to XML");
try
{
using (MemoryStream memoryStream = new MemoryStream())
{
XmlWriter writer = XmlWriter.Create(memoryStream);
wSSecurityTokenSerializer.WriteToken(writer, samlToken);
result.IdType = EnumASBFactory.CredentialTypeToInt(CredentialType.SamlToken);
result.SamlToken = memoryStream.ToArray();
result.Password = tokenId;
}
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Verbose, 0, string.Format(CultureInfo.CurrentCulture, "Serialized SAML Token {0}:", new object[1] { samlToken.Id }));
}
catch (Exception ex)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, string.Format(CultureInfo.CurrentCulture, "Exception during serialization: '{0}'", new object[1] { ex.Message }));
Exception innerException = ex.InnerException;
if (innerException != null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, string.Format(CultureInfo.CurrentCulture, "-> '{0}'", new object[1] { innerException.Message }));
Exception innerException2 = innerException.InnerException;
if (innerException2 != null)
{
SvcTrace.DiagException.TraceEvent(TraceEventType.Error, 0, string.Format(CultureInfo.CurrentCulture, "-> '{0}'", new object[1] { innerException2.Message }));
}
}
}
}
else
{
SvcTrace.DiagDiagnostics.TraceEvent(TraceEventType.Verbose, 0, "Serializer is NOT capable of writing SAML token to XML");
}
}
return result;
}
}

Some files were not shown because too many files have changed in this diff Show More