/// <summary>
 /// Convert user token policies to service model
 /// </summary>
 /// <param name="policies"></param>
 /// <returns></returns>
 public static List <AuthenticationMethodModel> ToServiceModel(
     this UserTokenPolicyCollection policies)
 {
     if (policies == null || policies.Count == 0)
     {
         return(new List <AuthenticationMethodModel> {
             new AuthenticationMethodModel {
                 Id = "Anonymous",
                 CredentialType = CredentialType.None
             }
         });
     }
     return(policies
            .Select(p => p.ToServiceModel())
            .Where(p => p != null)
            .Distinct()
            .ToList());
 }
        /// <summary>
        /// Finds the best match for the current protocol and security selections.
        /// </summary>
        private int FindBestUserTokenPolicy(EndpointDescription endpoint)
        {
            // filter by the current token type.
            UserTokenType currentTokenType = UserTokenType.Anonymous;

            if (UserTokenTypeCB.SelectedIndex != -1)
            {
                currentTokenType = (UserTokenType)UserTokenTypeCB.SelectedItem;
            }

            // filter by issued token type.
            string currentIssuedTokenType = (string)IssuedTokenTypeCB.SelectedItem;

            // find all matching descriptions.
            UserTokenPolicyCollection matches = new UserTokenPolicyCollection();

            if (endpoint != null)
            {
                for (int ii = 0; ii < endpoint.UserIdentityTokens.Count; ii++)
                {
                    UserTokenPolicy policy = endpoint.UserIdentityTokens[ii];

                    if (currentTokenType != policy.TokenType)
                    {
                        continue;
                    }

                    if (policy.TokenType == UserTokenType.IssuedToken)
                    {
                        if (currentIssuedTokenType != policy.IssuedTokenType)
                        {
                            continue;
                        }
                    }

                    return(ii);
                }
            }

            return(-1);
        }
        /// <summary>
        /// Returns the UserTokenPolicies supported by the server.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        /// <returns>Returns a collection of UserTokenPolicy objects, the return type is <seealso cref="UserTokenPolicyCollection"/> . </returns>
        public virtual UserTokenPolicyCollection GetUserTokenPolicies(ApplicationConfiguration configuration, EndpointDescription description)
        {
            int policyId = 0;
            UserTokenPolicyCollection policies = new UserTokenPolicyCollection();

            if (configuration.ServerConfiguration == null || configuration.ServerConfiguration.UserTokenPolicies == null)
            {
                return(policies);
            }

            foreach (UserTokenPolicy policy in configuration.ServerConfiguration.UserTokenPolicies)
            {
                UserTokenPolicy clone = (UserTokenPolicy)policy.MemberwiseClone();

                if (String.IsNullOrEmpty(policy.SecurityPolicyUri))
                {
                    // ensure each policy has a unique id.
                    if (description.SecurityMode == MessageSecurityMode.None)
                    {
                        // ensure a security policy is specified for user tokens.
                        clone.SecurityPolicyUri = SecurityPolicies.Basic256;
                        clone.PolicyId          = Utils.Format("{0}", ++policyId);
                    }
                    else
                    {
                        clone.PolicyId = Utils.Format("{0}", policyId++);
                    }

                    policyId++;
                }
                else
                {
                    clone.PolicyId = Utils.Format("{0}", policyId++);
                }

                policies.Add(clone);
            }

            return(policies);
        }
        /// <summary>
        /// Override some of the default user token policies for some endpoints.
        /// </summary>
        /// <remarks>
        /// Sample to show how to override default user token policies.
        /// </remarks>
        public override UserTokenPolicyCollection GetUserTokenPolicies(ApplicationConfiguration configuration, EndpointDescription description)
        {
            var policies = base.GetUserTokenPolicies(configuration, description);

            // sample how to modify default user token policies
            if (description.SecurityPolicyUri == SecurityPolicies.Aes256_Sha256_RsaPss &&
                description.SecurityMode == MessageSecurityMode.SignAndEncrypt)
            {
                policies = new UserTokenPolicyCollection(policies.Where(u => u.TokenType != UserTokenType.Certificate));
            }
            else if (description.SecurityPolicyUri == SecurityPolicies.Aes128_Sha256_RsaOaep &&
                     description.SecurityMode == MessageSecurityMode.Sign)
            {
                policies = new UserTokenPolicyCollection(policies.Where(u => u.TokenType != UserTokenType.Anonymous));
            }
            else if (description.SecurityPolicyUri == SecurityPolicies.Aes128_Sha256_RsaOaep &&
                     description.SecurityMode == MessageSecurityMode.SignAndEncrypt)
            {
                policies = new UserTokenPolicyCollection(policies.Where(u => u.TokenType != UserTokenType.UserName));
            }
            return(policies);
        }
