Example #1
0
 /// <summary>
 /// Match security mode to filter
 /// </summary>
 /// <param name="mode"></param>
 /// <param name="filter"></param>
 /// <returns></returns>
 public static bool MatchesFilter(this SecurityMode mode, SecurityMode filter)
 {
     if (mode == SecurityMode.Best)
     {
         mode = SecurityMode.SignAndEncrypt;
     }
     if (filter == SecurityMode.Best)
     {
         filter = SecurityMode.SignAndEncrypt;
     }
     if (filter == mode)
     {
         return(true);
     }
     if (filter == SecurityMode.Sign)
     {
         if (mode == SecurityMode.SignAndEncrypt)
         {
             return(true);
         }
     }
     if (filter == SecurityMode.None)
     {
         return(true);
     }
     return(false);
 }
Example #2
0
        public static int Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(HangmanService)))
            {
                var security = new SecurityMode();
                host.AddServiceEndpoint(
                    typeof(IHangmanService),
                    new WSHttpBinding(security, true),
                    "http://localhost:8325/");

                host.Open();

                /*
                 * Console.WriteLine ("Type [CR] to stop ...");
                 * Console.ReadKey ();
                 */

                /* Demon */
                UnixSignal    sigint  = new UnixSignal(Signum.SIGINT);
                UnixSignal    sigterm = new UnixSignal(Signum.SIGTERM);
                UnixSignal    sighup  = new UnixSignal(Signum.SIGHUP);
                UnixSignal    sigusr2 = new UnixSignal(Signum.SIGUSR2);
                UnixSignal [] signals = new UnixSignal[]
                {
                    sigint,
                    sigterm,
                    sighup,
                    sigusr2
                };

                bool exit = false;
                while (!exit)
                {
                    int id = UnixSignal.WaitAny(signals);

                    if (id >= 0 && id < signals.Length)
                    {
                        if (sigint.IsSet || sigterm.IsSet)
                        {
                            sigint.Reset();
                            sigterm.Reset();
                            exit = true;
                        }
                        else if (sighup.IsSet)
                        {
                            sighup.Reset();
                        }
                        else if (sigusr2.IsSet)
                        {
                            sighup.Reset();
                        }
                    }
                }
                /* Demon */

                host.Close();
            }

            return(0);
        }
Example #3
0
        internal WSHttpSecurity(SecurityMode mode, HttpTransportSecurity transportSecurity, NonDualMessageSecurityOverHttp messageSecurity)
        {
            _mode = mode;
            _transportSecurity = transportSecurity == null?GetDefaultHttpTransportSecurity() : transportSecurity;

            _messageSecurity = messageSecurity == null ? new NonDualMessageSecurityOverHttp() : messageSecurity;
        }
Example #4
0
        NetTcpSecurity(SecurityMode mode, TcpTransportSecurity transportSecurity)
        {
            Fx.Assert(SecurityModeHelper.IsDefined(mode), string.Format("Invalid SecurityMode value: {0}.", mode.ToString()));

            this.mode = mode;
            this.transportSecurity = transportSecurity == null ? new TcpTransportSecurity() : transportSecurity;
        }
        void FilterMexEndpointsAndAddOneInstance(string mexScheme)
        {
            Uri           serviceUri         = new Uri(mexScheme + "://tests:30003");
            ServiceHost   host               = new ServiceHost(typeof(MockServiceWithShielding), serviceUri);
            SecurityMode  securityMode       = SetMexAndSecurity(host, mexScheme);
            WSHttpBinding mockServiceBinding = new WSHttpBinding(securityMode);

            host.AddServiceEndpoint(typeof(IMockService), mockServiceBinding, serviceUri);
            try
            {
                host.Open();
            }
            catch (AddressAccessDeniedException ex)
            {
                Assert.Inconclusive("In order to run the tests, please run Visual Studio as Administrator.\r\n{0}", ex.ToString());
            }
            try
            {
                foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
                {
                    Assert.AreEqual(dispatcher.BindingName.Contains(mockServiceBinding.Name) ? 1 : 0, dispatcher.ErrorHandlers.Count);
                    Assert.IsFalse(dispatcher.IncludeExceptionDetailInFaults);
                }
            }
            finally
            {
                if (host.State == CommunicationState.Opened)
                {
                    host.Close();
                }
            }
        }
 public WS2007HttpBinding(SecurityMode securityMode, bool reliableSessionEnabled)
     : base(securityMode, reliableSessionEnabled)
 {
     this.ReliableSessionBindingElement.ReliableMessagingVersion = WS2007ReliableMessagingVersion;
     this.TransactionFlowBindingElement.TransactionProtocol = WS2007TransactionProtocol;
     this.HttpsTransport.MessageSecurityVersion = WS2007MessageSecurityVersion;
 }
Example #7
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="securityMode"></param>
 public CertificateWSTrustBinding(SecurityMode securityMode) : base(securityMode)
 {
     if (SecurityMode.Message == securityMode)
     {
         _clientCredentialType = HttpClientCredentialType.None;
     }
 }
Example #8
0
        private NetTcpSecurity(SecurityMode mode, TcpTransportSecurity transportSecurity)
        {
            Fx.Assert(SecurityModeHelper.IsDefined(mode), string.Format("Invalid SecurityMode value: {0}.", mode.ToString()));

            _mode     = mode;
            Transport = transportSecurity ?? new TcpTransportSecurity();
        }
Example #9
0
        internal WSHTTPSecurity(SecurityMode mode, HttpTransportSecurity transportSecurity, NonDualMessageSecurityOverHttp messageSecurity)
        {
            this.mode = mode;
            this.transportSecurity = transportSecurity == null?GetDefaultHttpTransportSecurity() : transportSecurity;

            this.messageSecurity = messageSecurity == null ? new NonDualMessageSecurityOverHttp() : messageSecurity;
        }
Example #10
0
        private static NetTcpBinding getBinding(PropertyString connectionProperties, out bool isWindowsCredential)
        {
            SecurityMode  securityMode = connectionProperties.GetEnum <SecurityMode>("SecurityMode", true);
            NetTcpBinding binding      = new NetTcpBinding(securityMode, false);

            binding.OpenTimeout            = connectionProperties.GetOptional("OpenTimeout", TimeSpan.FromSeconds(defaultTimeoutSeconds));
            binding.CloseTimeout           = connectionProperties.GetOptional("CloseTimeout", TimeSpan.FromSeconds(defaultTimeoutSeconds));
            binding.ReceiveTimeout         = connectionProperties.GetOptional("RecieveTimeout", TimeSpan.FromSeconds(defaultTimeoutSeconds));
            binding.SendTimeout            = connectionProperties.GetOptional("SendTimeout", TimeSpan.FromSeconds(defaultTimeoutSeconds));
            binding.MaxReceivedMessageSize = connectionProperties.GetOptional("MaxReceivedMessageSize", defaultMaxReceivedMessageSize);
            binding.MaxBufferSize          = connectionProperties.GetOptional("MaxBufferSize", defaultMaxBufferSize);
            binding.ReaderQuotas.MaxStringContentLength = connectionProperties.GetOptional("MaxStringContentLength", defaultMaxStringContentLength);
            binding.ReaderQuotas.MaxArrayLength         = connectionProperties.GetOptional("MaxArrayLength", defaultMaxArrayLength);
            binding.ReaderQuotas.MaxBytesPerRead        = connectionProperties.GetOptional("MaxBytesPerRead", defaultMaxBytesPerRead);
            switch (securityMode)
            {
            case SecurityMode.Message:
                binding.Security.Message.ClientCredentialType = connectionProperties.GetEnum <MessageCredentialType>("MessageCredentialType", false);
                isWindowsCredential = binding.Security.Message.ClientCredentialType == MessageCredentialType.Windows;
                break;

            case SecurityMode.Transport:
                binding.Security.Transport.ClientCredentialType = connectionProperties.GetEnum <TcpClientCredentialType>("ClientCredentialType", false);
                isWindowsCredential = binding.Security.Transport.ClientCredentialType == TcpClientCredentialType.Windows;
                break;

            default:
                isWindowsCredential = false;
                break;
            }
            return(binding);
        }
