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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use std::sync::{Arc, RwLock};
use opcua_core::prelude::*;
use opcua_types::node_ids::ObjectId;
use opcua_types::profiles;
use opcua_types::service_types::{ApplicationDescription, RegisteredServer, ApplicationType, EndpointDescription, UserNameIdentityToken, UserTokenPolicy, UserTokenType, X509IdentityToken};
use opcua_types::service_types::ServerState as ServerStateType;
use opcua_types::status_code::StatusCode;
use crate::config::{ServerConfig, ServerEndpoint};
use crate::diagnostics::ServerDiagnostics;
const TOKEN_POLICY_ANONYMOUS: &str = "anonymous";
const TOKEN_POLICY_USER_PASS_PLAINTEXT: &str = "userpass_plaintext";
pub struct ServerState {
pub application_uri: UAString,
pub product_uri: UAString,
pub application_name: LocalizedText,
pub base_endpoint: String,
pub start_time: DateTime,
pub namespaces: Vec<String>,
pub servers: Vec<String>,
pub config: Arc<RwLock<ServerConfig>>,
pub server_certificate: Option<X509>,
pub server_pkey: Option<PrivateKey>,
pub last_subscription_id: u32,
pub max_subscriptions: usize,
pub min_publishing_interval: Duration,
pub default_keep_alive_count: u32,
pub max_keep_alive_count: u32,
pub max_lifetime_count: u32,
pub state: ServerStateType,
pub abort: bool,
pub diagnostics: Arc<RwLock<ServerDiagnostics>>,
}
impl ServerState {
pub fn endpoints(&self, transport_profile_uris: &Option<Vec<UAString>>) -> Option<Vec<EndpointDescription>> {
debug!("Endpoints requested {:?}", transport_profile_uris);
if let Some(ref transport_profile_uris) = *transport_profile_uris {
if !transport_profile_uris.is_empty() {
let found_binary_transport = transport_profile_uris.iter().find(|profile_uri| {
profile_uri.as_ref() == profiles::TRANSPORT_PROFILE_URI_BINARY
});
if found_binary_transport.is_none() {
error!("Client wants to connect with a non binary transport {:#?}", transport_profile_uris);
return None;
}
}
}
let config = trace_read_lock_unwrap!(self.config);
Some(config.endpoints.iter().map(|(_, e)| {
self.new_endpoint_description(&config, e, true)
}).collect())
}
pub fn endpoint_exists(&self, endpoint_url: &str, security_policy: SecurityPolicy, security_mode: MessageSecurityMode) -> bool {
let config = trace_read_lock_unwrap!(self.config);
config.find_endpoint(endpoint_url, security_policy, security_mode).is_some()
}
pub fn new_endpoint_descriptions(&self, endpoint_url: &str) -> Option<Vec<EndpointDescription>> {
debug!("find_endpoint, url = {}", endpoint_url);
let config = trace_read_lock_unwrap!(self.config);
let base_endpoint_url = config.base_endpoint_url();
let endpoints: Vec<EndpointDescription> = config.endpoints.iter().filter(|&(_, e)| {
url_matches_except_host(&e.endpoint_url(&base_endpoint_url), endpoint_url)
}).map(|(_, e)| self.new_endpoint_description(&config, e, false)).collect();
if endpoints.is_empty() { None } else { Some(endpoints) }
}
fn new_endpoint_description(&self, config: &ServerConfig, endpoint: &ServerEndpoint, all_fields: bool) -> EndpointDescription {
let base_endpoint_url = config.base_endpoint_url();
let mut user_identity_tokens = Vec::with_capacity(2);
if endpoint.supports_anonymous() {
user_identity_tokens.push(UserTokenPolicy {
policy_id: UAString::from(TOKEN_POLICY_ANONYMOUS),
token_type: UserTokenType::Anonymous,
issued_token_type: UAString::null(),
issuer_endpoint_url: UAString::null(),
security_policy_uri: UAString::null(),
});
}
if !endpoint.user_token_ids.is_empty() {
user_identity_tokens.push(UserTokenPolicy {
policy_id: UAString::from(TOKEN_POLICY_USER_PASS_PLAINTEXT),
token_type: UserTokenType::Username,
issued_token_type: UAString::null(),
issuer_endpoint_url: UAString::null(),
security_policy_uri: UAString::from(SecurityPolicy::None.to_uri()),
});
}
let (server, server_certificate) = if all_fields {
(ApplicationDescription {
application_uri: self.application_uri.clone(),
product_uri: self.product_uri.clone(),
application_name: self.application_name.clone(),
application_type: self.application_type(),
gateway_server_uri: self.gateway_server_uri(),
discovery_profile_uri: UAString::null(),
discovery_urls: self.discovery_urls(),
}, self.server_certificate_as_byte_string())
} else {
(ApplicationDescription {
application_uri: UAString::null(),
product_uri: UAString::null(),
application_name: LocalizedText::null(),
application_type: self.application_type(),
gateway_server_uri: self.gateway_server_uri(),
discovery_profile_uri: UAString::null(),
discovery_urls: self.discovery_urls(),
}, ByteString::null())
};
EndpointDescription {
endpoint_url: endpoint.endpoint_url(&base_endpoint_url).into(),
server,
server_certificate,
security_mode: endpoint.message_security_mode(),
security_policy_uri: UAString::from(endpoint.security_policy().to_uri()),
user_identity_tokens: Some(user_identity_tokens),
transport_profile_uri: UAString::from(profiles::TRANSPORT_PROFILE_URI_BINARY),
security_level: endpoint.security_level,
}
}
pub fn discovery_urls(&self) -> Option<Vec<UAString>> {
let config = trace_read_lock_unwrap!(self.config);
if config.discovery_url.is_empty() {
None
} else {
Some(vec![UAString::from(config.discovery_url.as_ref())])
}
}
pub fn application_type(&self) -> ApplicationType { ApplicationType::Server }
pub fn gateway_server_uri(&self) -> UAString { UAString::null() }
pub fn abort(&mut self) {
info!("Server has been told to abort");
self.abort = true;
self.state = ServerStateType::Shutdown;
}
pub fn state(&self) -> ServerStateType { self.state }
pub fn set_state(&mut self, state: ServerStateType) {
self.state = state;
}
pub fn is_abort(&self) -> bool { self.abort }
pub fn is_running(&self) -> bool { self.state == ServerStateType::Running }
pub fn server_certificate_as_byte_string(&self) -> ByteString {
if let Some(ref server_certificate) = self.server_certificate {
server_certificate.as_byte_string()
} else {
ByteString::null()
}
}
pub fn registered_server(&self) -> RegisteredServer {
let server_uri = self.application_uri.clone();
let product_uri = self.product_uri.clone();
let gateway_server_uri = self.gateway_server_uri();
let discovery_urls = self.discovery_urls();
let server_type = self.application_type();
let is_online = self.is_running();
let server_names = Some(vec![self.application_name.clone()]);
RegisteredServer {
server_uri,
product_uri,
server_names,
server_type,
gateway_server_uri,
discovery_urls,
semaphore_file_path: UAString::null(),
is_online,
}
}
pub fn create_subscription_id(&mut self) -> u32 {
self.last_subscription_id += 1;
self.last_subscription_id
}
pub fn authenticate_endpoint(&self, endpoint_url: &str, security_policy: SecurityPolicy, security_mode: MessageSecurityMode, user_identity_token: &ExtensionObject) -> StatusCode {
let config = trace_read_lock_unwrap!(self.config);
let decoding_limits = config.decoding_limits();
if let Some(endpoint) = config.find_endpoint(endpoint_url, security_policy, security_mode) {
if user_identity_token.is_null() || user_identity_token.is_empty() {
Self::authenticate_anonymous_token(endpoint)
} else {
if let Ok(object_id) = user_identity_token.node_id.as_object_id() {
match object_id {
ObjectId::AnonymousIdentityToken_Encoding_DefaultBinary => {
Self::authenticate_anonymous_token(endpoint)
}
ObjectId::UserNameIdentityToken_Encoding_DefaultBinary => {
let result = user_identity_token.decode_inner::<UserNameIdentityToken>(&decoding_limits);
if let Ok(token) = result {
self.authenticate_username_identity_token(&config, endpoint, &token)
} else {
error!("User name identity token could not be decoded");
StatusCode::BadIdentityTokenInvalid
}
}
ObjectId::X509IdentityToken_Encoding_DefaultBinary => {
let result = user_identity_token.decode_inner::<X509IdentityToken>(&decoding_limits);
if let Ok(_) = result {
error!("X509 identity token type is not supported");
StatusCode::BadIdentityTokenRejected
} else {
error!("X509 identity token could not be decoded");
StatusCode::BadIdentityTokenInvalid
}
}
_ => {
error!("User identity token type {:?} is unrecognized", object_id);
StatusCode::BadIdentityTokenInvalid
}
}
} else {
error!("Cannot read user identity token");
StatusCode::BadIdentityTokenInvalid
}
}
} else {
error!("Cannot find endpoint that matches path \"{}\", security policy {:?}, and security mode {:?}", endpoint_url, security_policy, security_mode);
StatusCode::BadTcpEndpointUrlInvalid
}
}
fn authenticate_anonymous_token(endpoint: &ServerEndpoint) -> StatusCode {
if endpoint.supports_anonymous() {
debug!("Anonymous identity is authenticated");
StatusCode::Good
} else {
error!("Endpoint \"{}\" does not support anonymous authentication", endpoint.path);
StatusCode::BadIdentityTokenRejected
}
}
fn authenticate_username_identity_token(&self, config: &ServerConfig, endpoint: &ServerEndpoint, token: &UserNameIdentityToken) -> StatusCode {
if !token.encryption_algorithm.is_null() {
error!("Only unencrypted passwords are supported, {:?}", token);
StatusCode::BadIdentityTokenInvalid
} else if token.user_name.is_null() {
error!("User identify token supplies no user name");
StatusCode::BadIdentityTokenInvalid
} else {
for user_token_id in &endpoint.user_token_ids {
if let Some(server_user_token) = config.user_tokens.get(user_token_id) {
if &server_user_token.user == token.user_name.as_ref() {
let result = if server_user_token.pass.is_none() {
token.authenticate(&server_user_token.user, b"")
} else {
let server_password = server_user_token.pass.as_ref().unwrap().as_bytes();
token.authenticate(&server_user_token.user, server_password)
};
let valid = result.is_ok();
if !valid {
error!("Cannot authenticate \"{}\", password is invalid", server_user_token.user);
return StatusCode::BadIdentityTokenRejected;
} else {
return StatusCode::Good;
}
}
}
}
error!("Cannot authenticate \"{}\", user not found for endpoint", token.user_name);
StatusCode::BadIdentityTokenRejected
}
}
}