/// <summary> /// Creates the session. /// </summary> public void Create( EndpointDescription endpoint, ApplicationDescription client, byte[] clientCertificate, string sessionName, double sessionTimeout, out NodeId sessionId, out NodeId authenticationToken, out byte[] serverNonce, out double revisedSessionTimeout) { lock (m_lock) { // save the secure channel id. m_secureChannelId = null; if (OperationContext.Current != null) { m_secureChannelId = OperationContext.Current.Channel.SessionId; } m_endpoint = endpoint; m_client = client; m_sessionName = sessionName; if (clientCertificate != null) { m_clientCertificate = new X509Certificate2(clientCertificate); } // Create a public and a private identifier for the session. The public identifier is visible in the // address space and audit logs. The private identifier is only used by the client to identify itself // when it sends a request. Clients and servers that do not keep the authentication token will be vulnerable // to session hijacking when using transports such as SSL to implement the secure channel. It is not an // issue for applications that use WS-Secure Conversation. // create a guid for a session id. use it for an authentication token as well. m_sessionId = new NodeId(System.Guid.NewGuid(), 1); m_authenticationToken = authenticationToken = sessionId = m_sessionId; // set a reasonable session timeout. m_sessionTimeout = sessionTimeout; if (m_sessionTimeout < 30000) { m_sessionTimeout = 30000; } revisedSessionTimeout = m_sessionTimeout; // create a server nonce. m_serverNonce = serverNonce = new byte[32]; RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); random.GetBytes(m_serverNonce); } }
/// <summary> /// Initializes the binding. /// </summary> /// <param name="namespaceUris">The namespace uris.</param> /// <param name="factory">The factory.</param> /// <param name="configuration">The configuration.</param> /// <param name="description">The description.</param> public UaSoapXmlOverTcpBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration, EndpointDescription description) : base(namespaceUris, factory, configuration) { if (description != null && description.SecurityMode != MessageSecurityMode.None) { SymmetricSecurityBindingElement bootstrap = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(); bootstrap.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature; bootstrap.DefaultAlgorithmSuite = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri); bootstrap.IncludeTimestamp = true; bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10; // bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; bootstrap.RequireSignatureConfirmation = false; bootstrap.SecurityHeaderLayout = SecurityHeaderLayout.Strict; m_security = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap, true); m_security.MessageProtectionOrder = MessageProtectionOrder.EncryptBeforeSign; m_security.DefaultAlgorithmSuite = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri); m_security.IncludeTimestamp = true; m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10; // m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; m_security.RequireSignatureConfirmation = false; m_security.SecurityHeaderLayout = SecurityHeaderLayout.Strict; m_security.SetKeyDerivation(true); } m_encoding = new BinaryMessageEncodingBindingElement(); // WCF does not distinguish between arrays and byte string. int maxArrayLength = configuration.MaxArrayLength; if (configuration.MaxArrayLength < configuration.MaxByteStringLength) { maxArrayLength = configuration.MaxByteStringLength; } m_encoding.ReaderQuotas.MaxArrayLength = maxArrayLength; m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength; m_encoding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue; m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue; m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue; m_transport = new System.ServiceModel.Channels.TcpTransportBindingElement(); m_transport.ManualAddressing = false; m_transport.MaxBufferPoolSize = Int32.MaxValue; m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize; }
/// <summary> /// Initializes a new instance of the <see cref="UaTcpTransportChannel"/> class. /// </summary> /// <param name="remoteEndpoint">the remoteEndpoint.</param> public UaTcpTransportChannel(EndpointDescription remoteEndpoint) { if (remoteEndpoint == null) { throw new ArgumentNullException(nameof(remoteEndpoint)); } this.RemoteEndpoint = remoteEndpoint; this.LocalReceiveBufferSize = DefaultBufferSize; this.LocalSendBufferSize = DefaultBufferSize; this.LocalMaxMessageSize = DefaultMaxMessageSize; this.LocalMaxChunkCount = DefaultMaxChunkCount; }
/// <summary> /// Initializes the binding. /// </summary> /// <param name="namespaceUris">The namespace uris.</param> /// <param name="factory">The factory.</param> /// <param name="configuration">The configuration.</param> /// <param name="description">The description.</param> public UaSoapXmlBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration, EndpointDescription description) : base(namespaceUris, factory, configuration) { if (description != null && description.SecurityMode != MessageSecurityMode.None) { TransportSecurityBindingElement bootstrap = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); bootstrap.IncludeTimestamp = true; bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; bootstrap.SecurityHeaderLayout = SecurityHeaderLayout.Strict; m_security = SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap); m_security.IncludeTimestamp = true; m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; m_security.SecurityHeaderLayout = SecurityHeaderLayout.Strict; } m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8); // WCF does not distinguish between arrays and byte string. int maxArrayLength = configuration.MaxArrayLength; if (configuration.MaxArrayLength < configuration.MaxByteStringLength) { maxArrayLength = configuration.MaxByteStringLength; } m_encoding.ReaderQuotas.MaxArrayLength = maxArrayLength; m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength; m_encoding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue; m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue; m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue; m_transport = new HttpTransportBindingElement(); m_transport.AllowCookies = false; m_transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; m_transport.ManualAddressing = false; m_transport.MaxBufferSize = configuration.MaxMessageSize; m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize; m_transport.TransferMode = TransferMode.Buffered; }
/// <summary> /// Initializes the binding. /// </summary> public UaBasicHttpBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration, EndpointDescription description) : base(namespaceUris, factory, configuration) { if (description != null && description.SecurityMode != MessageSecurityMode.None) { // TBD } m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8); // WCF does not distinguish between arrays and byte string. int maxArrayLength = configuration.MaxArrayLength; if (configuration.MaxArrayLength < configuration.MaxByteStringLength) { maxArrayLength = configuration.MaxByteStringLength; } m_encoding.ReaderQuotas.MaxArrayLength = maxArrayLength; m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength; m_encoding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue; m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue; m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue; m_transport = new HttpTransportBindingElement(); m_transport.AllowCookies = false; m_transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; m_transport.BypassProxyOnLocal = true; m_transport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; m_transport.KeepAliveEnabled = true; m_transport.ManualAddressing = false; m_transport.MaxBufferPoolSize = Int32.MaxValue; m_transport.MaxBufferSize = configuration.MaxMessageSize; m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize; m_transport.TransferMode = TransferMode.Buffered; m_transport.UseDefaultWebProxy = false; }
/// <summary> /// Creates a channel for for a client. /// </summary> public TcpClientChannel( string contextId, BufferManager bufferManager, TcpChannelQuotas quotas, X509Certificate2 clientCertificate, X509Certificate2 serverCertificate, EndpointDescription endpoint) : base( contextId, bufferManager, quotas, serverCertificate, (endpoint != null)?new EndpointDescriptionCollection(new EndpointDescription[] { endpoint }):null, (endpoint != null)?endpoint.SecurityMode:MessageSecurityMode.None, (endpoint != null)?endpoint.SecurityPolicyUri:SecurityPolicies.None) { if (endpoint != null && endpoint.SecurityMode != MessageSecurityMode.None) { if (clientCertificate == null) throw new ArgumentNullException("clientCertificate"); if (clientCertificate.RawData.Length > TcpMessageLimits.MaxCertificateSize) { throw new ArgumentException( Utils.Format("The DER encoded certificate may not be more than {0} bytes.", TcpMessageLimits.MaxCertificateSize), "clientCertificate"); } ClientCertificate = clientCertificate; } m_requests = new Dictionary<uint,WriteOperation>(); m_lastRequestId = 0; m_ConnectCallback = new AsyncCallback(OnConnectComplete); m_StartHandshake = new TimerCallback(OnScheduledHandshake); m_HandshakeComplete = new AsyncCallback(OnHandshakeComplete); // save the endpoint. EndpointDescription = endpoint; m_url = new Uri(endpoint.EndpointUrl); }
/// <summary> /// Connects the specified endpoint URL. /// </summary> /// <param name="endpointUrl">The endpoint URL.</param> /// <exception cref="System.ArgumentNullException">endpointUrl</exception> /// <exception cref="System.ArgumentException">endpointUrl</exception> public async Task Connect(string endpointUrl) { if (String.IsNullOrEmpty(endpointUrl)) { throw new ArgumentNullException(nameof(endpointUrl)); } if (!Uri.IsWellFormedUriString(endpointUrl, UriKind.Absolute)) { throw new ArgumentException(endpointUrl + " is not a valid URL.", nameof(endpointUrl)); } bool serverHalted = false; do { serverHalted = false; try { EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(endpointUrl, true); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(Application.ApplicationConfiguration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); await Connect(endpoint); } catch (ServiceResultException e) { if (e.StatusCode == StatusCodes.BadServerHalted) { serverHalted = true; await Task.Delay(1000); } else { throw; } } } while (serverHalted); }
/// <summary> /// Select a security endpoint from description. /// </summary> public static EndpointDescription SelectEndpoint( ApplicationConfiguration configuration, EndpointDescriptionCollection endpoints, Uri url, string securityPolicy) { EndpointDescription selectedEndpoint = null; // select the best endpoint to use based on the selected URL and the UseSecurity checkbox. foreach (var endpoint in endpoints) { // check for a match on the URL scheme. if (endpoint.EndpointUrl.StartsWith(url.Scheme)) { // skip unsupported security policies if (SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri) == null) { continue; } // pick the first available endpoint by default. if (selectedEndpoint == null && securityPolicy.Equals(endpoint.SecurityPolicyUri)) { selectedEndpoint = endpoint; continue; } if (selectedEndpoint?.SecurityMode < endpoint.SecurityMode && securityPolicy.Equals(endpoint.SecurityPolicyUri)) { selectedEndpoint = endpoint; } } } // return the selected endpoint. return(selectedEndpoint); }
/// <summary> /// Creates a new session. /// </summary> /// <returns>The new session object.</returns> private async Task <Session> Connect(string serverUrl) { // disconnect from existing session. Disconnect( ); if (m_configuration == null) { throw new ArgumentNullException("m_configuration"); } // select the best endpoint. EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(serverUrl, UseSecurity); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); m_session = await Session.Create( m_configuration, endpoint, false, false, (string.IsNullOrEmpty(OpcUaName))?m_configuration.ApplicationName : OpcUaName, 60000, UserIdentity, new string[] { }); // set up keep alive callback. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // update the client status m_IsConnected = true; // raise an event. DoConnectComplete(null); // return the new session. return(m_session); }
/// <summary> /// Initializes the binding. /// </summary> public UaBasicHttpBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration, EndpointDescription description) : base(namespaceUris, factory, configuration) { if (description != null && description.SecurityMode != MessageSecurityMode.None) { // TBD } m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8); // WCF does not distinguish between arrays and byte string. int maxArrayLength = configuration.MaxArrayLength; if (configuration.MaxArrayLength < configuration.MaxByteStringLength) { maxArrayLength = configuration.MaxByteStringLength; } m_encoding.ReaderQuotas.MaxArrayLength = maxArrayLength; m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength; m_encoding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue; m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue; m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue; m_transport = new HttpTransportBindingElement(); m_transport.AllowCookies = false; m_transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; m_transport.ManualAddressing = false; m_transport.MaxBufferSize = configuration.MaxMessageSize; m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize; m_transport.TransferMode = TransferMode.Buffered; }
/// <summary> /// Creates a new session. /// </summary> /// <returns>The new session object.</returns> public Session Connect() { // disconnect from existing session. Disconnect(); // determine the URL that was selected. string serverUrl = UrlCB.Text; if (UrlCB.SelectedIndex >= 0) { serverUrl = (string)UrlCB.SelectedItem; } // select the best endpoint. EndpointDescription endpointDescription = ClientUtils.SelectEndpoint(serverUrl, UseSecurityCK.Checked); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); m_session = Session.Create( m_configuration, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName))?m_configuration.ApplicationName:SessionName, 60000, UserIdentity, PreferredLocales); // set up keep alive callback. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // raise an event. DoConnectComplete(null); // return the new session. return(m_session); }
/// <summary> /// Initializes the binding. /// </summary> /// <param name="namespaceUris">The namespace uris.</param> /// <param name="factory">The factory.</param> /// <param name="configuration">The configuration.</param> /// <param name="description">The description.</param> public UaHttpsSoapBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration, EndpointDescription description) : base(namespaceUris, factory, configuration) { m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8); // WCF does not distinguish between arrays and byte string. int maxArrayLength = configuration.MaxArrayLength; if (configuration.MaxArrayLength < configuration.MaxByteStringLength) { maxArrayLength = configuration.MaxByteStringLength; } m_encoding.ReaderQuotas.MaxArrayLength = maxArrayLength; m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength; m_encoding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue; m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue; m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue; m_transport = new HttpsTransportBindingElement(); m_transport.AllowCookies = false; m_transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; m_transport.BypassProxyOnLocal = true; m_transport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; m_transport.KeepAliveEnabled = true; m_transport.ManualAddressing = false; m_transport.MaxBufferPoolSize = Int32.MaxValue; m_transport.MaxBufferSize = configuration.MaxMessageSize; m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize; m_transport.TransferMode = TransferMode.Buffered; m_transport.UseDefaultWebProxy = false; }
/// <summary> /// Creates a new session. /// </summary> /// <returns>The new session object.</returns> public async Task <Session> Connect() { // disconnect from existing session. //Disconnect(); if (m_configuration == null) { throw new ArgumentNullException("m_configuration"); } // TODO bool useSecurity = false; // select the best endpoint. EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(serverUrl, useSecurity, m_discoverTimeout); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); m_session = await Session.Create( m_configuration, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName))?m_configuration.ApplicationName : SessionName, 60000, UserIdentity, PreferredLocales); // set up keep alive callback. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // raise an event. DoConnectComplete(null); // return the new session. return(m_session); }
private void ConnectButton_Click(object sender, EventArgs e) { string endPointUrl = this.EndpointCB.Text; Uri uri = new Uri(endPointUrl); //2 - Create EndpointDescription EndpointDescription description = new EndpointDescription(); description.EndpointUrl = uri.ToString(); description.SecurityMode = MessageSecurityMode.SignAndEncrypt; description.SecurityPolicyUri = SecurityPolicies.Basic128Rsa15; description.Server.ApplicationUri = Utils.UpdateInstanceUri(uri.ToString()); description.Server.ApplicationName = uri.AbsolutePath; //3 - Create Endpoint ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, description); //4 - Create Session m_session = Session.Create(m_config, endpoint, true, "", 60000, null, null); //5 - Show the server namespace browseTreeCtrl1.SetView(m_session, BrowseViewType.Objects, null); }
/// <summary> /// Displays the dialog. /// </summary> public bool ShowDialog(EndpointDescription endpoint) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } EndpointTB.Text = endpoint.EndpointUrl; ServerNameTB.Text = endpoint.Server.ApplicationName.Text; ServerUriTB.Text = endpoint.Server.ApplicationUri; try { X509Certificate2 certificate = CertificateFactory.Create(endpoint.ServerCertificate, true); ServerCertificateTB.Text = String.Format("{0}", certificate.Subject); } catch { ServerCertificateTB.Text = "<bad certificate>"; } SecurityModeTB.Text = String.Format("{0}", endpoint.SecurityMode); ; SecurityPolicyUriTB.Text = String.Format("{0}", endpoint.SecurityPolicyUri); UserIdentityTypeTB.Text = ""; foreach (UserTokenPolicy policy in endpoint.UserIdentityTokens) { UserIdentityTypeTB.Text += String.Format("{0} ", policy.TokenType); } if (ShowDialog() != DialogResult.OK) { return(false); } return(true); }
/// <summary> /// Returns the stack action to use for the current context. /// </summary> public static StackAction GetStackAction(TestCaseContext context, EndpointDescription endpointDescription) { if (!endpointDescription.EndpointUrl.StartsWith(Utils.UriSchemeOpcTcp)) { return(null); } StackAction action = new StackAction(); switch (context.StackEventType) { case 1: { action.ActionType = StackActionType.CorruptMessageChunk; break; } case 2: { action.ActionType = StackActionType.ReuseSequenceNumber; break; } case 3: { action.ActionType = StackActionType.CloseConnectionSocket; break; } case 4: { action.ActionType = StackActionType.CloseConnectionSocket; break; } default: { return(null); } } // cannot detect corrupt messages predictably if no security is used. if (endpointDescription.SecurityMode == MessageSecurityMode.None) { if (action.ActionType == StackActionType.CorruptMessageChunk) { action.ActionType = StackActionType.ReuseSequenceNumber; } } return(action); }
// Подключение к считывателю по OPC UA public void connectOPC() { // Точка подключения EndpointDescription eds = new EndpointDescription("opc.tcp://" + url + "/"); try { myHelperApi.Connect(eds, true, false, "", "").Wait(); rfidKey.SetValue("Debug", url + " | Success connected"); } catch { rfidKey.SetValue("Debug", url + " | Error connected"); } // Проверка результатов подключения if (myHelperApi.Session != null && myHelperApi.Session.Connected) { // Запрос методов и пространства имен myRfidMethodIdentifiers = new UARfidMethodIdentifiers(myHelperApi); rfidNamespaceIdx = GetRfidNamespaceIndex(); } this.connected = (myHelperApi.Session != null && myHelperApi.Session.Connected); }
/// <summary> /// Connects to a single OPC UA Server's endpoint /// </summary> public static async Task EndpointConnect(Uri endpointUrl) { EndpointDescription selectedEndpoint = SelectUaTcpEndpoint(DiscoverEndpoints(m_configuration, endpointUrl, 10)); ConfiguredEndpoint configuredEndpoint = new ConfiguredEndpoint(selectedEndpoint.Server, EndpointConfiguration.Create(m_configuration)); configuredEndpoint.Update(selectedEndpoint); Session newSession = await Session.Create( m_configuration, configuredEndpoint, true, false, m_configuration.ApplicationName, 60000, new UserIdentity(new AnonymousIdentityToken()), null); if (newSession != null) { Trace("Opc.Ua.Publisher.Module: Created session with updated endpoint " + selectedEndpoint.EndpointUrl + " from server!"); newSession.KeepAlive += new KeepAliveEventHandler((sender, e) => StandardClient_KeepAlive(sender, e, newSession)); m_sessions.Add(newSession); } }
/// <summary> /// Connects to a single OPC UA Server's endpoint /// </summary> public static async Task EndpointConnect(Uri endpointUrl) { EndpointDescription selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl.AbsoluteUri, true); ConfiguredEndpoint configuredEndpoint = new ConfiguredEndpoint(selectedEndpoint.Server, EndpointConfiguration.Create(m_configuration)); configuredEndpoint.Update(selectedEndpoint); Session newSession = await Session.Create( m_configuration, configuredEndpoint, true, false, m_configuration.ApplicationName, 60000, new UserIdentity(new AnonymousIdentityToken()), null); if (newSession != null) { Trace("Created session with updated endpoint " + selectedEndpoint.EndpointUrl + " from server!"); newSession.KeepAlive += new KeepAliveEventHandler((sender, e) => StandardClient_KeepAlive(sender, e, newSession)); m_sessions.Add(newSession); } }
private IEndpoint BuildEndpoint(EndpointDescription description) { switch (description) { case SocketServer sockServ: return(new PXSocketServer( sockServ.Address, sockServ.Port, this.container, sockServ.SenderId, sockServ.StreamWrappers, sockServ.ProtocolProvider, sockServ.ReconnectAllowedValue )); case CliServer cliServ: return(new PXCliServer( cliServ.PipeName, this.container )); } return(null); }
private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) { try { int index = EndpointCB.SelectedIndex; if (index == -1) { return; } EndpointDescription endpoint = m_endpoints[index]; switch (endpoint.EncodingSupport) { case BinaryEncodingSupport.Required: { UseBinaryEncodingCK.Checked = true; UseBinaryEncodingCK.Enabled = false; break; } case BinaryEncodingSupport.Optional: { UseBinaryEncodingCK.Checked = true; UseBinaryEncodingCK.Enabled = true; break; } default: { UseBinaryEncodingCK.Checked = false; UseBinaryEncodingCK.Enabled = false; break; } } } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Create OPC UA client session /// </summary> /// <param name="applicationConfig"></param> /// <param name="selectedEndpoint"></param> /// <param name="sessionName"></param> /// <param name="sessionTimeout"></param> /// <param name="keepAlive"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ServiceResultException"></exception> public async Task CreateOpcUaSession(ApplicationConfiguration applicationConfig, EndpointDescription selectedEndpoint, string sessionName, uint sessionTimeout, KeepAliveEventHandler keepAlive = null) { if (applicationConfig == null) { throw new ArgumentNullException(nameof(applicationConfig)); } if (selectedEndpoint == null) { throw new ArgumentNullException(nameof(selectedEndpoint)); } if (string.IsNullOrWhiteSpace(sessionName)) { throw new ArgumentNullException(nameof(sessionName)); } this.SessionTimeout = sessionTimeout == 0 ? throw new ArgumentException(nameof(sessionTimeout)) : sessionTimeout; var endpointConfiguration = EndpointConfiguration.Create(applicationConfiguration: applicationConfig); var endpoint = new ConfiguredEndpoint(collection: null, description: selectedEndpoint, configuration: endpointConfiguration); this.Session = await Session.Create(configuration : applicationConfig, endpoint : endpoint, updateBeforeConnect : false, sessionName : sessionName, sessionTimeout : this.SessionTimeout, identity : this.User, preferredLocales : null); this.RegisterKeepAlive(keepAlive: keepAlive); }
/// <summary> /// Show a Sign In dialog if the remote endpoint demands a UserNameIdentity token. /// </summary> /// <param name="endpoint">The remote endpoint.</param> /// <returns>A UserIdentity</returns> private static async Task <IUserIdentity> ShowSignInDialog(EndpointDescription endpoint) { IUserIdentity userIdentity = null; if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous)) { userIdentity = new AnonymousIdentity(); } else if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName)) { Console.WriteLine("Server is requesting UserName identity..."); Console.Write("Enter user name: "); var userName = Console.ReadLine(); Console.Write("Enter password: "******"Program supports servers requesting Anonymous and UserName identity."); } return(userIdentity); }
private Data GetRequest(BehaviorChain chain, EndpointDescription endpoint) { var firstCall = chain.FirstCall(); DataType type = null; List <BodyLineItem> description = null; if (firstCall.HasInput && !chain.Route.AllowsGet() && !chain.Route.AllowsDelete()) { type = _typeGraphFactory.BuildGraph(firstCall.InputType(), chain.FirstCall()); description = _bodyDescriptionFactory.Create(type); } return(_configuration.RequestOverrides.Apply(chain, new Data { Comments = endpoint.RequestComments, Headers = GetHeaders(chain, HttpDirection.Request), MimeTypes = GetMimeTypes(chain, HttpDirection.Request), Body = new Body { Type = type, Description = description } })); }
/// <summary> /// Displays the dialog. /// </summary> public bool ShowDialog(EndpointDescription endpoint) { if (endpoint == null) throw new ArgumentNullException("endpoint"); EndpointTB.Text = endpoint.EndpointUrl; ServerNameTB.Text = endpoint.Server.ApplicationName.Text; ServerUriTB.Text = endpoint.Server.ApplicationUri; try { X509Certificate2 certificate = CertificateFactory.Create(endpoint.ServerCertificate, true); ServerCertificateTB.Text = String.Format("{0}", certificate.Subject); } catch { ServerCertificateTB.Text = "<bad certificate>"; } SecurityModeTB.Text = String.Format("{0}", endpoint.SecurityMode);; SecurityPolicyUriTB.Text = String.Format("{0}", endpoint.SecurityPolicyUri); UserIdentityTypeTB.Text = ""; foreach (UserTokenPolicy policy in endpoint.UserIdentityTokens) { UserIdentityTypeTB.Text += String.Format("{0} ", policy.TokenType); } if (ShowDialog() != DialogResult.OK) { return false; } return true; }
/// <summary> /// Creates a minimal endpoint description which allows a client to connect to a server. /// </summary> /// <remarks> /// In most cases the client will use the server's discovery endpoint to fetch the information /// constained in this structure. /// </remarks> public static EndpointDescription CreateEndpointDescription(string Url) { // create the endpoint description. EndpointDescription endpointDescription = new EndpointDescription(); //endpointDescription.EndpointUrl = Utils.Format("opc.tcp://{0}:4840", System.Net.Dns.GetHostName()); endpointDescription.EndpointUrl = Url; // specify the security policy to use. //endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic128Rsa15; endpointDescription.SecurityPolicyUri = SecurityPolicies.None; //endpointDescription.SecurityMode = MessageSecurityMode.SignAndEncrypt; endpointDescription.SecurityMode = MessageSecurityMode.None; // specify the transport profile. endpointDescription.TransportProfileUri = Profiles.WsHttpXmlOrBinaryTransport; // load the the server certificate from the local certificate store. CertificateIdentifier certificateIdentifier = new CertificateIdentifier(); certificateIdentifier.StoreType = CertificateStoreType.Windows; certificateIdentifier.StorePath = "LocalMachine\\My"; certificateIdentifier.SubjectName = "UA Test Client"; X509Certificate2 serverCertificate = certificateIdentifier.Find(); if (serverCertificate == null) { throw ServiceResultException.Create(StatusCodes.BadCertificateInvalid, "Could not find server certificate in certificate store: {0}", certificateIdentifier.SubjectName); } endpointDescription.ServerCertificate = serverCertificate.GetRawCertData(); return(endpointDescription); }
/// <summary> /// Initializes the binding. /// </summary> /// <param name="namespaceUris">The namespace uris.</param> /// <param name="factory">The factory.</param> /// <param name="configuration">The configuration.</param> /// <param name="description">The description.</param> public UaSoapXmlBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration, EndpointDescription description) : base(namespaceUris, factory, configuration) { if (description != null && description.SecurityMode != MessageSecurityMode.None) { SymmetricSecurityBindingElement bootstrap = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(); bootstrap.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature; bootstrap.DefaultAlgorithmSuite = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri); bootstrap.IncludeTimestamp = true; bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10; bootstrap.RequireSignatureConfirmation = false; bootstrap.SecurityHeaderLayout = SecurityHeaderLayout.Strict; bootstrap.SetKeyDerivation(true); m_security = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap, true); m_security.MessageProtectionOrder = MessageProtectionOrder.EncryptBeforeSign; m_security.DefaultAlgorithmSuite = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri); m_security.IncludeTimestamp = true; m_security.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy; m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10; m_security.RequireSignatureConfirmation = false; m_security.SecurityHeaderLayout = SecurityHeaderLayout.Strict; m_security.SetKeyDerivation(true); } m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8); // WCF does not distinguish between arrays and byte string. int maxArrayLength = configuration.MaxArrayLength; if (configuration.MaxArrayLength < configuration.MaxByteStringLength) { maxArrayLength = configuration.MaxByteStringLength; } m_encoding.ReaderQuotas.MaxArrayLength = maxArrayLength; m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength; m_encoding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue; m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue; m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue; m_transport = new HttpTransportBindingElement(); m_transport.AllowCookies = false; m_transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; m_transport.BypassProxyOnLocal = true; m_transport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; m_transport.KeepAliveEnabled = true; m_transport.ManualAddressing = false; m_transport.MaxBufferPoolSize = Int32.MaxValue; m_transport.MaxBufferSize = configuration.MaxMessageSize; m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize; m_transport.TransferMode = TransferMode.Buffered; m_transport.UseDefaultWebProxy = false; }
private void SelectCorrespondingEndpointFromList(EndpointDescription endpoint) { if (!m_selecting) { int index = -1; // try to match endpoint description id if (endpoint != null) { for (int ii = 0; ii < EndpointListLB.Items.Count; ii++) { if (endpoint == ((EndpointDescriptionString)EndpointListLB.Items[ii]).EndpointDescription) { index = ii; break; } } } EndpointListLB.SelectedIndex = index; } }
/// <summary> /// Initializes a new instance of the <see cref="UaTcpSessionChannel"/> class. /// </summary> /// <param name="localDescription">The <see cref="ApplicationDescription"/> of the local application.</param> /// <param name="localCertificate">The <see cref="X509Certificate2"/> of the local application.</param> /// <param name="userIdentity">The user identity or null if anonymous. Supports <see cref="AnonymousIdentity"/>, <see cref="UserNameIdentity"/>, <see cref="IssuedIdentity"/> and <see cref="X509Identity"/>.</param> /// <param name="remoteEndpoint">The <see cref="EndpointDescription"/> of the remote application. Obtained from a prior call to UaTcpDiscoveryClient.GetEndpoints.</param> public UaTcpSessionChannel(ApplicationDescription localDescription, X509Certificate2 localCertificate, IUserIdentity userIdentity, EndpointDescription remoteEndpoint) : base(localDescription, localCertificate, remoteEndpoint) { this.UserIdentity = userIdentity; this.SessionTimeout = DefaultSessionTimeout; }
/// <summary> /// 建立与OPC UA的连接,该种方式需要用户名与密码形式 /// </summary> /// <param name="Url">需要连接的Url地址信息</param> /// <param name="userName">用户名</param> /// <param name="userPwd">密码</param> public void Connect(string Url, String userName, String userPwd) { try { // Create the configuration. ApplicationConfiguration configuration = opcUA_Helper.CreateClientConfiguration(); // Create the endpoint description. EndpointDescription endpointDescription = opcUA_Helper.CreateEndpointDescription(Url); // Create the endpoint configuration (use the application configuration to provide default values). EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); // The default timeout for a requests sent using the channel. endpointConfiguration.OperationTimeout = 300000; // Use the pure binary encoding on the wire. endpointConfiguration.UseBinaryEncoding = true; // Create the endpoint. ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); // Create the binding factory. BindingFactory bindingFactory = BindingFactory.Create(configuration); // Update endpoint description using the discovery endpoint. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(bindingFactory); endpointDescription = endpoint.Description; endpointConfiguration = endpoint.Configuration; } X509Certificate2 clientCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find(); // Set up a callback to handle certificate validation errors. configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); // Initialize the channel which will be created with the server. SessionChannel channel = SessionChannel.Create( configuration, endpointDescription, endpointConfiguration, bindingFactory, clientCertificate, null); // Wrap the channel with the session object. // This call will fail if the server does not trust the client certificate. m_Session = new Session(channel, configuration, endpoint); m_Session.ReturnDiagnostics = DiagnosticsMasks.All; // Register keep alive callback. m_Session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); UserIdentity identity = new UserIdentity(userName, userPwd); // Create the session. This actually connects to the server. // Passing null for the user identity will create an anonymous session. m_Session.Open("625IIS - main session", identity); } catch (Exception e) { throw e; } }
/// <summary> /// Starts the server application. /// </summary> /// <param name="configuration">The configuration.</param> protected override void StartApplication(ApplicationConfiguration configuration) { base.StartApplication(configuration); lock (m_lock) { try { // create the datastore for the instance. m_serverInternal = new ServerInternalData( ServerProperties, configuration, MessageContext, new CertificateValidator(), InstanceCertificate); // create the manager responsible for providing localized string resources. ResourceManager resourceManager = CreateResourceManager(m_serverInternal, configuration); // create the manager responsible for incoming requests. RequestManager requestManager = CreateRequestManager(m_serverInternal, configuration); // create the master node manager. MasterNodeManager masterNodeManager = CreateMasterNodeManager(m_serverInternal, configuration); // add the node manager to the datastore. m_serverInternal.SetNodeManager(masterNodeManager); // put the node manager into a state that allows it to be used by other objects. masterNodeManager.Startup(); // create the manager responsible for handling events. EventManager eventManager = CreateEventManager(m_serverInternal, configuration); // creates the server object. m_serverInternal.CreateServerObject( eventManager, resourceManager, requestManager); // do any additional processing now that the node manager is up and running. OnNodeManagerStarted(m_serverInternal); // create the manager responsible for aggregates. m_serverInternal.AggregateManager = CreateAggregateManager(m_serverInternal, configuration); // start the session manager. SessionManager sessionManager = CreateSessionManager(m_serverInternal, configuration); sessionManager.Startup(); // start the subscription manager. SubscriptionManager subscriptionManager = CreateSubscriptionManager(m_serverInternal, configuration); subscriptionManager.Startup(); // add the session manager to the datastore. m_serverInternal.SetSessionManager(sessionManager, subscriptionManager); ServerError = null; // setup registration information. lock (m_registrationLock) { m_bindingFactory = BindingFactory.Create(configuration, MessageContext); m_maxRegistrationInterval = configuration.ServerConfiguration.MaxRegistrationInterval; ApplicationDescription serverDescription = ServerDescription; m_registrationInfo = new RegisteredServer(); m_registrationInfo.ServerUri = serverDescription.ApplicationUri; m_registrationInfo.ServerNames.Add(serverDescription.ApplicationName); m_registrationInfo.ProductUri = serverDescription.ProductUri; m_registrationInfo.ServerType = serverDescription.ApplicationType; m_registrationInfo.GatewayServerUri = null; m_registrationInfo.IsOnline = true; m_registrationInfo.SemaphoreFilePath = null; // add all discovery urls. string computerName = Utils.GetHostName(); for (int ii = 0; ii < BaseAddresses.Count; ii++) { UriBuilder uri = new UriBuilder(BaseAddresses[ii].DiscoveryUrl); if (String.Compare(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0) { uri.Host = computerName; } m_registrationInfo.DiscoveryUrls.Add(uri.ToString()); } // build list of registration endpoints. m_registrationEndpoints = new ConfiguredEndpointCollection(configuration); EndpointDescription endpoint = configuration.ServerConfiguration.RegistrationEndpoint; if (endpoint == null) { endpoint = new EndpointDescription(); endpoint.EndpointUrl = Utils.Format(Utils.DiscoveryUrls[0], "localhost"); endpoint.SecurityLevel = 0; endpoint.SecurityMode = MessageSecurityMode.SignAndEncrypt; endpoint.SecurityPolicyUri = SecurityPolicies.Basic128Rsa15; endpoint.Server.ApplicationType = ApplicationType.DiscoveryServer; } m_registrationEndpoints.Add(endpoint); m_minRegistrationInterval = 1000; m_lastRegistrationInterval = m_minRegistrationInterval; // start registration timer. if (m_registrationTimer != null) { m_registrationTimer.Dispose(); m_registrationTimer = null; } if (m_maxRegistrationInterval > 0) { m_registrationTimer = new Timer(OnRegisterServer, this, m_minRegistrationInterval, Timeout.Infinite); } } // set the server status as running. SetServerState(ServerState.Running); // all initialization is complete. OnServerStarted(m_serverInternal); // monitor the configuration file. if (!String.IsNullOrEmpty(configuration.SourceFilePath)) { m_configurationWatcher = new ConfigurationWatcher(configuration); m_configurationWatcher.Changed += new EventHandler<ConfigurationWatcherEventArgs>(this.OnConfigurationChanged); } } catch (Exception e) { Utils.Trace(e, "Unexpected error starting application"); m_serverInternal = null; ServiceResult error = ServiceResult.Create(e, StatusCodes.BadInternalError, "Unexpected error starting application"); ServerError = error; throw new ServiceResultException(error); } } }
private Data GetResponse(BehaviorChain chain, EndpointDescription endpoint) { var lastCall = chain.LastCall(); DataType type = null; List<BodyLineItem> description = null; if (lastCall.HasOutput) { type = _typeGraphFactory.BuildGraph(lastCall.OutputType()); description = _bodyDescriptionFactory.Create(type); } return _configuration.ResponseOverrides.Apply(chain, new Data { Comments = endpoint.ResponseComments, Headers = GetHeaders(chain, HttpDirection.Response), MimeTypes = GetMimeTypes(chain, HttpDirection.Response), Body = new Body { Type = type, Description = description } }); }
/// <summary> /// Returns an endpoint description for the specified URL. /// </summary> /// <param name="url">The URL to use.</param> /// <returns>Tne endpoint description.</returns> /// <remarks> /// This method fills in default security settings for the server. /// It will not be possible to connect to the server if the server's settings do not match. /// </remarks> private static EndpointDescription CreateEndpointDescription(string url, X509Certificate2 serverCertificate) { // fill in the minimum amount of information. EndpointDescription description = new EndpointDescription(); // The EndpointUrl specifies the communication protocol to use as well as the network address. description.EndpointUrl = url; // The SecurityMode determines what security is applied to the messages. // If the SecurityMode is None then security is turned off. description.SecurityMode = MessageSecurityMode.SignAndEncrypt_3; // The SecurityPolicyUri is a UA defined URI which represents a suite of cryptography algorithms. // This field is ignored if the SecurityMode is None and should be set to SecurityPolicies.None description.SecurityPolicyUri = SecurityPolicies.Basic256Rsa15; // The server certificate is stored as DER encoded blob. description.ServerCertificate = serverCertificate.RawData; return description; }
/// <inheritdoc/> /// <summary> /// Create a new service host for UA TCP. /// </summary> public List <EndpointDescription> CreateServiceHost( ServerBase serverBase, IDictionary <string, ServiceHost> hosts, ApplicationConfiguration configuration, IList <string> baseAddresses, ApplicationDescription serverDescription, List <ServerSecurityPolicy> securityPolicies, X509Certificate2 instanceCertificate, X509Certificate2Collection instanceCertificateChain) { // generate a unique host name. string hostName = "/Tcp"; if (hosts.ContainsKey(hostName)) { hostName += Utils.Format("/{0}", hosts.Count); } // build list of uris. List <Uri> uris = new List <Uri>(); EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection(); // create the endpoint configuration to use. EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); string computerName = Utils.GetHostName(); for (int ii = 0; ii < baseAddresses.Count; ii++) { // UA TCP and HTTPS endpoints support multiple policies. if (!baseAddresses[ii].StartsWith(Utils.UriSchemeOpcTcp, StringComparison.Ordinal)) { continue; } UriBuilder uri = new UriBuilder(baseAddresses[ii]); if (String.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) { uri.Host = computerName; } ITransportListener listener = this.Create(); if (listener != null) { EndpointDescriptionCollection listenerEndpoints = new EndpointDescriptionCollection(); uris.Add(uri.Uri); foreach (ServerSecurityPolicy policy in securityPolicies) { // create the endpoint description. EndpointDescription description = new EndpointDescription(); description.EndpointUrl = uri.ToString(); description.Server = serverDescription; description.SecurityMode = policy.SecurityMode; description.SecurityPolicyUri = policy.SecurityPolicyUri; description.SecurityLevel = ServerSecurityPolicy.CalculateSecurityLevel(policy.SecurityMode, policy.SecurityPolicyUri); description.UserIdentityTokens = serverBase.GetUserTokenPolicies(configuration, description); description.TransportProfileUri = Profiles.UaTcpTransport; bool requireEncryption = ServerBase.RequireEncryption(description); if (requireEncryption) { description.ServerCertificate = instanceCertificate.RawData; // check if complete chain should be sent. if (configuration.SecurityConfiguration.SendCertificateChain && instanceCertificateChain != null && instanceCertificateChain.Count > 0) { List <byte> serverCertificateChain = new List <byte>(); for (int i = 0; i < instanceCertificateChain.Count; i++) { serverCertificateChain.AddRange(instanceCertificateChain[i].RawData); } description.ServerCertificate = serverCertificateChain.ToArray(); } } listenerEndpoints.Add(description); } serverBase.CreateServiceHostEndpoint(uri.Uri, listenerEndpoints, endpointConfiguration, listener, configuration.CertificateValidator.GetChannelValidator() ); endpoints.AddRange(listenerEndpoints); } else { Utils.Trace(Utils.TraceMasks.Error, "Failed to create endpoint {0} because the transport profile is unsupported.", uri); } } hosts[hostName] = serverBase.CreateServiceHost(serverBase, uris.ToArray()); return(endpoints); }
/// <summary> /// Constructs the binding from the endpoint description. /// </summary> /// <param name="endpoint"></param> /// <returns></returns> private static Binding CreateSessionBinding(EndpointDescription endpoint) { // Parse the url provided. Uri url = new Uri(endpoint.EndpointUrl); // Construct the binding based on the URL scheme. // The available bindings are specified in the app.config file. // Applications cannot communicate unless the binding configuration matches. // UA specifies standard binding configurations to ensure interoperability. // The bindings used in the sample app.config file are the standard UA bindings. Binding binding = null; switch (url.Scheme) { case "http": { binding = new BasicHttpBinding("UaBasicSoapXmlBinding_ISessionEndpoint"); break; } case "net.tcp": { binding = new NetTcpBinding("UaSoapXmlOverTcpBinding_IDiscoveryEndpoint"); break; } case "net.pipe": { binding = new NetNamedPipeBinding("UaSoapXmlOverPipeBinding_IDiscoveryEndpoint"); break; } /* case "http": { binding = new CustomBinding("UaSoapXmlBinding_ISessionEndpoint"); break; } case "net.tcp": { binding = new CustomBinding("UaSoapXmlOverTcpBinding_ISessionEndpoint"); break; } case "net.pipe": { binding = new CustomBinding("UaSoapXmlOverPipeBinding_ISessionEndpoint"); break; } */ } // TBD - Modify the binding to match the SecuirtyMode and the SecurityPolicyUri // specified in the EndpointDescription. SignAndEncrypt/Basic256Rsa15 is the default. return binding; }
/// <summary> /// Select the best supported endpoint from an /// EndpointDescriptionCollection, with or without security. /// </summary> /// <param name="url"></param> /// <param name="endpoints"></param> /// <param name="useSecurity"></param> public static EndpointDescription SelectEndpoint( Uri url, EndpointDescriptionCollection endpoints, bool useSecurity) { EndpointDescription selectedEndpoint = null; // select the best endpoint to use based on the selected URL and the UseSecurity checkbox. for (int ii = 0; ii < endpoints.Count; ii++) { EndpointDescription endpoint = endpoints[ii]; // check for a match on the URL scheme. if (endpoint.EndpointUrl.StartsWith(url.Scheme)) { // check if security was requested. if (useSecurity) { if (endpoint.SecurityMode == MessageSecurityMode.None) { continue; } // skip unsupported security policies if (SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri) == null) { continue; } } else { if (endpoint.SecurityMode != MessageSecurityMode.None) { continue; } } // pick the first available endpoint by default. if (selectedEndpoint == null) { selectedEndpoint = endpoint; } // The security level is a relative measure assigned by the server to the // endpoints that it returns. Clients should always pick the highest level // unless they have a reason not too. if (endpoint.SecurityLevel > selectedEndpoint.SecurityLevel) { selectedEndpoint = endpoint; } } } // pick the first available endpoint by default. if (selectedEndpoint == null && endpoints.Count > 0) { selectedEndpoint = endpoints[0]; } // return the selected endpoint. return(selectedEndpoint); }
/// <summary> /// Updates the list of servers displayed in the control. /// </summary> private void OnUpdateEndpoints(object state) { if (this.InvokeRequired) { this.BeginInvoke(new WaitCallback(OnUpdateEndpoints), state); return; } try { // get the updated descriptions. EndpointDescriptionCollection endpoints = state as EndpointDescriptionCollection; if (endpoints == null) { m_showAllOptions = true; InitializeProtocols(m_availableEndpoints); } else { m_showAllOptions = false; m_availableEndpoints = endpoints; BuildEndpointDescriptionStrings(m_availableEndpoints); if (endpoints.Count > 0) { m_currentDescription = endpoints[0]; } // initializing the protocol will trigger an update to all other controls. InitializeProtocols(m_availableEndpoints); // select the best security mode. MessageSecurityMode bestMode = MessageSecurityMode.Invalid; foreach (MessageSecurityMode securityMode in SecurityModeCB.Items) { if (securityMode > bestMode) { bestMode = securityMode; } } SecurityModeCB.SelectedItem = bestMode; // select the best encoding. Encoding bestEncoding = Encoding.Default; foreach (Encoding encoding in EncodingCB.Items) { if (encoding > bestEncoding) { bestEncoding = encoding; } } EncodingCB.SelectedItem = bestEncoding; } if (m_endpoint != null) { Uri url = m_endpoint.EndpointUrl; foreach (Protocol protocol in ProtocolCB.Items) { if (protocol.Matches(url)) { ProtocolCB.SelectedItem = protocol; break; } } foreach (MessageSecurityMode securityMode in SecurityModeCB.Items) { if (securityMode == m_endpoint.Description.SecurityMode) { SecurityModeCB.SelectedItem = securityMode; break; } } foreach (string securityPolicy in SecurityPolicyCB.Items) { if (securityPolicy == m_endpoint.Description.SecurityPolicyUri) { SecurityPolicyCB.SelectedItem = securityPolicy; break; } } foreach (Encoding encoding in EncodingCB.Items) { if (encoding == Encoding.Binary && m_endpoint.Configuration.UseBinaryEncoding) { EncodingCB.SelectedItem = encoding; break; } if (encoding == Encoding.Xml && !m_endpoint.Configuration.UseBinaryEncoding) { EncodingCB.SelectedItem = encoding; break; } } } } catch (Exception e) { Utils.Trace(e, "Unexpected error updating endpoints."); } }
/// <summary> /// Called when a secure channel is created by the client. /// </summary> /// <param name="implementationInfo">Information about the secure channel implementation.</param> /// <param name="endpointUrl">The identifier assigned to the secure channel</param> /// <param name="secureChannelId">The identifier assigned to the secure channel</param> /// <param name="endpoint">The endpoint.</param> /// <param name="clientCertificate">The client certificate.</param> /// <param name="serverCertificate">The server certificate.</param> /// <param name="encodingSupport">The type of encoding supported by the channel.</param> public static void SecureChannelCreated( string implementationInfo, string endpointUrl, string secureChannelId, EndpointDescription endpoint, X509Certificate2 clientCertificate, X509Certificate2 serverCertificate, BinaryEncodingSupport encodingSupport) { // do nothing if security turned off. if ((Utils.TraceMask & Utils.TraceMasks.Security) == 0) { return; } StringBuilder buffer = new StringBuilder(); buffer.Append("SECURE CHANNEL CREATED"); buffer.Append(" ["); buffer.Append(implementationInfo); buffer.Append("]"); buffer.Append(" [ID="); buffer.Append(secureChannelId); buffer.Append("]"); buffer.Append(" Connected To: "); buffer.Append(endpointUrl); if (endpoint != null) { buffer.Append(" ["); buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", endpoint.SecurityMode); buffer.Append("/"); buffer.Append(SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri)); buffer.Append("/"); if (encodingSupport == BinaryEncodingSupport.Required) { buffer.Append("Binary"); } else if (encodingSupport == BinaryEncodingSupport.None) { buffer.Append("Xml"); } else { buffer.Append("BinaryOrXml"); } buffer.Append("]"); if (endpoint.SecurityMode != MessageSecurityMode.None) { if (clientCertificate != null) { buffer.Append(" Client Certificate: ["); buffer.Append(clientCertificate.Subject); buffer.Append("] ["); buffer.Append(clientCertificate.Thumbprint); buffer.Append("]"); } if (serverCertificate != null) { buffer.Append(" Server Certificate: ["); buffer.Append(serverCertificate.Subject); buffer.Append("] ["); buffer.Append(serverCertificate.Thumbprint); buffer.Append("]"); } } } Utils.Trace(Utils.TraceMasks.Security, buffer.ToString()); }
public EndpointDescriptionString(EndpointDescription endpointDescription) { m_endpointDescription = endpointDescription; m_protocol = new Protocol(endpointDescription); m_currentPolicy = SecurityPolicies.GetDisplayName(endpointDescription.SecurityPolicyUri); m_messageSecurityMode = endpointDescription.SecurityMode; switch (m_endpointDescription.EncodingSupport) { case BinaryEncodingSupport.None: { m_encoding = Encoding.Xml; break; } case BinaryEncodingSupport.Optional: case BinaryEncodingSupport.Required: { m_encoding = Encoding.Binary; break; } } BuildEndpointDescription(); }
/// <summary> /// Initializes a new instance of the <see cref="UaTcpSecureChannel"/> class. /// </summary> /// <param name="localDescription">The local description.</param> /// <param name="localCertificate">The local certificate</param> /// <param name="remoteEndpoint">The remote endpoint</param> public UaTcpSecureChannel(ApplicationDescription localDescription, X509Certificate2 localCertificate, EndpointDescription remoteEndpoint) : base(remoteEndpoint) { if (localDescription == null) { throw new ArgumentNullException(nameof(localDescription)); } this.LocalDescription = localDescription; this.LocalCertificate = localCertificate; this.TimeoutHint = DefaultTimeoutHint; this.DiagnosticsHint = DefaultDiagnosticsHint; this.AuthenticationToken = null; this.NamespaceUris = new List<string> { "http://opcfoundation.org/UA/" }; this.ServerUris = new List<string>(); this.channelCts = new CancellationTokenSource(); this.cancelRequest = new Action<object>(this.CancelRequest); this.pendingRequests = new BufferBlock<TaskCompletionSource<IServiceResponse>>(); this.pendingCompletions = new ConcurrentDictionary<uint, TaskCompletionSource<IServiceResponse>>(); this.sendingSemaphore = new SemaphoreSlim(1, 1); this.receivingSemaphore = new SemaphoreSlim(1, 1); this.tokenRenewalTime = DateTime.MaxValue; }
/// <summary> /// Displays the dialog. /// </summary> public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationConfiguration configuration) { if (server == null) throw new ArgumentNullException("server"); m_configuration = configuration; // construct a list of available endpoint descriptions for the application. m_availableEndpoints = new EndpointDescriptionCollection(); m_availableEndpointsDescriptions = new List<EndpointDescriptionString>(); m_endpointConfiguration = EndpointConfiguration.Create(configuration); // create a default endpoint description. m_endpoint = null; m_currentDescription = null; // initializing the protocol will trigger an update to all other controls. InitializeProtocols(m_availableEndpoints); BuildEndpointDescriptionStrings(m_availableEndpoints); // discover endpoints in the background. m_discoverySucceeded = false; Interlocked.Increment(ref m_discoverCount); ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), server); if (ShowDialog() != DialogResult.OK) { return null; } return m_endpoint; }
/// <summary> /// Displays the dialog. /// </summary> public ConfiguredEndpoint ShowDialog(ConfiguredEndpoint endpoint, ApplicationConfiguration configuration) { if (endpoint == null) throw new ArgumentNullException("endpoint"); m_endpoint = endpoint; m_configuration = configuration; // construct a list of available endpoint descriptions for the application. m_availableEndpoints = new EndpointDescriptionCollection(); m_availableEndpointsDescriptions = new List<EndpointDescriptionString>(); m_availableEndpoints.Add(endpoint.Description); m_currentDescription = endpoint.Description; m_endpointConfiguration = endpoint.Configuration; if (m_endpointConfiguration == null) { m_endpointConfiguration = EndpointConfiguration.Create(configuration); } if (endpoint.Collection != null) { foreach (ConfiguredEndpoint existingEndpoint in endpoint.Collection.Endpoints) { if (existingEndpoint.Description.Server.ApplicationUri == endpoint.Description.Server.ApplicationUri) { m_availableEndpoints.Add(existingEndpoint.Description); } } } BuildEndpointDescriptionStrings(m_availableEndpoints); UserTokenPolicy policy = m_endpoint.SelectedUserTokenPolicy; if (policy == null) { if (m_endpoint.Description.UserIdentityTokens.Count > 0) { policy = m_endpoint.Description.UserIdentityTokens[0]; } } if (policy != null) { UserTokenItem userTokenItem = new UserTokenItem(policy); if (policy.TokenType == UserTokenType.UserName && m_endpoint.UserIdentity is UserNameIdentityToken) { m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity; } if (policy.TokenType == UserTokenType.Certificate && m_endpoint.UserIdentity is X509IdentityToken) { m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity; } if (policy.TokenType == UserTokenType.IssuedToken && m_endpoint.UserIdentity is IssuedIdentityToken) { m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity; } } // copy com identity. m_comIdentity = endpoint.ComIdentity; // initializing the protocol will trigger an update to all other controls. InitializeProtocols(m_availableEndpoints); // check if the current settings match the defaults. EndpointConfiguration defaultConfiguration = EndpointConfiguration.Create(configuration); // discover endpoints in the background. Interlocked.Increment(ref m_discoverCount); ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), m_endpoint.Description.Server); if (ShowDialog() != DialogResult.OK) { return null; } return m_endpoint; }
public Protocol(EndpointDescription url) { Url = null; if (url != null) { Url = Utils.ParseUri(url.EndpointUrl); if ((Url != null) && (Url.Scheme == Utils.UriSchemeHttp)) { switch (url.TransportProfileUri) { case Profiles.HttpsXmlTransport: case Profiles.HttpsBinaryTransport: case Profiles.HttpsXmlOrBinaryTransport: { Profile = "REST"; break; } case Profiles.WsHttpXmlTransport: case Profiles.WsHttpXmlOrBinaryTransport: { Profile = "WS-*"; break; } } } } }
/// <summary> /// Handles requests arriving from a channel. /// </summary> public async Task SendAsync(HttpContext context) { IAsyncResult result = null; try { if (m_callback == null) { context.Response.ContentLength = 0; context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.NotImplemented; await context.Response.WriteAsync(string.Empty).ConfigureAwait(false); return; } if (context.Request.ContentType != "application/octet-stream") { context.Response.ContentLength = 0; context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.BadRequest; await context.Response.WriteAsync("HTTPSLISTENER - Unsupported content type.").ConfigureAwait(false); return; } int length = (int)context.Request.ContentLength; byte[] buffer = await ReadBodyAsync(context.Request).ConfigureAwait(false); if (buffer.Length != length) { context.Response.ContentLength = 0; context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.BadRequest; await context.Response.WriteAsync("HTTPSLISTENER - Couldn't decode buffer.").ConfigureAwait(false); return; } IServiceRequest input = (IServiceRequest)BinaryDecoder.DecodeMessage(buffer, null, m_quotas.MessageContext); // extract the JWT token from the HTTP headers. if (input.RequestHeader == null) { input.RequestHeader = new RequestHeader(); } if (NodeId.IsNull(input.RequestHeader.AuthenticationToken) && input.TypeId != DataTypeIds.CreateSessionRequest) { if (context.Request.Headers.ContainsKey("Authorization")) { foreach (string value in context.Request.Headers["Authorization"]) { if (value.StartsWith("Bearer", StringComparison.OrdinalIgnoreCase)) { // note: use NodeId(string, uint) to avoid the NodeId.Parse call. input.RequestHeader.AuthenticationToken = new NodeId(value.Substring("Bearer ".Length).Trim(), 0); } } } } if (!context.Request.Headers.TryGetValue("OPCUA-SecurityPolicy", out var header)) { header = SecurityPolicies.None; } EndpointDescription endpoint = null; foreach (var ep in m_descriptions) { if (ep.EndpointUrl.StartsWith(Utils.UriSchemeHttps, StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(header)) { if (!string.Equals(ep.SecurityPolicyUri, header, StringComparison.Ordinal)) { continue; } } endpoint = ep; break; } } if (endpoint == null && input.TypeId != DataTypeIds.GetEndpointsRequest && input.TypeId != DataTypeIds.FindServersRequest) { var message = "Connection refused, invalid security policy."; Utils.LogError(message); context.Response.ContentLength = message.Length; context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await context.Response.WriteAsync(message).ConfigureAwait(false); } result = m_callback.BeginProcessRequest( m_listenerId, endpoint, input as IServiceRequest, null, null); IServiceResponse output = m_callback.EndProcessRequest(result); byte[] response = BinaryEncoder.EncodeMessage(output, m_quotas.MessageContext); context.Response.ContentLength = response.Length; context.Response.ContentType = context.Request.ContentType; context.Response.StatusCode = (int)HttpStatusCode.OK; #if NETSTANDARD2_1 || NET5_0_OR_GREATER || NETCOREAPP3_1_OR_GREATER await context.Response.Body.WriteAsync(response.AsMemory(0, response.Length)).ConfigureAwait(false); #else await context.Response.Body.WriteAsync(response, 0, response.Length).ConfigureAwait(false); #endif } catch (Exception e) { Utils.LogError(e, "HTTPSLISTENER - Unexpected error processing request."); context.Response.ContentLength = e.Message.Length; context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; await context.Response.WriteAsync(e.Message).ConfigureAwait(false); } }
/// <summary> /// Initializes the message encodings dropdown. /// </summary> private void InitializeEncodings(EndpointDescriptionCollection endpoints, EndpointDescription endpoint) { // preserve the existing value. Encoding currentEncoding = Encoding.Default; if (EncodingCB.SelectedIndex != -1) { currentEncoding = (Encoding)EncodingCB.SelectedItem; } EncodingCB.Items.Clear(); if (endpoint != null) { Protocol protocol = new Protocol(endpoint); String securityPolicy = SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri); foreach (EndpointDescription endpointDescription in endpoints) { if ((protocol.Matches(Utils.ParseUri(endpointDescription.EndpointUrl))) && (endpoint.SecurityMode == endpointDescription.SecurityMode) && (securityPolicy == SecurityPolicies.GetDisplayName(endpointDescription.SecurityPolicyUri))) { switch (endpointDescription.EncodingSupport) { case BinaryEncodingSupport.None: { if (!EncodingCB.Items.Contains(Encoding.Xml)) { EncodingCB.Items.Add(Encoding.Xml); } break; } case BinaryEncodingSupport.Required: { if (!EncodingCB.Items.Contains(Encoding.Binary)) { EncodingCB.Items.Add(Encoding.Binary); } break; } case BinaryEncodingSupport.Optional: { if (!EncodingCB.Items.Contains(Encoding.Binary)) { EncodingCB.Items.Add(Encoding.Binary); } if (!EncodingCB.Items.Contains(Encoding.Xml)) { EncodingCB.Items.Add(Encoding.Xml); } break; } } } } } // add at least one encoding. if (EncodingCB.Items.Count == 0) { EncodingCB.Items.Add(Encoding.Default); } // set the current value. int index = EncodingCB.Items.IndexOf(currentEncoding); if (index == -1) { index = 0; } EncodingCB.SelectedIndex = index; }
/// <summary> /// Checks if there is an active OPC UA session for the provided browser session. If the persisted OPC UA session does not exist, /// a new OPC UA session to the given endpoint URL is established. /// </summary> public async Task <Session> GetSessionAsync(ApplicationConfiguration config, string sessionID, string endpointURL, bool enforceTrust = false) { if (string.IsNullOrEmpty(sessionID) || string.IsNullOrEmpty(endpointURL)) { return(null); } OpcSessionCacheData entry; if (OpcSessionCache.TryGetValue(sessionID, out entry)) { if (entry.OPCSession != null) { if (entry.OPCSession.Connected) { return(entry.OPCSession); } try { entry.OPCSession.Close(500); } catch (Exception) { // do nothing } entry.OPCSession = null; } } else { // create a new entry OpcSessionCacheData newEntry = new OpcSessionCacheData { EndpointURL = new Uri(endpointURL) }; OpcSessionCache.TryAdd(sessionID, newEntry); } Uri endpointURI = new Uri(endpointURL); EndpointDescriptionCollection endpointCollection = DiscoverEndpoints(config, endpointURI, 10); EndpointDescription selectedEndpoint = SelectUaTcpEndpoint(endpointCollection); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(config); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); Session session = null; try { // lock the session creation for the enforced trust case await _trustedSessionCertificateValidation.WaitAsync().ConfigureAwait(false); if (enforceTrust) { // enforce trust in the certificate validator by setting the trusted session id _trustedSessionId = sessionID; } session = await Session.Create( config, endpoint, true, false, sessionID, 60000, new UserIdentity(new AnonymousIdentityToken()), null).ConfigureAwait(false); if (session != null) { session.KeepAlive += new KeepAliveEventHandler(StandardClient_KeepAlive); // Update our cache data if (OpcSessionCache.TryGetValue(sessionID, out entry)) { if (string.Equals(entry.EndpointURL.AbsoluteUri, endpointURL, StringComparison.InvariantCultureIgnoreCase)) { OpcSessionCacheData newValue = new OpcSessionCacheData { CertThumbprint = entry.CertThumbprint, EndpointURL = entry.EndpointURL, Trusted = entry.Trusted, OPCSession = session }; OpcSessionCache.TryUpdate(sessionID, newValue, entry); } } } } finally { _trustedSessionId = null; _trustedSessionCertificateValidation.Release(); } return(session); }
private Data GetRequest(BehaviorChain chain, EndpointDescription endpoint) { var firstCall = chain.FirstCall(); DataType type = null; List<BodyLineItem> description = null; if (firstCall.HasInput && !chain.Route.AllowsGet() && !chain.Route.AllowsDelete()) { type = _typeGraphFactory.BuildGraph(firstCall.InputType(), chain.FirstCall()); description = _bodyDescriptionFactory.Create(type); } return _configuration.RequestOverrides.Apply(chain, new Data { Comments = endpoint.RequestComments, Headers = GetHeaders(chain, HttpDirection.Request), MimeTypes = GetMimeTypes(chain, HttpDirection.Request), Body = new Body { Type = type, Description = description } }); }
/// <summary> /// Creates the endpoint description from current selections. /// </summary> private EndpointDescription CreateDescriptionFromSelections() { Protocol currentProtocol = (Protocol)ProtocolCB.SelectedItem; EndpointDescription endpoint = null; for (int ii = 0; ii < m_availableEndpoints.Count; ii++) { Uri url = Utils.ParseUri(m_availableEndpoints[ii].EndpointUrl); if (url == null) { continue; } if (endpoint == null) { endpoint = m_availableEndpoints[ii]; } if (currentProtocol.Matches(url)) { endpoint = m_availableEndpoints[ii]; break; } } UriBuilder builder = null; string scheme = Utils.UriSchemeOpcTcp; if (currentProtocol != null && currentProtocol.Url != null) { scheme = currentProtocol.Url.Scheme; } if (endpoint == null) { builder = new UriBuilder(); builder.Host = "localhost"; if (scheme == Utils.UriSchemeOpcTcp) { builder.Port = Utils.UaTcpDefaultPort; } } else { builder = new UriBuilder(endpoint.EndpointUrl); } builder.Scheme = scheme; endpoint = new EndpointDescription(); endpoint.EndpointUrl = builder.ToString(); endpoint.SecurityMode = (MessageSecurityMode)SecurityModeCB.SelectedItem; endpoint.SecurityPolicyUri = SecurityPolicies.GetUri((string)SecurityPolicyCB.SelectedItem); endpoint.Server.ApplicationName = endpoint.EndpointUrl; endpoint.Server.ApplicationType = ApplicationType.Server; endpoint.Server.ApplicationUri = endpoint.EndpointUrl; return endpoint; }
private void EditBTN_Click(object sender, EventArgs e) { try { Uri uri = null; ConfiguredEndpoint endpoint = null; if (m_endpoint == null) { string url = EndpointTB.Text; if (String.IsNullOrEmpty(url)) { DiscoverBTN_Click(sender, e); return; } uri = new Uri(url); EndpointDescription description = new EndpointDescription(uri.ToString()); endpoint = new ConfiguredEndpoint(null, description, EndpointConfiguration.Create(m_configuration)); } else { uri = m_endpoint.EndpointUrl; endpoint = m_endpoint; } ConfigureEndpoint(endpoint); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
public override IList <EndpointDescription> GetEndpointDescriptions(string endpointUrlHint) { var certStr = ApplicationCertificate.Export(X509ContentType.Cert); var epNoSecurity = new EndpointDescription( endpointUrlHint, uaAppDesc, null, MessageSecurityMode.None, Types.SLSecurityPolicyUris[(int)SecurityPolicy.None], new UserTokenPolicy[] { new UserTokenPolicy("0", UserTokenType.Anonymous, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.None]), }, Types.TransportProfileBinary, 0); var epSignBasic128Rsa15 = new EndpointDescription( endpointUrlHint, uaAppDesc, certStr, MessageSecurityMode.Sign, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic128Rsa15], new UserTokenPolicy[] { new UserTokenPolicy("0", UserTokenType.Anonymous, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic128Rsa15]), new UserTokenPolicy("1", UserTokenType.UserName, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic128Rsa15]), }, Types.TransportProfileBinary, 0); var epSignBasic256 = new EndpointDescription( endpointUrlHint, uaAppDesc, certStr, MessageSecurityMode.Sign, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256], new UserTokenPolicy[] { new UserTokenPolicy("0", UserTokenType.Anonymous, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256]), new UserTokenPolicy("1", UserTokenType.UserName, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256]), }, Types.TransportProfileBinary, 0); var epSignBasic256Sha256 = new EndpointDescription( endpointUrlHint, uaAppDesc, certStr, MessageSecurityMode.Sign, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256Sha256], new UserTokenPolicy[] { new UserTokenPolicy("0", UserTokenType.Anonymous, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256Sha256]), new UserTokenPolicy("1", UserTokenType.UserName, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256Sha256]), }, Types.TransportProfileBinary, 0); var epSignEncryptBasic128Rsa15 = new EndpointDescription( endpointUrlHint, uaAppDesc, certStr, MessageSecurityMode.SignAndEncrypt, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic128Rsa15], new UserTokenPolicy[] { new UserTokenPolicy("0", UserTokenType.Anonymous, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic128Rsa15]), new UserTokenPolicy("1", UserTokenType.UserName, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic128Rsa15]), }, Types.TransportProfileBinary, 0); var epSignEncryptBasic256 = new EndpointDescription( endpointUrlHint, uaAppDesc, certStr, MessageSecurityMode.SignAndEncrypt, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256], new UserTokenPolicy[] { new UserTokenPolicy("0", UserTokenType.Anonymous, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256]), new UserTokenPolicy("1", UserTokenType.UserName, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256]), }, Types.TransportProfileBinary, 0); var epSignEncryptBasic256Sha256 = new EndpointDescription( endpointUrlHint, uaAppDesc, certStr, MessageSecurityMode.SignAndEncrypt, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256Sha256], new UserTokenPolicy[] { new UserTokenPolicy("0", UserTokenType.Anonymous, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256Sha256]), new UserTokenPolicy("1", UserTokenType.UserName, null, null, Types.SLSecurityPolicyUris[(int)SecurityPolicy.Basic256Sha256]), }, Types.TransportProfileBinary, 0); return(new EndpointDescription[] { epNoSecurity, epSignBasic256Sha256, epSignEncryptBasic256Sha256, epSignBasic128Rsa15, epSignEncryptBasic128Rsa15, epSignBasic256, epSignEncryptBasic256 }); }
private void OkBTN_Click(object sender, EventArgs e) { try { // check that discover has completed. if (!m_discoverySucceeded) { DialogResult result = MessageBox.Show( "Endpoint information may be out of date because the discovery process has not completed. Continue anyways?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result != DialogResult.Yes) { return; } } EndpointConfiguration configuration = m_endpointConfiguration; if (configuration == null) { configuration = EndpointConfiguration.Create(m_configuration); } if (m_currentDescription == null) { m_currentDescription = CreateDescriptionFromSelections(); } // the discovery endpoint should always be on the same machine as the server. // if there is a mismatch it is likely because the server has multiple addresses // and was not configured to return the current address to the client. // The code automatically updates the domain in the url. Uri endpointUrl = Utils.ParseUri(m_currentDescription.EndpointUrl); if (m_discoverySucceeded) { if (!Utils.AreDomainsEqual(endpointUrl, m_discoveryUrl)) { UriBuilder url = new UriBuilder(endpointUrl); url.Host = m_discoveryUrl.DnsSafeHost; if (url.Scheme == m_discoveryUrl.Scheme) { url.Port = m_discoveryUrl.Port; } endpointUrl = url.Uri; m_currentDescription.EndpointUrl = endpointUrl.ToString(); } } // set the encoding. Encoding encoding = (Encoding)EncodingCB.SelectedItem; configuration.UseBinaryEncoding = encoding != Encoding.Xml; if (m_endpoint == null) { m_endpoint = new ConfiguredEndpoint(null, m_currentDescription, configuration); } else { m_endpoint.Update(m_currentDescription); m_endpoint.Update(configuration); } DialogResult = DialogResult.OK; } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
private void ProtocolCB_SelectedIndexChanged(object sender, EventArgs e) { try { InitializeSecurityModes(m_availableEndpoints); if (!m_updating) { try { m_updating = true; // update current description. m_currentDescription = FindBestEndpointDescription(m_availableEndpoints); InitializeEncodings(m_availableEndpoints, m_currentDescription); SelectCorrespondingEndpointFromList(m_currentDescription); } finally { m_updating = false; } } if (ProtocolCB.SelectedItem != null) { if (((Protocol)ProtocolCB.SelectedItem).Url.DnsSafeHost != m_endpoint.EndpointUrl.DnsSafeHost) { m_statusObject.SetStatus(StatusChannel.SelectedProtocol, "Warning: Selected Endpoint hostname is different than initial hostname.", StatusType.Warning); } else { m_statusObject.ClearStatus(StatusChannel.SelectedProtocol); } } else { m_statusObject.SetStatus(StatusChannel.SelectedProtocol, "Error: Selected Protocol is invalid.", StatusType.Warning); } UpdateStatus(); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <inheritdoc/> /// <summary> /// Create a new service host for UA HTTPS. /// </summary> public List <EndpointDescription> CreateServiceHost( ServerBase serverBase, IDictionary <string, Task> hosts, ApplicationConfiguration configuration, IList <string> baseAddresses, ApplicationDescription serverDescription, List <ServerSecurityPolicy> securityPolicies, X509Certificate2 instanceCertificate, X509Certificate2Collection instanceCertificateChain ) { // generate a unique host name. string hostName = String.Empty; if (hosts.ContainsKey(hostName)) { hostName = "/Https"; } if (hosts.ContainsKey(hostName)) { hostName += Utils.Format("/{0}", hosts.Count); } // build list of uris. List <Uri> uris = new List <Uri>(); EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection(); // create the endpoint configuration to use. EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); string computerName = Utils.GetHostName(); for (int ii = 0; ii < baseAddresses.Count; ii++) { if (!baseAddresses[ii].StartsWith(Utils.UriSchemeHttps, StringComparison.Ordinal)) { continue; } UriBuilder uri = new UriBuilder(baseAddresses[ii]); if (uri.Path[uri.Path.Length - 1] != '/') { uri.Path += "/"; } if (String.Compare(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0) { uri.Host = computerName; } uris.Add(uri.Uri); if (uri.Scheme == Utils.UriSchemeHttps) { // Can only support one policy with HTTPS // So pick the first policy with security mode sign and encrypt ServerSecurityPolicy bestPolicy = null; foreach (ServerSecurityPolicy policy in securityPolicies) { if (policy.SecurityMode != MessageSecurityMode.SignAndEncrypt) { continue; } bestPolicy = policy; break; } // Pick the first policy from the list if no policies with sign and encrypt defined if (bestPolicy == null) { bestPolicy = securityPolicies[0]; } EndpointDescription description = new EndpointDescription(); description.EndpointUrl = uri.ToString(); description.Server = serverDescription; if (instanceCertificate != null) { description.ServerCertificate = instanceCertificate.RawData; // check if complete chain should be sent. if (configuration.SecurityConfiguration.SendCertificateChain && instanceCertificateChain != null && instanceCertificateChain.Count > 0) { List <byte> serverCertificateChain = new List <byte>(); for (int i = 0; i < instanceCertificateChain.Count; i++) { serverCertificateChain.AddRange(instanceCertificateChain[i].RawData); } description.ServerCertificate = serverCertificateChain.ToArray(); } } description.SecurityMode = bestPolicy.SecurityMode; description.SecurityPolicyUri = bestPolicy.SecurityPolicyUri; description.SecurityLevel = ServerSecurityPolicy.CalculateSecurityLevel(bestPolicy.SecurityMode, bestPolicy.SecurityPolicyUri); description.UserIdentityTokens = serverBase.GetUserTokenPolicies(configuration, description); description.TransportProfileUri = Profiles.HttpsBinaryTransport; ITransportListener listener = Create(); if (listener != null) { endpoints.Add(description); serverBase.CreateServiceHostEndpoint(uri.Uri, endpoints, endpointConfiguration, listener, configuration.CertificateValidator.GetChannelValidator()); } else { Utils.Trace(Utils.TraceMasks.Error, "Failed to create endpoint {0} because the transport profile is unsupported.", uri); } } } return(endpoints); }
private void SecurityModeCB_SelectedIndexChanged(object sender, EventArgs e) { try { InitializeSecurityPolicies(m_availableEndpoints); if (!m_updating) { try { m_updating = true; // update current description. m_currentDescription = FindBestEndpointDescription(m_availableEndpoints); InitializeEncodings(m_availableEndpoints, m_currentDescription); SelectCorrespondingEndpointFromList(m_currentDescription); } finally { m_updating = false; } } if (SecurityModeCB.SelectedItem != null) { if ((((MessageSecurityMode)SecurityModeCB.SelectedItem) == MessageSecurityMode.None) && (ProtocolCB.SelectedItem != null) && (((Protocol)ProtocolCB.SelectedItem).ToString().IndexOf("https") != 0)) { m_statusObject.SetStatus(StatusChannel.SelectedSecurityMode, "Warning: Selected Endpoint has no security.", StatusType.Warning); } else if (((MessageSecurityMode)SecurityModeCB.SelectedItem) == MessageSecurityMode.Invalid) { m_statusObject.SetStatus(StatusChannel.SelectedSecurityMode, "Error: Selected Endpoint Security Mode is unsupported.", StatusType.Warning); } else { m_statusObject.ClearStatus(StatusChannel.SelectedSecurityMode); } } else { m_statusObject.SetStatus(StatusChannel.SelectedSecurityMode, "Error: Selected Endpoint Security Mode is invalid.", StatusType.Warning); } UpdateStatus(); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Handles requests arriving from a channel. /// </summary> private IAsyncResult BeginProcessRequest(Stream istrm, string action, string securityPolicyUri, object callbackData) { IAsyncResult result = null; try { if (m_callback != null) { string contentType = WebOperationContext.Current.IncomingRequest.ContentType; Uri uri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri; string scheme = uri.Scheme + ":"; EndpointDescription endpoint = null; for (int ii = 0; ii < m_descriptions.Count; ii++) { if (m_descriptions[ii].EndpointUrl.StartsWith(scheme)) { if (endpoint == null) { endpoint = m_descriptions[ii]; } if (m_descriptions[ii].SecurityPolicyUri == securityPolicyUri) { endpoint = m_descriptions[ii]; break; } } } IEncodeable request = null; if (String.IsNullOrEmpty(action)) { request = BinaryDecoder.DecodeMessage(istrm, null, this.m_quotas.MessageContext); } else { string requestType = "Opc.Ua." + action + "Request"; request = HttpsTransportChannel.ReadSoapMessage( istrm, action + "Request", Type.GetType(requestType), this.m_quotas.MessageContext); } result = m_callback.BeginProcessRequest( m_listenerId, endpoint, request as IServiceRequest, null, callbackData); } } catch (Exception e) { Utils.Trace(e, "HTTPSLISTENER - Unexpected error processing request."); } return(result); }
private void SecurityPolicyCB_SelectedIndexChanged(object sender, EventArgs e) { try { if (!m_updating) { try { m_updating = true; // update current description. m_currentDescription = FindBestEndpointDescription(m_availableEndpoints); InitializeEncodings(m_availableEndpoints, m_currentDescription); SelectCorrespondingEndpointFromList(m_currentDescription); } finally { m_updating = false; } } if (SecurityPolicyCB.SelectedItem != null) { m_statusObject.ClearStatus(StatusChannel.SelectedSecurityPolicy); } else { m_statusObject.SetStatus(StatusChannel.SelectedSecurityPolicy, "Error: Selected Security Policy is invalid.", StatusType.Warning); } UpdateStatus(); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Handles requests arriving from a channel. /// </summary> public async void SendAsync(HttpContext context) { IAsyncResult result = null; try { if (m_callback == null) { context.Response.ContentLength = 0; context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.NotImplemented; await context.Response.WriteAsync(string.Empty); return; } byte[] buffer = new byte[(int)context.Request.ContentLength]; lock (m_lock) { Task <int> task = context.Request.Body.ReadAsync(buffer, 0, (int)context.Request.ContentLength); task.Wait(); } IServiceRequest input = (IServiceRequest)BinaryDecoder.DecodeMessage(buffer, null, m_quotas.MessageContext); // extract the JWT token from the HTTP headers. if (input.RequestHeader == null) { input.RequestHeader = new RequestHeader(); } if (NodeId.IsNull(input.RequestHeader.AuthenticationToken) && input.TypeId != DataTypeIds.CreateSessionRequest) { if (context.Request.Headers.Keys.Contains("Authorization")) { foreach (string value in context.Request.Headers["Authorization"]) { if (value.StartsWith("Bearer")) { input.RequestHeader.AuthenticationToken = new NodeId(value.Substring("Bearer ".Length).Trim()); } } } } EndpointDescription endpoint = null; foreach (var ep in m_descriptions) { if (ep.EndpointUrl.StartsWith(Utils.UriSchemeHttps)) { endpoint = ep; break; } } result = m_callback.BeginProcessRequest( m_listenerId, endpoint, input as IServiceRequest, null, null); IServiceResponse output = m_callback.EndProcessRequest(result); byte[] response = BinaryEncoder.EncodeMessage(output, m_quotas.MessageContext); context.Response.ContentLength = response.Length; context.Response.ContentType = context.Request.ContentType; context.Response.StatusCode = (int)HttpStatusCode.OK; await context.Response.Body.WriteAsync(response, 0, response.Length); } catch (Exception e) { Utils.Trace(e, "HTTPSLISTENER - Unexpected error processing request."); context.Response.ContentLength = e.Message.Length; context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; await context.Response.WriteAsync(e.Message); } }
private void EndpointListLB_SelectedIndexChanged(object sender, EventArgs e) { if (!m_updating) { try { m_updating = true; m_selecting = true; int selectedIndex = EndpointListLB.SelectedIndex; if (selectedIndex != -1) { EndpointDescriptionString selection = (EndpointDescriptionString)EndpointListLB.SelectedItem; int index = -1; for (int i = 0; i < ProtocolCB.Items.Count; ++i) { if (((Protocol)ProtocolCB.Items[i]).ToString() == selection.Protocol.ToString()) { index = i; break; } } ProtocolCB.SelectedIndex = index; InitializeSecurityModes(m_availableEndpoints); m_currentDescription = m_availableEndpoints[selectedIndex]; InitializeEncodings(m_availableEndpoints, m_currentDescription); index = -1; for (int i = 0; i < SecurityModeCB.Items.Count; ++i) { if ((MessageSecurityMode)SecurityModeCB.Items[i] == selection.MessageSecurityMode) { index = i; break; } } SecurityModeCB.SelectedIndex = index; index = -1; for (int i = 0; i < SecurityPolicyCB.Items.Count; ++i) { if ((string)SecurityPolicyCB.Items[i] == selection.CurrentPolicy) { index = i; break; } } SecurityPolicyCB.SelectedIndex = index; index = -1; for (int i = 0; i < EncodingCB.Items.Count; ++i) { if ((Encoding)EncodingCB.Items[i] == selection.Encoding) { index = i; break; } } EncodingCB.SelectedIndex = index; } } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } finally { m_updating = false; m_selecting = false; } } UpdateAdvancedEndpointInformation(); }