Example #11
0
        private void CheckSettings()
        {
#if FEATURE_NETNATIVE // In .NET Native, some settings for the binding security are not supported; this check is not necessary for CoreCLR
            NetTcpSecurity security = this.Security;
            if (security == null)
            {
                return;
            }

            SecurityMode mode = security.Mode;
            if (mode == SecurityMode.None)
            {
                return;
            }
            else if (mode == SecurityMode.Message)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode)));
            }

            // Message.ClientCredentialType = Certificate, IssuedToken or Windows are not supported.
            if (mode == SecurityMode.TransportWithMessageCredential)
            {
                MessageSecurityOverTcp message = security.Message;
                if (message != null)
                {
                    MessageCredentialType mct = message.ClientCredentialType;
                    if ((mct == MessageCredentialType.Certificate) || (mct == MessageCredentialType.IssuedToken) || (mct == MessageCredentialType.Windows))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Message.ClientCredentialType", mct)));
                    }
                }
            }
#endif // FEATURE_NETNATIVE
        }
Example #12
0
        public static string Sign(WebSecureToken token, SecurityMode mode, string secretKey)
        {
            byte[] bSecretKey = Encoding.ASCII.GetBytes(secretKey);
            string encoded    = string.Empty;

            switch (mode)
            {
            case SecurityMode.Sign:
                var tokenHandler = new JwtSecurityTokenHandler();

                var jwtoken = tokenHandler.CreateJwtSecurityToken(issuer: token.Issuer, audience: null,
                                                                  subject: new ClaimsIdentity(new[] {
                    new Claim(WebSecureToken.GXISSUER, token.Issuer),
                    new Claim(WebSecureToken.GXPROGRAM, token.ProgramName),
                    new Claim(WebSecureToken.GXVALUE, token.Value),
                    new Claim(WebSecureToken.GXEXPIRATION, token.Expiration.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString())
                }),
                                                                  notBefore: DateTime.UtcNow,
                                                                  expires: token.Expiration,
                                                                  signingCredentials: new SigningCredentials(new SymmetricSecurityKey(bSecretKey), SecurityAlgorithms.HmacSha256));

                return(tokenHandler.WriteToken(jwtoken));
            }
            return(encoded);
        }
 public IssuedTokenWSTrustBinding(Binding issuerBinding, EndpointAddress issuerAddress, SecurityMode mode, TrustVersion version, SecurityKeyType keyType, SecurityAlgorithmSuite algorithmSuite, string tokenType, IEnumerable<ClaimTypeRequirement> claimTypeRequirements, EndpointAddress issuerMetadataAddress)
     : base(mode, version)
 {
     this._claimTypeRequirements = new Collection<ClaimTypeRequirement>();
   
     if ((SecurityMode.Message != mode) && (SecurityMode.TransportWithMessageCredential != mode))
     {
         throw new InvalidOperationException("ID3226");
     }
     if ((this._keyType == SecurityKeyType.BearerKey) && (version == TrustVersion.WSTrustFeb2005))
     {
         throw new InvalidOperationException("ID3267");
     }
     
     this._keyType = keyType;
     this._algorithmSuite = algorithmSuite;
     this._tokenType = tokenType;
     this._issuerBinding = issuerBinding;
     this._issuerAddress = issuerAddress;
     this._issuerMetadataAddress = issuerMetadataAddress;
     
     if (claimTypeRequirements != null)
     {
         foreach (ClaimTypeRequirement requirement in claimTypeRequirements)
         {
             this._claimTypeRequirements.Add(requirement);
         }
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BusinessServicesClientConfigEntity"/> class.
 /// </summary>
 /// <param name="host">The host.</param>
 /// <param name="port">The port.</param>
 /// <param name="servicesName">Name of the services.</param>
 /// <param name="securityMode">The binding security mode.</param>
 public BusinessServicesClientConfigEntity(string host, int port, string servicesName, SecurityMode? securityMode)
 {
     _host = host;
     _port = port;
     _servicesName = servicesName;
     _securityMode = securityMode;
 }
Example #15
0
 public static bool IsDefined(SecurityMode value)
 {
     return(value == SecurityMode.None ||
            value == SecurityMode.Transport ||
            value == SecurityMode.Message ||
            value == SecurityMode.TransportWithMessageCredential);
 }
Example #16
0
        private void CheckSettings()
        {
            NetTcpSecurity security = Security;

            if (security == null)
            {
                return;
            }

            SecurityMode mode = security.Mode;

            if (mode == SecurityMode.None)
            {
                return;
            }
            else if (mode == SecurityMode.Message)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode)));
            }

            // Message.ClientCredentialType = Certificate, IssuedToken or Windows are not supported.
            if (mode == SecurityMode.TransportWithMessageCredential)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode)));
            }
        }
Example #17
0
        public static Binding GetNetTcpBinding(SecurityMode mode)
        {
            var binding = new NetTcpBinding(mode);

            Configure(binding);
            return(binding);
        }
    protected WSTrust13Binding(SecurityMode securityMode)
    {
        this._securityMode = SecurityMode.Message;

        ValidateSecurityMode(securityMode);
        this._securityMode = securityMode;
    }
    public static void Mode_Property_Sets(SecurityMode mode)
    {
        NetTcpSecurity security = new NetTcpSecurity();

        security.Mode = mode;
        Assert.Equal <SecurityMode>(mode, security.Mode);
    }
Example #20
0
        void FilterMexEndpointsAndAddOneInstance(string mexScheme)
        {
            Uri           serviceUri         = new Uri(mexScheme + "://tests:30003");
            ServiceHost   host               = new ServiceHost(typeof(MockServiceWithShielding), serviceUri);
            SecurityMode  securityMode       = SetMexAndSecurity(host, mexScheme);
            WSHttpBinding mockServiceBinding = new WSHttpBinding(securityMode);

            host.AddServiceEndpoint(typeof(IMockService), mockServiceBinding, serviceUri);
            host.Open();
            try
            {
                foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
                {
                    Assert.AreEqual(dispatcher.BindingName.Contains(mockServiceBinding.Name) ? 1 : 0, dispatcher.ErrorHandlers.Count);
                    Assert.IsFalse(dispatcher.IncludeExceptionDetailInFaults);
                }
            }
            finally
            {
                if (host.State == CommunicationState.Opened)
                {
                    host.Close();
                }
            }
        }