Example #5
0
        /// <summary>
        /// Returns the UserTokenPolicies supported by the server.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        /// <returns>Returns a collection of UserTokenPolicy objects, the return type is <seealso cref="UserTokenPolicyCollection"/> . </returns>
        public virtual UserTokenPolicyCollection GetUserTokenPolicies(ApplicationConfiguration configuration, EndpointDescription description)
        {
            UserTokenPolicyCollection policies = new UserTokenPolicyCollection();

            if (configuration.ServerConfiguration == null || configuration.ServerConfiguration.UserTokenPolicies == null)
            {
                return(policies);
            }

            foreach (UserTokenPolicy policy in configuration.ServerConfiguration.UserTokenPolicies)
            {
                // ensure a security policy is specified for user tokens.
                if (description.SecurityMode == MessageSecurityMode.None)
                {
                    if (String.IsNullOrEmpty(policy.SecurityPolicyUri))
                    {
                        UserTokenPolicy clone = (UserTokenPolicy)policy.MemberwiseClone();
                        clone.SecurityPolicyUri = SecurityPolicies.Basic256;
                        policies.Add(clone);
                        continue;
                    }
                }

                policies.Add(policy);
            }

            // ensure each policy has a unique id.
            for (int ii = 0; ii < policies.Count; ii++)
            {
                if (String.IsNullOrEmpty(policies[ii].PolicyId))
                {
                    policies[ii].PolicyId = Utils.Format("{0}", ii);
                }
            }

            return(policies);
        }
