opc服务端

OpcUaServer.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
using Opc.Ua;
using Opc.Ua.Configuration;
using Opc.Ua.Server;
using System.Security.Cryptography.X509Certificates;
 
namespace OpcServerCore.Util
{
    public class OpcUaServer : StandardServer
    
        public ApplicationInstance Application { get; private set; }
 
        public bool AutoAccept { get; set; }
 
        /// <summary>
        /// 认证方式
        /// </summary>
        public UserTokenType UserTokenType { get; set; }
 
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; } = "admin";
 
        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; } = "123456";
 
        ICertificateValidator m_userCertificateValidator;
 
        public OpcUaNodeManager OpcuaNode1 { get; set; }
 
        protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration)
        {
            OpcuaNode1 = new OpcUaNodeManager(server, configuration);
 
            List<INodeManager> nodeManagers = new List<INodeManager>();
            nodeManagers.Add(OpcuaNode1);
 
            return new MasterNodeManager(server, configuration, null, nodeManagers.ToArray());
        }
 
        public async Task LoadAsync(string applicationName, string configSectionName)
        {
            try
            {
                CertificatePasswordProvider passwordProvider = new CertificatePasswordProvider(Password);
 
                Application = new ApplicationInstance
                {
                    ApplicationName = applicationName,
                    ApplicationType = ApplicationType.Server,
                    ConfigSectionName = configSectionName,
                    CertificatePasswordProvider = passwordProvider
                };
 
                await Application.LoadApplicationConfiguration(false);
            }
            catch (Exception ex)
            {
                throw new Exception($"Load async error: {ex.Message}", ex);
            }
        }
          
        public async Task CheckCertificateAsync(bool renewCertificate)
        {
            try
            {
                ApplicationConfiguration config = Application.ApplicationConfiguration;
 
                if (renewCertificate)
                {
                    await Application.DeleteApplicationInstanceCertificate();
                }
 
                bool haveAppCertificate = await Application.CheckApplicationInstanceCertificate(false, minimumKeySize: 0);
                if (!haveAppCertificate)
                {
                    throw new Exception("Application instance certificate invalid!");
                }
 
                if (!config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                    config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
                }
 
                // 指定认证方式
                config.ServerConfiguration.UserTokenPolicies.Clear();
                UserTokenPolicy utp = new UserTokenPolicy();
                utp.TokenType = UserTokenType;
                utp.PolicyId = utp.TokenType.ToString();
                config.ServerConfiguration.UserTokenPolicies.Add(utp);
 
                for (int ii = 0; ii < config.ServerConfiguration.UserTokenPolicies.Count; ii++)
                {
                    UserTokenPolicy policy = config.ServerConfiguration.UserTokenPolicies[ii];
 
                    if (policy.TokenType == UserTokenType.Certificate)
                    {
                        if (config.SecurityConfiguration.TrustedUserCertificates != null && config.SecurityConfiguration.UserIssuerCertificates != null)
                        {
                            CertificateValidator certificateValidator = new CertificateValidator();
                            certificateValidator.Update(config.SecurityConfiguration).Wait();
                            certificateValidator.Update(config.SecurityConfiguration.UserIssuerCertificates, config.SecurityConfiguration.TrustedUserCertificates, config.SecurityConfiguration.RejectedCertificateStore);
                            m_userCertificateValidator = certificateValidator.GetChannelValidator();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"CheckCertificateAsync: {ex.Message}", ex);
            }
        }
 
        /// <summary>
        /// Create server instance and add node managers.
        /// </summary>
        public void Create(IList<INodeManagerFactory> nodeManagerFactories)
        {
            try
            {
                if (nodeManagerFactories != null)
                {
                    foreach (INodeManagerFactory factory in nodeManagerFactories)
                    {
                        this.AddNodeManager(factory);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Create Node manager Factories: {ex.Message}", ex);
            }
        }
 
        /// <summary>
        /// Start the server.
        /// </summary>
        public async Task StartAsync()
        {
            try
            {
                await Application.Start(this);
 
                this.CurrentInstance.SessionManager.ImpersonateUser += new ImpersonateEventHandler(ImpersonateUser);
                this.CurrentInstance.SessionManager.SessionActivated += EventStatus;
                this.CurrentInstance.SessionManager.SessionClosing += EventStatus;
                this.CurrentInstance.SessionManager.SessionCreated += EventStatus;
            }
            catch (Exception ex)
            {
                throw new Exception($"Start async: {ex.Message}", ex);
            }
        }
 
        /// <summary>
        /// Stops the server.
        /// </summary>
        public async Task StopAsync()
        {
            try
            {
                this.Stop();
            }
            catch (Exception ex)
            {
                throw new Exception($"Stop async: {ex.Message}", ex);
            }
        }
 
        /// <summary>
        /// The certificate validator is used
        /// if auto accept is not selected in the configuration.
        /// </summary>
        private void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e)
        {
            if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted)
            {
                if (AutoAccept)
                {
                    Logger.Info($"Accepted Certificate: [{e.Certificate.Subject}] [{e.Certificate.Thumbprint}]");
                    e.Accept = true;
                    return;
                }
            }
            Logger.Info($"Rejected Certificate: {e.Error} [{e.Certificate.Subject}] [{e.Certificate.Thumbprint}]");
        }
 
        private void EventStatus(Session session, SessionEventReason reason)
        {
              
        }
 
        private void ImpersonateUser(Session session, ImpersonateEventArgs args)
        {
            UserNameIdentityToken? userNameToken = args.NewIdentity as UserNameIdentityToken;
 
            if (userNameToken != null)
            {
                args.Identity = VerifyPassword(userNameToken);
                return;
            }
 
            X509IdentityToken? x509Token = args.NewIdentity as X509IdentityToken;
 
            if (x509Token != null)
            {
                VerifyUserTokenCertificate(x509Token.Certificate);
                args.Identity = new UserIdentity(x509Token);
                Utils.Trace("X509 Token Accepted: {0}", args.Identity.DisplayName);
                return;
            }
        }
 
        /// <summary>
        /// Validates the password for a username token.
        /// </summary>
        private IUserIdentity VerifyPassword(UserNameIdentityToken userNameToken)
        {
            var userName = userNameToken.UserName;
            var password = userNameToken.DecryptedPassword;
 
            if (string.IsNullOrEmpty(userName))
            {
                throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "Security token is not a valid username token. An empty username is not accepted.");
            }
 
            if (string.IsNullOrEmpty(password))
            {
                throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Security token is not a valid username token. An empty password is not accepted.");
            }
 
            if (!(userName == "admin" && password == "123456"))
            {
                TranslationInfo info = new TranslationInfo("InvalidPassword", "en-US", "Invalid username or password.", userName);
                throw new ServiceResultException(new ServiceResult(StatusCodes.BadUserAccessDenied, "InvalidPassword", "http://opcfoundation.org/Quickstart/ReferenceServer/v1.03", new LocalizedText(info)));
            }
 
            return new UserIdentity(userNameToken);
        }
 
        /// <summary>
        /// Verifies that a certificate user token is trusted.
        /// </summary>
        private void VerifyUserTokenCertificate(X509Certificate2 certificate)
        {
            try
            {
                if (m_userCertificateValidator != null)
                {
                    m_userCertificateValidator.Validate(certificate);
                }
                else
                {
                    new CertificateValidator().Validate(certificate);
                }
            }
            catch (Exception e)
            {
                TranslationInfo info;
                StatusCode result = StatusCodes.BadIdentityTokenRejected;
                ServiceResultException se = e as ServiceResultException;
                if (se != null && se.StatusCode == StatusCodes.BadCertificateUseNotAllowed)
                {
                    info = new TranslationInfo("InvalidCertificate", "en-US", "'{0}' is an invalid user certificate.", certificate.Subject);
                    result = StatusCodes.BadIdentityTokenInvalid;
                }
                else
                {
                    info = new TranslationInfo("UntrustedCertificate", "en-US", "'{0}' is not a trusted user certificate.", certificate.Subject);
                }
                throw new ServiceResultException(new ServiceResult(result, info.Key, "http://opcfoundation.org/Quickstart/ReferenceServer/v1.04", new LocalizedText(info)));
            }
        }
    }
}

  

 

posted @   CHHC  阅读(81)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示