Example #21
0
        /// <summary>
        /// Loads settings from the Registry.
        /// </summary>
        void LoadConfig()
        {
            _sec     = (SecurityMode)Util.GetIntProperty("SecurityMode", 0);
            _sign    = (string)Util.GetProperty("Sign", "False") == "True";
            _encrypt = (string)Util.GetProperty("Encrypt", "False") == "True";
            _cert    = (string)Util.GetProperty("Cert", string.Empty);
            _tls     = (string)Util.GetProperty("TLS", "True") == "True";
            _ssl     = (string)Util.GetProperty("SSL", "True") == "True";
            _suites  = Util.GetIntProperty("Suites", 0);

            _server   = (string)Util.GetProperty("SmtpServer", string.Empty);
            _port     = Util.GetIntProperty("SmtpPort", 25);
            _userName = (string)Util.GetProperty("UserName", string.Empty);
            _password = (string)Util.GetProperty("Password", string.Empty);
            _method   = (SmtpAuthenticationMethod)Util.GetIntProperty("SmtpAuthenticationMethod", 0);
            _timeout  = Util.GetIntProperty("Timeout", 60000);

            _proxyServer               = (string)Util.GetProperty("ProxyServer", string.Empty);
            _proxyUserName             = (string)Util.GetProperty("ProxyUserName", string.Empty);
            _proxyPassword             = (string)Util.GetProperty("ProxyPassword", string.Empty);
            _proxyDomain               = (string)Util.GetProperty("ProxyDomain", string.Empty);
            _proxyPort                 = Util.GetIntProperty("ProxyPort", 1080);
            _proxyAuthenticationMethod = (ProxyHttpConnectAuthMethod)Util.GetIntProperty("ProxyAuthentication", 0);
            _proxyType                 = (ProxyType)Util.GetIntProperty("ProxyType", 0);
        }
Example #22
0
        /// <summary>
        /// Creates a kerberos binding with the specified security mode.
        /// On ADFS 2.0 only TransportWithMessageCredential is available.
        /// </summary>
        private static Binding CreateKerberosBinding(SecurityMode securityMode)
        {
            if (securityMode == SecurityMode.None)
            {
                throw new ArgumentException("securityMode None is not allowed");
            }

            BindingElementCollection bindingElements = new BindingElementCollection();

            // Add securtiy binding element
            if (securityMode == SecurityMode.Message)
            {
                bindingElements.Add(
                    SecurityBindingElement.CreateKerberosBindingElement());
            }
            else if (securityMode == SecurityMode.TransportWithMessageCredential)
            {
                bindingElements.Add(
                    SecurityBindingElement.CreateKerberosOverTransportBindingElement());
            }

            // Add encoding binding element
            bindingElements.Add(CreateEncodingBindingElement());

            // Add transport binding element
            HttpTransportBindingElement transportBindingElement =
                CreateTransportBindingElement(securityMode);

            transportBindingElement.AuthenticationScheme = AuthenticationSchemes.Negotiate;
            bindingElements.Add(transportBindingElement);

            // Create binding
            return(new CustomBinding(bindingElements));
        }
Example #23
0
        internal static bool TryCreate(SecurityBindingElement sbe, UnifiedSecurityMode mode, HttpTransportSecurity transportSecurity, bool isReliableSessionEnabled, out WSHttpSecurity security)
        {
            security = null;
            NonDualMessageSecurityOverHttp messageSecurity = null;
            SecurityMode securityMode = SecurityMode.None;

            if (sbe != null)
            {
                mode        &= UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential;
                securityMode = SecurityModeHelper.ToSecurityMode(mode);
                Fx.Assert(SecurityModeHelper.IsDefined(securityMode), string.Format("Invalid SecurityMode value: {0}.", mode.ToString()));
                if (!MessageSecurityOverHttp.TryCreate(sbe, securityMode == SecurityMode.TransportWithMessageCredential, isReliableSessionEnabled, out messageSecurity))
                {
                    return(false);
                }
            }
            else
            {
                mode        &= ~(UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential);
                securityMode = SecurityModeHelper.ToSecurityMode(mode);
            }
            Fx.Assert(SecurityModeHelper.IsDefined(securityMode), string.Format("Invalid SecurityMode value: {0}.", securityMode.ToString()));
            security = new WSHttpSecurity(securityMode, transportSecurity, messageSecurity);
            return(true);
        }
Example #24
0
        public static NetTcpBinding GetBufferedModeBinding(SecurityMode securityMode = SecurityMode.None)
        {
            var binding = new NetTcpBinding(securityMode);

            ApplyDebugTimeouts(binding);
            return(binding);
        }
Example #25
0
 public WIFINetworkDetail(string SSID, SecurityMode securityMode, BSSType networkType, int rssi, int maxDataRate)
     : base(SSID, securityMode)
 {
     this.netType     = networkType;
     this.rssi        = rssi;
     this.maxDataRate = maxDataRate;
 }
Example #26
0
 public WS2007HttpBinding(SecurityMode securityMode, bool reliableSessionEnabled)
     : base(securityMode, reliableSessionEnabled)
 {
     this.ReliableSessionBindingElement.ReliableMessagingVersion = s_WS2007ReliableMessagingVersion;
     this.TransactionFlowBindingElement.TransactionProtocol      = s_WS2007TransactionProtocol;
     this.HttpsTransport.MessageSecurityVersion = s_WS2007MessageSecurityVersion;
 }