Example #6
0
        private ApplicationConfiguration GetDefaultConfiguration(string url)
        {
            ApplicationConfiguration config = new ApplicationConfiguration();

            // 签名及加密验证
            ServerSecurityPolicyCollection policies = new ServerSecurityPolicyCollection( );

            if (Util.SharpSettings.SecurityPolicyNone)
            {
                policies.Add(new ServerSecurityPolicy( )
                {
                    SecurityMode      = MessageSecurityMode.None,
                    SecurityPolicyUri = SecurityPolicies.None
                });
            }
            if (Util.SharpSettings.SecurityPolicyBasic128_Sign)
            {
                policies.Add(new ServerSecurityPolicy( )
                {
                    SecurityMode      = MessageSecurityMode.Sign,
                    SecurityPolicyUri = SecurityPolicies.Basic128Rsa15
                });
            }
            if (Util.SharpSettings.SecurityPolicyBasic128_Sign_Encrypt)
            {
                policies.Add(new ServerSecurityPolicy( )
                {
                    SecurityMode      = MessageSecurityMode.SignAndEncrypt,
                    SecurityPolicyUri = SecurityPolicies.Basic128Rsa15
                });
            }
            if (Util.SharpSettings.SecurityPolicyBasic256_Sign)
            {
                policies.Add(new ServerSecurityPolicy( )
                {
                    SecurityMode      = MessageSecurityMode.Sign,
                    SecurityPolicyUri = SecurityPolicies.Basic256
                });
            }
            if (Util.SharpSettings.SecurityPolicyBasic256_Sign_Encrypt)
            {
                policies.Add(new ServerSecurityPolicy( )
                {
                    SecurityMode      = MessageSecurityMode.SignAndEncrypt,
                    SecurityPolicyUri = SecurityPolicies.Basic256
                });
            }

            // 用户名验证
            UserTokenPolicyCollection userTokens = new UserTokenPolicyCollection( );

            if (Util.SharpSettings.SecurityAnonymous)
            {
                userTokens.Add(new UserTokenPolicy(UserTokenType.Anonymous));
            }
            if (Util.SharpSettings.SecurityAccount)
            {
                userTokens.Add(new UserTokenPolicy(UserTokenType.UserName));
            }


            config.ApplicationName = "OpcUaServer";
            config.ApplicationType = ApplicationType.Server;


            config.SecurityConfiguration = new SecurityConfiguration()
            {
                ApplicationCertificate = new CertificateIdentifier()
                {
                    StoreType   = "Directory",
                    StorePath   = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault",
                    SubjectName = config.ApplicationName,
                },

                TrustedPeerCertificates = new CertificateTrustList()
                {
                    StoreType = "Directory",
                    StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications",
                },

                TrustedIssuerCertificates = new CertificateTrustList()
                {
                    StoreType = "Directory",
                    StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities",
                },

                RejectedCertificateStore = new CertificateStoreIdentifier()
                {
                    StoreType = "Directory",
                    StorePath = @"% CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates"
                }
            };
            config.TransportConfigurations = new TransportConfigurationCollection();
            config.TransportQuotas         = new TransportQuotas();

            config.ServerConfiguration = new ServerConfiguration( )
            {
                // 配置登录的地址
                BaseAddresses = new string[]
                {
                    url
                },

                SecurityPolicies = policies,

                UserTokenPolicies = userTokens,

                DiagnosticsEnabled           = false,  // 是否启用诊断
                MaxSessionCount              = 1000,   // 最大打开会话数
                MinSessionTimeout            = 10000,  // 允许该会话在与客户端断开时(单位毫秒)仍然保持连接的最小时间
                MaxSessionTimeout            = 60000,  // 允许该会话在与客户端断开时(单位毫秒)仍然保持连接的最大时间
                MaxBrowseContinuationPoints  = 1000,   // 用于Browse / BrowseNext操作的连续点的最大数量。
                MaxQueryContinuationPoints   = 1000,   // 用于Query / QueryNext操作的连续点的最大数量
                MaxHistoryContinuationPoints = 500,    // 用于HistoryRead操作的最大连续点数。
                MaxRequestAge               = 1000000, // 传入请求的最大年龄(旧请求被拒绝)。
                MinPublishingInterval       = 100,     // 服务器支持的最小发布间隔(以毫秒为单位)
                MaxPublishingInterval       = 3600000, // 服务器支持的最大发布间隔(以毫秒为单位)1小时
                PublishingResolution        = 50,      // 支持的发布间隔(以毫秒为单位)的最小差异
                MaxSubscriptionLifetime     = 3600000, // 订阅将在没有客户端发布的情况下保持打开多长时间 1小时
                MaxMessageQueueSize         = 100,     // 每个订阅队列中保存的最大消息数
                MaxNotificationQueueSize    = 100,     // 为每个被监视项目保存在队列中的最大证书数
                MaxNotificationsPerPublish  = 1000,    // 每次发布的最大通知数
                MinMetadataSamplingInterval = 1000,    // 元数据的最小采样间隔
                AvailableSamplingRates      = new SamplingRateGroupCollection(new List <SamplingRateGroup>()
                {
                    new SamplingRateGroup(5, 5, 20),
                    new SamplingRateGroup(100, 100, 4),
                    new SamplingRateGroup(500, 250, 2),
                    new SamplingRateGroup(1000, 500, 20),
                }),                                // 可用的采样率
                MaxRegistrationInterval = 30000,   // 两次注册尝试之间的最大时间(以毫秒为单位)
                //NodeManagerSaveFile = string.Empty,// 包含节点的文件的路径由核心节点管理器持久化 ??
            };



            config.CertificateValidator = new CertificateValidator();
            config.CertificateValidator.Update(config);
            config.Extensions = new XmlElementCollection();

            return(config);
        }