Example #27
0
 public UserNameWSTrustBinding(SecurityMode securityMode) : base(securityMode)
 {
     if (SecurityMode.Message == securityMode)
     {
         this._clientCredentialType = HttpClientCredentialType.None;
     }
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="mode">The security mode of the validator. Control what parts has to be exist</param>
        /// <param name="publicKey">the public key as string (will be prefered before the file)</param>
        /// <param name="publicKeyFile">the public key file</param>
        public NetSparkleDSAVerificator(SecurityMode mode, String publicKey = null, String publicKeyFile = "NetSparkle_DSA.pub")
        {
            _securityMode = mode;

            String key = publicKey;

            if (string.IsNullOrEmpty(key))
            {
                // TODO: Loading Ressources don't work
                Stream data = TryGetResourceStream(publicKeyFile);
                if (data == null)
                    data = TryGetFileResource(publicKeyFile, data);

                if (data != null)
                {
                    using (StreamReader reader = new StreamReader(data))
                    {
                        key = reader.ReadToEnd();
                    }
                }
            }

            if (!string.IsNullOrEmpty(key))
            {
                try
                {
                    _provider = new DSACryptoServiceProvider();
                    _provider.FromXmlString(key);
                }
                catch
                {
                    _provider = null;
                }
            }
        }
 public UserNameWSTrustBinding(SecurityMode securityMode) : base(securityMode)
 {
     if (SecurityMode.Message == securityMode)
     {
         _clientCredentialType = HttpClientCredentialType.None;
     }
 }
        public BindingProperties(SecurityMode securityMode, MessageCredentialType messageCredentialType, 
            TcpClientCredentialType tcpClientCredentialType, ProtectionLevel protectionLevel,
            int maxConnections, long maxReceivedMessageSize, long maxBufferPoolSize, int maxArrayLength, 
            int maxBytesPerRead, int maxDepth, int maxStringContentLength, int maxBufferSize,
            TimeSpan openTimeout, TimeSpan closeTimeout, TimeSpan receiveTimeout, TimeSpan sendTimeout)
        {
            m_SecurityMode = securityMode;
            m_MessageCredentialType = messageCredentialType;
            m_TcpClientCredentialType = tcpClientCredentialType;
            m_ProtectionLevel = protectionLevel;

            m_MaxConnections = maxConnections;
            m_MaxReceivedMessageSize = maxReceivedMessageSize;
            m_MaxBufferPoolSize = maxBufferPoolSize;
            m_MaxArrayLength = maxArrayLength;
            m_MaxBytesPerRead = maxBytesPerRead;
            m_MaxDepth = maxDepth;
            m_MaxStringContentLength = maxStringContentLength;
            m_MaxBufferSize = maxBufferSize;

            m_OpenTimeout = openTimeout;
            m_CloseTimeout = closeTimeout;
            m_ReceiveTimeout = receiveTimeout;
            m_SendTimeout = sendTimeout;
        }
Example #31
0
 public static bool IsDefined(SecurityMode value)
 {
     return (value == SecurityMode.None ||
         value == SecurityMode.Transport ||
         value == SecurityMode.Message ||
         value == SecurityMode.TransportWithMessageCredential);
 }
Example #32
0
        protected string Security(SecurityMode securityMode, string source)
        {
            switch (_securityComponentMode)
            {
            case SecurityComponentMode.Base64:
                _securityUtility = new Base64Helper();
                break;

            case SecurityComponentMode.DES:
                _securityUtility = new DESHelper();
                break;

            case SecurityComponentMode.MD5:
                _securityUtility = new MD5Helper();
                break;

            case SecurityComponentMode.RSACryption:
                _securityUtility = new RSACryptionHelper(_privateKey, _publicKey);
                break;

            case SecurityComponentMode.TripleDES:
                _securityUtility = new TripleDESHelper();
                break;

            default:
                break;
            }
            return(_securityUtility.SecurityUtilityInvoke(securityMode).Invoke(source));
        }
Example #33
0
        public static WSHttpBinding GetBufferedModeWSHttpBinding(SecurityMode securityMode)
        {
            var binding = new WSHttpBinding(securityMode);

            ApplyDebugTimeouts(binding);
            return(binding);
        }
Example #34
0
        /*
         * Otvaranje konekcije na servis
         */
        private void Connect()
        {
            var security = new SecurityMode();
            var binding  = new WSHttpBinding(security, true);
            var address  = new EndpointAddress("http://zivlakmilos.ddns.net:8325/");

            client = new HangmanClient(binding, address);
        }
 internal static bool IsDefined(SecurityMode value)
 {
     if (((value != SecurityMode.None) && (value != SecurityMode.Transport)) && (value != SecurityMode.Message))
     {
         return(value == SecurityMode.TransportWithMessageCredential);
     }
     return(true);
 }
        /// <summary>
        /// Hosts the service.
        /// </summary>
        /// <typeparam name="Service">Service contract or type</typeparam>
        /// <typeparam name="Implementation">Implementation contract or type</typeparam>
        /// <param name="endPointAddress">The end point address.</param>
        /// <param name="securityMode">The security mode.</param>
        public void HostService <Service, Implementation>(string endPointAddress, SecurityMode securityMode = SecurityMode.None)
        {
            var serviceHost = new ServiceHost(typeof(Service));
            var tcpBinding  = new NetTcpBinding(SecurityMode.None);

            serviceHost.AddServiceEndpoint(typeof(Implementation), tcpBinding, endPointAddress);
            serviceHost.Open();
        }
Example #37
0
 private void PropertyChangedHandler(object sender, PropertyChangedEventArgs args)
 {
     if (args.PropertyName == "CurrentItem")
     {
         LoadPermissionsDataSet();
         m_securityMode = IsNewRecord || !string.IsNullOrEmpty(CurrentItem.RemoteCertificateFile) ? SecurityMode.TLS : SecurityMode.Gateway;
     }
 }
Example #38
0
        public int Create(string Name)
        {
            int          result = 1;
            SecurityMode sr     = SecurityMode.CreateSecurityMode(0, Name, Name);

            context.AddToSecurityModes(sr);
            return(result);
        }
        NetTcpSecurity(SecurityMode mode, TcpTransportSecurity transportSecurity, MessageSecurityOverTcp messageSecurity)
        {
            Fx.Assert(SecurityModeHelper.IsDefined(mode), string.Format("Invalid SecurityMode value: {0}.", mode.ToString()));

            this.mode = mode;
            this.transportSecurity = transportSecurity == null ? new TcpTransportSecurity() : transportSecurity;
            this.messageSecurity = messageSecurity == null ? new MessageSecurityOverTcp() : messageSecurity;
        }
    protected static void ValidateSecurityMode(SecurityMode securityMode)
    {
        SecurityMode[] allowedModes = { SecurityMode.Message, SecurityMode.Transport, SecurityMode.TransportWithMessageCredential };

        if (!allowedModes.Contains(securityMode))
        {
            throw new ArgumentException();
        }
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="BusinessServicesClientConfigEntity"/> class.
 /// </summary>
 /// <param name="host">The host.</param>
 /// <param name="port">The port.</param>
 /// <param name="servicesName">Name of the services.</param>
 /// <param name="securityMode">The security mode.</param>
 /// <param name="userName">The username component of the security credentials.</param>
 /// <param name="password">The password component of the security credentials.</param>
 public BusinessServicesClientConfigEntity(string host, int port, string servicesName, SecurityMode? securityMode, string userName, string password)
 {
     _host = host;
     _port = port;
     _servicesName = servicesName;
     _securityMode = securityMode;
     _userName = userName;
     _password = password;
 }
Example #42
0
		public static int Main (string[] args)
		{
			using (ServiceHost host = new ServiceHost (typeof (HangmanService)))
			{
				var security = new SecurityMode ();
				host.AddServiceEndpoint (
					typeof(IHangmanService),
					new WSHttpBinding (security, true),
					"http://localhost:8325/");

				host.Open ();

				/*
				Console.WriteLine ("Type [CR] to stop ...");
				Console.ReadKey ();
				*/

				/* Demon */
				UnixSignal sigint = new UnixSignal (Signum.SIGINT);
				UnixSignal sigterm = new UnixSignal (Signum.SIGTERM);
				UnixSignal sighup = new UnixSignal (Signum.SIGHUP);
				UnixSignal sigusr2 = new UnixSignal (Signum.SIGUSR2);
				UnixSignal [] signals = new UnixSignal[]
					{
						sigint,
						sigterm,
						sighup,
						sigusr2
					};

				bool exit = false;
				while (!exit)
				{
					int id = UnixSignal.WaitAny (signals);

					if (id >= 0 && id < signals.Length)
					{
						if (sigint.IsSet || sigterm.IsSet)
						{
							sigint.Reset ();
							sigterm.Reset ();
							exit = true;
						} else if (sighup.IsSet)
							sighup.Reset ();
						else if (sigusr2.IsSet)
							sighup.Reset ();

					}
				}
				/* Demon */

				host.Close ();
			}

			return 0;
		}
    public static Binding NewBinding(SecurityMode securityMode)
    {
      Contract.Ensures(Contract.Result<Binding>() != null);

#if WS_HTTP_BINDING
      return new WSDualHttpBinding(securityMode);
#elif NET_TCP_BINDING
      return new NetTcpBinding(securityMode);
#endif
    }
		private static ServiceConfiguration CreateForLongOperation(SecurityMode securityMode)
		{
			return
				new ServiceConfiguration(
					new NetTcpBinding(securityMode),
					HostName,
					Port,
					int.MaxValue,
					int.MaxValue,
					true);
		}
 internal static bool SetTransportSecurity(BindingElement transport, SecurityMode mode, TcpTransportSecurity transportSecurity)
 {
     if (mode == SecurityMode.TransportWithMessageCredential)
     {
         return TcpTransportSecurity.SetTransportProtectionOnly(transport, transportSecurity);
     }
     if (mode == SecurityMode.Transport)
     {
         return TcpTransportSecurity.SetTransportProtectionAndAuthentication(transport, transportSecurity);
     }
     return (transport == null);
 }
Example #46
0
    public static void Ctor_Default_Initializes_Properties(SecurityMode securityMode)
    {
        var binding = new NetTcpBinding(securityMode);

        Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap12, binding.EnvelopeVersion);
        Assert.Equal<long>(512 * 1024, binding.MaxBufferPoolSize);
        Assert.Equal<long>(65536, binding.MaxBufferSize);
        Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
        Assert.Equal<string>("net.tcp", binding.Scheme);
        Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
        Assert.Equal<SecurityMode>(securityMode, binding.Security.Mode);
    }
Example #47
0
        private NetTcpSecurity(SecurityMode mode, TcpTransportSecurity transportSecurity, MessageSecurityOverTcp messageSecurity)
        {
            Contract.Assert(SecurityModeHelper.IsDefined(mode),
                            string.Format("Invalid SecurityMode value: {0} = {1} (default is {2} = {3}).",
                                            (int)mode,
                                            mode.ToString(),
                                            (int)SecurityMode.Transport,
                                            SecurityMode.Transport.ToString()));

            _mode = mode;
            _transportSecurity = transportSecurity == null ? new TcpTransportSecurity() : transportSecurity;
            _messageSecurity = messageSecurity == null ? new MessageSecurityOverTcp() : messageSecurity;
        }
 protected WSTrustBindingBase(SecurityMode securityMode, TrustVersion trustVersion)
 {
     this._securityMode = SecurityMode.Message;
     this._trustVersion = TrustVersion.WSTrust13;
     if (trustVersion == null)
     {
         throw new ArgumentNullException("trustVersion");
     }
     this.ValidateTrustVersion(trustVersion);
     ValidateSecurityMode(securityMode);
     this._securityMode = securityMode;
     this._trustVersion = trustVersion;
 }
 public UserNameWSTrustBinding(SecurityMode mode, HttpClientCredentialType clientCredentialType)
     : base(mode)
 {
     if (!IsHttpClientCredentialTypeDefined(clientCredentialType))
     {
         throw new ArgumentOutOfRangeException("clientCredentialType");
     }
     if (((SecurityMode.Transport == mode) && (HttpClientCredentialType.Digest != clientCredentialType)) && (HttpClientCredentialType.Basic != clientCredentialType))
     {
         throw new InvalidOperationException("ID3225");
     }
     this._clientCredentialType = clientCredentialType;
 }
 internal static bool TryCreate(SecurityBindingElement wsSecurity, SecurityMode mode, bool isReliableSessionEnabled, BindingElement transportSecurity, TcpTransportSecurity tcpTransportSecurity, out NetTcpSecurity security)
 {
     security = null;
     MessageSecurityOverTcp messageSecurity = null;
     if (mode == SecurityMode.Message)
     {
         if (!MessageSecurityOverTcp.TryCreate(wsSecurity, isReliableSessionEnabled, null, out messageSecurity))
         {
             return false;
         }
     }
     else if ((mode == SecurityMode.TransportWithMessageCredential) && !MessageSecurityOverTcp.TryCreate(wsSecurity, isReliableSessionEnabled, transportSecurity, out messageSecurity))
     {
         return false;
     }
     security = new NetTcpSecurity(mode, tcpTransportSecurity, messageSecurity);
     return SecurityElementBase.AreBindingsMatching(security.CreateMessageSecurity(isReliableSessionEnabled), wsSecurity, false);
 }
    static ClousotWCFServiceCommon()
    {
      Identity = new DnsEndpointIdentity("research.microsoft.com"); // Used by the client to be sure that we are who we say we are

#if DEBUG
      SecurityMode = SecurityMode.None;  // Mehdi: "Very complex things", we ignore them
#else
      SecurityMode = SecurityMode.None; // TODO
#endif

#if WS_HTTP_BINDING
#if DEBUG
      // This address does not need administrator privilege
      // Namespace created during the installation of Visual Studio
      BaseAddress = "http://localhost:8732/Design_Time_Addresses/ClousotService/";
#else
      // Need administrator privilege
      BaseAddress = "http://localhost:8732/Microsoft.Research/ClousotService/";
#endif
#elif NET_TCP_BINDING
      BaseAddress = "net.tcp://localhost:9922/ClousotService/";
#endif
      BaseUri = new Uri(BaseAddress);
    }
 public WindowsWSTrustBinding(SecurityMode securityMode)
     : base(securityMode)
 { }
Example #53
0
			public MyWSBinding (SecurityMode mode)
				: base (mode)
			{
			}
Example #54
0
		public static void NetTcpBinding (
			TestContext context, MetadataSet doc, SecurityMode security,
			bool reliableSession, TransferMode transferMode, TestLabel label)
		{
			label.EnterScope ("netTcpBinding");

			var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

			label.EnterScope ("wsdl");

			label.EnterScope ("bindings");
			Assert.That (sd.Bindings.Count, Is.EqualTo (1), label.Get ());
			var binding = sd.Bindings [0];
			Assert.That (binding.ExtensibleAttributes, Is.Null, label.Get ());
			Assert.That (binding.Extensions, Is.Not.Null, label.Get ());

			WS.Soap12Binding soap = null;
			XmlElement xml = null;
			
			foreach (var ext in binding.Extensions) {
				if (ext is WS.Soap12Binding)
					soap = (WS.Soap12Binding)ext;
				else if (ext is XmlElement)
					xml = (XmlElement)ext;
			}
			
			CheckSoapBinding (soap, "http://schemas.microsoft.com/soap/tcp", label);

			label.EnterScope ("policy-xml");
			Assert.That (xml, Is.Not.Null, label.Get ());
			var assertions = AssertPolicy (sd, xml, label);
			Assert.That (assertions, Is.Not.Null, label.Get ());
			AssertPolicy (assertions, BinaryEncodingQName, label);
			AssertPolicy (assertions, UsingAddressingQName, label);
			if (transferMode == TransferMode.Streamed)
				AssertPolicy (assertions, StreamedTransferQName, label);
			switch (security) {
			case SecurityMode.Message:
				AssertPolicy (assertions, SymmetricBindingQName, label);
				AssertPolicy (assertions, Wss11QName, label);
				AssertPolicy (assertions, Trust10QName, label);
				break;
			case SecurityMode.Transport:
				AssertPolicy (assertions, TransportBindingQName, label);
				break;
			case SecurityMode.TransportWithMessageCredential:
				AssertPolicy (assertions, TransportBindingQName, label);
				AssertPolicy (assertions, EndorsingSupportingQName, label);
				AssertPolicy (assertions, Wss11QName, label);
				AssertPolicy (assertions, Trust10QName, label);
				break;
			default:
				break;
			}
			if (reliableSession)
				AssertPolicy (assertions, ReliableSessionQName, label);
			Assert.That (assertions.Count, Is.EqualTo (0), label.Get ());
			label.LeaveScope ();

			label.EnterScope ("services");
			Assert.That (sd.Services, Is.Not.Null, label.Get ());
			Assert.That (sd.Services.Count, Is.EqualTo (1), label.Get ());
			var service = sd.Services [0];
			Assert.That (service.Ports, Is.Not.Null, label.Get ());
			Assert.That (service.Ports.Count, Is.EqualTo (1), label.Get ());
			var port = service.Ports [0];

			label.EnterScope ("port");
			Assert.That (port.Extensions, Is.Not.Null, label.Get ());
			Assert.That (port.Extensions.Count, Is.EqualTo (2), label.Get ());

			WS.Soap12AddressBinding soap_addr_binding = null;
			XmlElement port_xml = null;
			foreach (var extension in port.Extensions) {
				if (extension is WS.Soap12AddressBinding)
					soap_addr_binding = (WS.Soap12AddressBinding)extension;
				else if (extension is XmlElement)
					port_xml = (XmlElement)extension;
				else
					Assert.Fail (label.Get ());
			}
			Assert.That (soap_addr_binding, Is.Not.Null, label.Get ());
			Assert.That (port_xml, Is.Not.Null, label.Get ());
			Assert.That (port_xml.NamespaceURI, Is.EqualTo (Wsa10Namespace), label.Get ());
			Assert.That (port_xml.LocalName, Is.EqualTo ("EndpointReference"), label.Get ());
			label.LeaveScope ();
			label.LeaveScope ();

			label.LeaveScope (); // wsdl

			var importer = new WsdlImporter (doc);

			label.EnterScope ("bindings");
			var bindings = importer.ImportAllBindings ();
			CheckImportErrors (importer, label);
			Assert.That (bindings, Is.Not.Null, label.Get ());
			Assert.That (bindings.Count, Is.EqualTo (1), label.Get ());
			
			CheckNetTcpBinding (
				bindings [0], security, reliableSession,
				transferMode, label);
			label.LeaveScope ();

			label.EnterScope ("endpoints");
			var endpoints = importer.ImportAllEndpoints ();
			CheckImportErrors (importer, label);
			Assert.That (endpoints, Is.Not.Null, label.Get ());
			Assert.That (endpoints.Count, Is.EqualTo (1), label.Get ());
			
			CheckEndpoint (endpoints [0], MetadataSamples.NetTcpUri, label);
			label.LeaveScope ();

			label.LeaveScope ();
		}
 internal PeerSecuritySettings(PeerSecurityElement element)
 {
     mode = element.Mode;
     transportSecurity = new PeerTransportSecuritySettings(element.Transport);
 }
Example #56
0
		public static void CheckNetTcpBinding (
			Binding binding, SecurityMode security, bool reliableSession,
			TransferMode transferMode, TestLabel label)
		{
			label.EnterScope ("net-tcp");
			if (security == SecurityMode.Message) {
				Assert.That (binding, Is.InstanceOfType (typeof(CustomBinding)), label.Get ());
			} else {
				Assert.That (binding, Is.InstanceOfType (typeof(NetTcpBinding)), label.Get ());
				var netTcp = (NetTcpBinding)binding;
				Assert.That (netTcp.EnvelopeVersion, Is.EqualTo (EnvelopeVersion.Soap12), label.Get ());
				Assert.That (netTcp.MessageVersion, Is.EqualTo (MessageVersion.Soap12WSAddressing10), label.Get ());
				Assert.That (netTcp.Scheme, Is.EqualTo ("net.tcp"), label.Get ());
				Assert.That (netTcp.TransferMode, Is.EqualTo (transferMode), label.Get ());

				label.EnterScope ("security");
				Assert.That (netTcp.Security, Is.Not.Null, label.Get ());
				Assert.That (netTcp.Security.Mode, Is.EqualTo (security), label.Get ());

				Assert.That (netTcp.Security.Transport, Is.Not.Null, label.Get ());
				Assert.That (netTcp.Security.Transport.ProtectionLevel, Is.EqualTo (ProtectionLevel.EncryptAndSign), label.Get ());
				Assert.That (netTcp.Security.Transport.ClientCredentialType, Is.EqualTo (TcpClientCredentialType.Windows), label.Get ());
				label.LeaveScope ();
			}

			label.EnterScope ("elements");
			
			var elements = binding.CreateBindingElements ();
			Assert.That (elements, Is.Not.Null, label.Get ());

			TcpTransportBindingElement transportElement = null;
			TransactionFlowBindingElement transactionFlowElement = null;
			BinaryMessageEncodingBindingElement encodingElement = null;
			WindowsStreamSecurityBindingElement windowsStreamElement = null;
			ReliableSessionBindingElement reliableSessionElement = null;
			TransportSecurityBindingElement transportSecurityElement = null;
			SslStreamSecurityBindingElement sslStreamElement = null;
			SymmetricSecurityBindingElement symmSecurityElement = null;
			
			foreach (var element in elements) {
				if (element is TcpTransportBindingElement)
					transportElement = (TcpTransportBindingElement)element;
				else if (element is TransactionFlowBindingElement)
					transactionFlowElement = (TransactionFlowBindingElement)element;
				else if (element is BinaryMessageEncodingBindingElement)
					encodingElement = (BinaryMessageEncodingBindingElement)element;
				else if (element is WindowsStreamSecurityBindingElement)
					windowsStreamElement = (WindowsStreamSecurityBindingElement)element;
				else if (element is ReliableSessionBindingElement)
					reliableSessionElement = (ReliableSessionBindingElement)element;
				else if (element is TransportSecurityBindingElement)
					transportSecurityElement = (TransportSecurityBindingElement)element;
				else if (element is SslStreamSecurityBindingElement)
					sslStreamElement = (SslStreamSecurityBindingElement)element;
				else if (element is SymmetricSecurityBindingElement)
					symmSecurityElement = (SymmetricSecurityBindingElement)element;
				else
					Assert.Fail (string.Format (
						"Unknown element `{0}'.", element.GetType ()), label.Get ());
			}

			label.EnterScope ("windows-stream");
			if (security == SecurityMode.Transport) {
				Assert.That (windowsStreamElement, Is.Not.Null, label.Get ());
				Assert.That (windowsStreamElement.ProtectionLevel, Is.EqualTo (ProtectionLevel.EncryptAndSign), label.Get ());
			} else {
				Assert.That (windowsStreamElement, Is.Null, label.Get ());
			}
			label.LeaveScope ();

			label.EnterScope ("reliable-session");
			if (reliableSession) {
				Assert.That (reliableSessionElement, Is.Not.Null, label.Get ());
			} else {
				Assert.That (reliableSessionElement, Is.Null, label.Get ());
			}
			label.LeaveScope ();

			label.EnterScope ("encoding");
			Assert.That (encodingElement, Is.Not.Null, label.Get ());
			label.LeaveScope ();

			label.EnterScope ("transaction");
			if (security == SecurityMode.Message) {
				Assert.That (transactionFlowElement, Is.Null, label.Get ());
			} else {
				Assert.That (transactionFlowElement, Is.Not.Null, label.Get ());
			}
			label.LeaveScope ();

			label.EnterScope ("transport");
			Assert.That (transportElement, Is.Not.Null, label.Get ());

			Assert.That (transportElement.Scheme, Is.EqualTo ("net.tcp"), label.Get ());
			Assert.That (transportElement.TransferMode, Is.EqualTo (transferMode), label.Get ());
			label.LeaveScope (); // transport

			label.EnterScope ("security");
			switch (security) {
			case SecurityMode.None:
			case SecurityMode.Transport:
				Assert.That (transportSecurityElement, Is.Null, label.Get ());
				Assert.That (sslStreamElement, Is.Null, label.Get ());
				Assert.That (symmSecurityElement, Is.Null, label.Get ());
				break;
			case SecurityMode.TransportWithMessageCredential:
				Assert.That (transportSecurityElement, Is.Not.Null, label.Get ());
				Assert.That (sslStreamElement, Is.Not.Null, label.Get ());
				Assert.That (symmSecurityElement, Is.Null, label.Get ());
				break;
			case SecurityMode.Message:
				Assert.That (transportSecurityElement, Is.Null, label.Get ());
				Assert.That (sslStreamElement, Is.Null, label.Get ());
				Assert.That (symmSecurityElement, Is.Not.Null, label.Get ());
				break;
			default:
				throw new InvalidOperationException ();
			}
			label.LeaveScope ();

			label.LeaveScope (); // elements
			label.LeaveScope (); // net-tcp
		}
Example #57
0
 private static bool SetTransportSecurity(BindingElement transport, SecurityMode mode, TcpTransportSecurity transportSecurity)
 {
     return NetTcpSecurity.SetTransportSecurity(transport, mode, transportSecurity);
 }
Example #58
0
 public NetTcpBinding(SecurityMode securityMode)
     : this()
 {
     _security.Mode = securityMode;
 }
Example #59
0
 public static void Mode_Property_Sets(SecurityMode mode)
 {
     NetTcpSecurity security = new NetTcpSecurity();
     security.Mode = mode;
     Assert.Equal<SecurityMode>(mode, security.Mode);
 }
Example #60
0
        /// <summary>
        /// Initializes <see cref="DataSubscriber"/>.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            Dictionary<string, string> settings = Settings;
            string setting;

            OperationalModes operationalModes;
            CompressionModes compressionModes;
            int metadataSynchronizationTimeout;
            double interval;
            int bufferSize;

            // Setup connection to data publishing server with or without authentication required
            if (settings.TryGetValue("requireAuthentication", out setting))
                RequireAuthentication = setting.ParseBoolean();

            // See if user has opted for different operational modes
            if (settings.TryGetValue("operationalModes", out setting) && Enum.TryParse(setting, true, out operationalModes))
                OperationalModes = operationalModes;

            // Set the security mode if explicitly defined
            if (!settings.TryGetValue("securityMode", out setting) || !Enum.TryParse(setting, true, out m_securityMode))
                m_securityMode = SecurityMode.None;

            // Apply gateway compression mode to operational mode flags
            if (settings.TryGetValue("compressionModes", out setting) && Enum.TryParse(setting, true, out compressionModes))
                CompressionModes = compressionModes;

            if (settings.TryGetValue("useZeroMQChannel", out setting))
                m_useZeroMQChannel = setting.ParseBoolean();

            // TODO: Remove this exception when CURVE is enabled in GSF ZeroMQ library
            if (m_useZeroMQChannel && m_securityMode == SecurityMode.TLS)
                throw new ArgumentException("CURVE security settings are not yet available for GSF ZeroMQ client channel.");

            // Settings specific to Gateway security
            if (m_securityMode == SecurityMode.Gateway)
            {
                if (!settings.TryGetValue("sharedSecret", out m_sharedSecret) || string.IsNullOrWhiteSpace(m_sharedSecret))
                    throw new ArgumentException("The \"sharedSecret\" setting must be defined when using Gateway security mode.");

                if (!settings.TryGetValue("authenticationID", out m_authenticationID) || string.IsNullOrWhiteSpace(m_authenticationID))
                    throw new ArgumentException("The \"authenticationID\" setting must be defined when using Gateway security mode.");
            }

            // Settings specific to Transport Layer Security
            if (m_securityMode == SecurityMode.TLS)
            {
                if (!settings.TryGetValue("localCertificate", out m_localCertificate) || !File.Exists(m_localCertificate))
                    m_localCertificate = GetLocalCertificate();

                if (!settings.TryGetValue("remoteCertificate", out m_remoteCertificate) || !RemoteCertificateExists())
                    throw new ArgumentException("The \"remoteCertificate\" setting must be defined and certificate file must exist when using TLS security mode.");

                if (!settings.TryGetValue("validPolicyErrors", out setting) || !Enum.TryParse(setting, out m_validPolicyErrors))
                    m_validPolicyErrors = SslPolicyErrors.None;

                if (!settings.TryGetValue("validChainFlags", out setting) || !Enum.TryParse(setting, out m_validChainFlags))
                    m_validChainFlags = X509ChainStatusFlags.NoError;

                if (settings.TryGetValue("checkCertificateRevocation", out setting) && !string.IsNullOrWhiteSpace(setting))
                    m_checkCertificateRevocation = setting.ParseBoolean();
                else
                    m_checkCertificateRevocation = true;
            }

            // Check if measurements for this connection should be marked as "internal" - i.e., owned and allowed for proxy
            if (settings.TryGetValue("internal", out setting))
                m_internal = setting.ParseBoolean();

            // Check if user has explicitly defined the ReceiveInternalMetadata flag
            if (settings.TryGetValue("receiveInternalMetadata", out setting))
                ReceiveInternalMetadata = setting.ParseBoolean();

            // Check if user has explicitly defined the ReceiveExternalMetadata flag
            if (settings.TryGetValue("receiveExternalMetadata", out setting))
                ReceiveExternalMetadata = setting.ParseBoolean();

            // Check if user has defined a meta-data synchronization timeout
            if (settings.TryGetValue("metadataSynchronizationTimeout", out setting) && int.TryParse(setting, out metadataSynchronizationTimeout))
                m_metadataSynchronizationTimeout = metadataSynchronizationTimeout;

            // Check if user has defined a flag for using a transaction during meta-data synchronization
            if (settings.TryGetValue("useTransactionForMetadata", out setting))
                m_useTransactionForMetadata = setting.ParseBoolean();

            // Check if user wants to request that publisher use millisecond resolution to conserve bandwidth
            if (settings.TryGetValue("useMillisecondResolution", out setting))
                m_useMillisecondResolution = setting.ParseBoolean();

            // Check if user wants to request that publisher remove NaN from the data stream to conserve bandwidth
            if (settings.TryGetValue("requestNaNValueFilter", out setting))
                m_requestNaNValueFilter = setting.ParseBoolean();

            // Check if user has defined any meta-data filter expressions
            if (settings.TryGetValue("metadataFilters", out setting))
                m_metadataFilters = setting;

            // Define auto connect setting
            if (settings.TryGetValue("autoConnect", out setting))
            {
                m_autoConnect = setting.ParseBoolean();

                if (m_autoConnect)
                    m_autoSynchronizeMetadata = true;
            }

            // Define the maximum allowed exceptions before resetting the connection
            if (settings.TryGetValue("allowedParsingExceptions", out setting))
                m_allowedParsingExceptions = int.Parse(setting);

            // Define the window of time over which parsing exceptions are tolerated
            if (settings.TryGetValue("parsingExceptionWindow", out setting))
                m_parsingExceptionWindow = Ticks.FromSeconds(double.Parse(setting));

            // Check if synchronize meta-data is explicitly enabled or disabled
            if (settings.TryGetValue("synchronizeMetadata", out setting))
                m_autoSynchronizeMetadata = setting.ParseBoolean();

            // Define data loss interval
            if (settings.TryGetValue("dataLossInterval", out setting) && double.TryParse(setting, out interval))
                DataLossInterval = interval;

            // Define buffer size
            if (!settings.TryGetValue("bufferSize", out setting) || !int.TryParse(setting, out bufferSize))
                bufferSize = ClientBase.DefaultReceiveBufferSize;

            if (settings.TryGetValue("useLocalClockAsRealTime", out setting))
                m_useLocalClockAsRealTime = setting.ParseBoolean();

            if (m_autoConnect)
            {
                // Connect to local events when automatically engaging connection cycle
                ConnectionAuthenticated += DataSubscriber_ConnectionAuthenticated;
                MetaDataReceived += DataSubscriber_MetaDataReceived;

                // Update output measurements to include "subscribed" points
                UpdateOutputMeasurements(true);
            }
            else if (m_autoSynchronizeMetadata)
            {
                // Output measurements do not include "subscribed" points,
                // but should still be filtered if applicable
                TryFilterOutputMeasurements();
            }

            if (m_securityMode != SecurityMode.TLS)
            {
                if (m_useZeroMQChannel)
                {
                    // Create a new ZeroMQ Dealer
                    ZeroMQClient commandChannel = new ZeroMQClient();

                    // Initialize default settings
                    commandChannel.PersistSettings = false;
                    commandChannel.MaxConnectionAttempts = 1;
                    commandChannel.ReceiveBufferSize = bufferSize;
                    commandChannel.SendBufferSize = bufferSize;

                    // Assign command channel client reference and attach to needed events
                    CommandChannel = commandChannel;
                }
                else
                {
                    // Create a new TCP client
                    TcpClient commandChannel = new TcpClient();

                    // Initialize default settings
                    commandChannel.PayloadAware = true;
                    commandChannel.PersistSettings = false;
                    commandChannel.MaxConnectionAttempts = 1;
                    commandChannel.ReceiveBufferSize = bufferSize;
                    commandChannel.SendBufferSize = bufferSize;

                    // Assign command channel client reference and attach to needed events
                    CommandChannel = commandChannel;
                }
            }
            else
            {
                if (m_useZeroMQChannel)
                {
                    // Create a new ZeroMQ Dealer with CURVE security enabled
                    ZeroMQClient commandChannel = new ZeroMQClient();

                    // Initialize default settings
                    commandChannel.PersistSettings = false;
                    commandChannel.MaxConnectionAttempts = 1;
                    commandChannel.ReceiveBufferSize = bufferSize;
                    commandChannel.SendBufferSize = bufferSize;

                    // TODO: Parse certificate and pass keys to ZeroMQClient for CURVE security

                    // Assign command channel client reference and attach to needed events
                    CommandChannel = commandChannel;
                }
                else
                {
                    // Create a new TLS client and certificate checker
                    TlsClient commandChannel = new TlsClient();
                    SimpleCertificateChecker certificateChecker = new SimpleCertificateChecker();

                    // Set up certificate checker
                    certificateChecker.TrustedCertificates.Add(new X509Certificate2(FilePath.GetAbsolutePath(m_remoteCertificate)));
                    certificateChecker.ValidPolicyErrors = m_validPolicyErrors;
                    certificateChecker.ValidChainFlags = m_validChainFlags;

                    // Initialize default settings
                    commandChannel.PayloadAware = true;
                    commandChannel.PersistSettings = false;
                    commandChannel.MaxConnectionAttempts = 1;
                    commandChannel.CertificateFile = FilePath.GetAbsolutePath(m_localCertificate);
                    commandChannel.CheckCertificateRevocation = m_checkCertificateRevocation;
                    commandChannel.CertificateChecker = certificateChecker;
                    commandChannel.ReceiveBufferSize = bufferSize;
                    commandChannel.SendBufferSize = bufferSize;

                    // Assign command channel client reference and attach to needed events
                    CommandChannel = commandChannel;
                }
            }

            // Get proper connection string - either from specified command channel or from base connection string
            if (settings.TryGetValue("commandChannel", out setting))
                m_commandChannel.ConnectionString = setting;
            else
                m_commandChannel.ConnectionString = ConnectionString;

            // Get logging path, if any has been defined
            if (settings.TryGetValue("loggingPath", out setting))
            {
                setting = FilePath.GetDirectoryName(FilePath.GetAbsolutePath(setting));

                if (Directory.Exists(setting))
                    m_loggingPath = setting;
                else
                    OnStatusMessage("WARNING: Logging path \"{0}\" not found, defaulting to \"{1}\"...", setting, FilePath.GetAbsolutePath(""));
            }

            // Initialize data gap recovery processing, if requested
            if (settings.TryGetValue("dataGapRecovery", out setting))
            {
                // Make sure setting exists to allow user to by-pass phasor data source validation at startup
                ConfigurationFile configFile = ConfigurationFile.Current;
                CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];
                CategorizedSettingsElement dataGapRecoveryEnabledSetting = systemSettings["DataGapRecoveryEnabled"];

                // See if this node should process phasor source validation
                if ((object)dataGapRecoveryEnabledSetting == null || dataGapRecoveryEnabledSetting.ValueAsBoolean())
                {
                    // Example connection string for data gap recovery:
                    //  dataGapRecovery={enabled=true; recoveryStartDelay=10.0; minimumRecoverySpan=0.0; maximumRecoverySpan=3600.0}
                    Dictionary<string, string> dataGapSettings = setting.ParseKeyValuePairs();

                    if (dataGapSettings.TryGetValue("enabled", out setting) && setting.ParseBoolean())
                    {
                        // Remove dataGapRecovery connection setting from command channel connection string, if defined there.
                        // This will prevent any recursive data gap recovery operations from being established:
                        Dictionary<string, string> connectionSettings = m_commandChannel.ConnectionString.ParseKeyValuePairs();
                        connectionSettings.Remove("dataGapRecovery");
                        connectionSettings.Remove("autoConnect");
                        connectionSettings.Remove("synchronizeMetadata");
                        connectionSettings.Remove("outputMeasurements");

                        // Note that the data gap recoverer will connect on the same command channel port as
                        // the real-time subscriber (TCP only)
                        m_dataGapRecoveryEnabled = true;
                        m_dataGapRecoverer = new DataGapRecoverer();
                        m_dataGapRecoverer.SourceConnectionName = Name;
                        m_dataGapRecoverer.DataSource = DataSource;
                        m_dataGapRecoverer.ConnectionString = string.Join("; ", $"autoConnect=false; synchronizeMetadata=false{(string.IsNullOrWhiteSpace(m_loggingPath) ? "" : "; loggingPath=" + m_loggingPath)}", dataGapSettings.JoinKeyValuePairs(), connectionSettings.JoinKeyValuePairs());
                        m_dataGapRecoverer.FilterExpression = this.OutputMeasurementKeys().Select(key => key.SignalID.ToString()).ToDelimitedString(';');
                        m_dataGapRecoverer.RecoveredMeasurements += m_dataGapRecoverer_RecoveredMeasurements;
                        m_dataGapRecoverer.StatusMessage += m_dataGapRecoverer_StatusMessage;
                        m_dataGapRecoverer.ProcessException += m_dataGapRecoverer_ProcessException;
                        m_dataGapRecoverer.Initialize();
                    }
                    else
                    {
                        m_dataGapRecoveryEnabled = false;
                    }
                }
            }
            else
            {
                m_dataGapRecoveryEnabled = false;
            }

            // Register subscriber with the statistics engine
            StatisticsEngine.Register(this, "Subscriber", "SUB");
            StatisticsEngine.Calculated += (sender, args) => ResetMeasurementsPerSecondCounters();

            Initialized = true;
        }