Example #7
0
        /// <summary>
        /// Returns the UserTokenPolicies supported by the server.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        /// <returns>Returns a collection of UserTokenPolicy objects, the return type is <seealso cref="UserTokenPolicyCollection"/> . </returns>
        protected virtual UserTokenPolicyCollection GetUserTokenPolicies(ApplicationConfiguration configuration, EndpointDescription description)
        {
            UserTokenPolicyCollection policies = new UserTokenPolicyCollection();

            if (configuration.ServerConfiguration == null || configuration.ServerConfiguration.UserTokenPolicies == null)
            {
                return policies;
            }

            foreach (UserTokenPolicy policy in configuration.ServerConfiguration.UserTokenPolicies)
            {
                // ensure a security policy is specified for user tokens.
                if (description.SecurityMode == MessageSecurityMode.None)
                {
                    if (String.IsNullOrEmpty(policy.SecurityPolicyUri))
                    {
                        UserTokenPolicy clone = (UserTokenPolicy)policy.Clone();
                        clone.SecurityPolicyUri = SecurityPolicies.Basic256;
                        policies.Add(clone);
                        continue;
                    }
                }

                policies.Add(policy);
            }

            // ensure each policy has a unique id.
            for (int ii = 0; ii < policies.Count; ii++)
            {
                if (String.IsNullOrEmpty(policies[ii].PolicyId))
                {
                    policies[ii].PolicyId = Utils.Format("{0}", ii);
                }
            }

            return policies;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientSecurityConfiguration"/> class.
        /// </summary>
        /// <param name="mode">The message security mode</param>
        /// <param name="policyUri">The Uri to the security policy</param>
        /// <param name="username">The username, leave blank to use ananoymous access</param>
        /// <param name="password">The password, leave blank to use anonymous access</param>
        /// <param name="userTokenPolicies">A collection of user token policies that may be used, to identify is anonymous login is allowed</param>
        public ClientSecurityConfiguration(MessageSecurityMode mode, string policyUri = "", string username = "", string password = "", UserTokenPolicyCollection userTokenPolicies = null)
        {
            this.securityMode      = mode;
            this.securityPolicyUri = policyUri;
            this.username          = username;
            this.password          = password;

            if (userTokenPolicies != null)
            {
                foreach (var token in userTokenPolicies)
                {
                    if (token.TokenType == UserTokenType.Anonymous)
                    {
                        this.anonymousAccessAllowed = true;
                        break;
                    }
                }
            }
        }
        public async Task <ConnectionStatus> OpcClient(string endpointURL)
        {
            try
            {
                Uri endpointURI      = new Uri(endpointURL);
                var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointURL, false, 15000);

                info.LabelText = "Selected endpoint uses: " + selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1);

                var endpointConfiguration = EndpointConfiguration.Create(config);
                var endpoint = new ConfiguredEndpoint(selectedEndpoint.Server, endpointConfiguration);
                endpoint.Update(selectedEndpoint);

                var platform    = Device.RuntimePlatform;
                var sessionName = "";

                switch (Device.RuntimePlatform)
                {
                case "Android":
                    sessionName = "AIS Demonstrator Android Applikation";
                    break;

                // other cases are irrelevant for the Industrie 4.0 Demonstrator as of now
                case "UWP":
                    sessionName = "OPC UA Xamarin Client UWP";
                    break;

                case "iOS":
                    sessionName = "OPC UA Xamarin Client IOS";
                    break;
                }
                #region OPC UA User Authentication handling

                /*
                 * Partially copied from https://github.com/OPCFoundation/UA-.NETStandard/issues/446
                 */
                UserTokenPolicy utp = new UserTokenPolicy();
                utp.TokenType = UserTokenType.UserName;

                UserTokenPolicyCollection utpCollection = new UserTokenPolicyCollection();
                utpCollection.Add(utp);
                selectedEndpoint.UserIdentityTokens = utpCollection;
                selectedEndpoint.SecurityMode       = MessageSecurityMode.SignAndEncrypt;
                UserIdentity SessionUserIdentity = new UserIdentity(MainActivity.UserName, MainActivity.UserPassword);

                #endregion
                session = await Session.Create(config, endpoint, false, sessionName, 30000, SessionUserIdentity, null);


                if (session != null)
                {
                    connectionStatus = ConnectionStatus.Connected;

                    #region Subscription + monitoredItems
                    // Code for Monitored Items based on http://opcfoundation.github.io/UA-.NETStandard/help/index.htm#client_development.htm

                    // Create Subscription
                    Subscription subscription = new Subscription() // new Subscription(OpcClient.session.DefaultSubscription)
                    {
                        PublishingInterval = 1000,
                        PublishingEnabled  = true
                    };
                    // CoffeeLevel
                    MonitoredItem CoffeeLevel = new MonitoredItem(subscription.DefaultItem)
                    {
                        StartNodeId      = "ns=1;s=CoffeeLevel",
                        DisplayName      = "MonitoredCoffeeLevel",
                        AttributeId      = Attributes.Value,
                        MonitoringMode   = MonitoringMode.Reporting,
                        SamplingInterval = 1000, // check the CoffeeLevel every second
                        QueueSize        = 1,    // only the most recent value for the CoffeeLevel is needed, thus we only need a queuesize of one
                        DiscardOldest    = true  // we only need the most recent value for CoffeeLevel
                    };
                    CoffeeLevel.Notification += (sender, e) => OnNotification(sender, e, ref valueCoffeeLevel);

                    // WaterLevel
                    MonitoredItem WaterLevel = new MonitoredItem(subscription.DefaultItem)
                    {
                        StartNodeId      = "ns=1;s=WaterLevel",
                        DisplayName      = "MonitoredWaterLevel",
                        AttributeId      = Attributes.Value,
                        MonitoringMode   = MonitoringMode.Reporting,
                        SamplingInterval = 1000, // check the CoffeeLevel every second
                        QueueSize        = 1,    // only the most recent value for the CoffeeLevel is needed, thus we only need a queuesize of one
                        DiscardOldest    = true  // we only need the most recent value for CoffeeLevel
                    };
                    WaterLevel.Notification += (sender, e) => OnNotification(sender, e, ref valueWaterLevel);

                    // CleanlinessLevel
                    MonitoredItem CleanlinessLevel = new MonitoredItem(subscription.DefaultItem)
                    {
                        StartNodeId      = "ns=1;s=Cleanliness",
                        DisplayName      = "MonitoredCleanlinessLevel",
                        AttributeId      = Attributes.Value,
                        MonitoringMode   = MonitoringMode.Reporting,
                        SamplingInterval = 1000, // check the CoffeeLevel every second
                        QueueSize        = 1,    // only the most recent value for the CoffeeLevel is needed, thus we only need a queuesize of one
                        DiscardOldest    = true  // we only need the most recent value for CoffeeLevel
                    };
                    CleanlinessLevel.Notification += (sender, e) => OnNotification(sender, e, ref valueCleanlinessLevel);

                    // add MonitoredItems to Subscription
                    subscription.AddItem(CoffeeLevel);
                    subscription.AddItem(WaterLevel);
                    subscription.AddItem(CleanlinessLevel);

                    // add Subscription to Session
                    session.AddSubscription(subscription);
                    subscription.Create();

                    #endregion
                }
                else
                {
                    connectionStatus = ConnectionStatus.NotConnected;
                }
                // register keep alive handler
                session.KeepAlive += Client_KeepAlive;
            }
            catch
            {
                connectionStatus = ConnectionStatus.Error;
            }
            return(connectionStatus);
        }
        /// <summary>
        /// Finds the best match for the current protocol and security selections.
        /// </summary>
        private int FindBestUserTokenPolicy(EndpointDescription endpoint)
        {
            // filter by the current token type.
            UserTokenItem currentTokenType = new UserTokenItem(UserTokenType.Anonymous);

            if (UserTokenTypeCB.SelectedIndex != -1)
            {
                currentTokenType = (UserTokenItem)UserTokenTypeCB.SelectedItem;
            }

            // filter by issued token type.
            string currentIssuedTokenType = (string)IssuedTokenTypeCB.SelectedItem;

            // find all matching descriptions.      
            UserTokenPolicyCollection matches = new UserTokenPolicyCollection();

            if (endpoint != null)
            {
                for (int ii = 0; ii < endpoint.UserIdentityTokens.Count; ii++)
                {
                    UserTokenPolicy policy = endpoint.UserIdentityTokens[ii];

                    if (currentTokenType.Policy.PolicyId == policy.PolicyId)
                    {
                        return ii;
                    }
                }

                for (int ii = 0; ii < endpoint.UserIdentityTokens.Count; ii++)
                {
                    UserTokenPolicy policy = endpoint.UserIdentityTokens[ii];

                    if (currentTokenType.Policy.TokenType != policy.TokenType)
                    {
                        continue;
                    }

                    if (policy.TokenType == UserTokenType.IssuedToken)
                    {
                        if (currentIssuedTokenType != policy.IssuedTokenType)
                        {
                            continue;
                        }
                    }

                    return ii;
                }
            }

            return -1;
        }