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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//! Provides server state information, such as status, configuration, running servers and so on.

use std::sync::{Arc, RwLock};

use opcua_core::prelude::*;

use opcua_types::{
    node_ids::ObjectId,
    profiles,
    service_types::{
        ApplicationDescription, RegisteredServer, ApplicationType, EndpointDescription,
        UserNameIdentityToken, UserTokenPolicy, UserTokenType, X509IdentityToken,
        ServerState as ServerStateType,
    },
    status_code::StatusCode,
};

use crate::config::{ServerConfig, ServerEndpoint};
use crate::diagnostics::ServerDiagnostics;
use crate::callbacks::{RegisterNodes, UnregisterNodes};

const TOKEN_POLICY_ANONYMOUS: &str = "anonymous";
const TOKEN_POLICY_USER_PASS_PLAINTEXT: &str = "userpass_plaintext";

/// Server state is any state associated with the server as a whole that individual sessions might
/// be interested in. That includes configuration info etc.
pub struct ServerState {
    /// The application URI
    pub application_uri: UAString,
    /// The product URI
    pub product_uri: UAString,
    /// The application name
    pub application_name: LocalizedText,
    /// The protocol, hostname and port formatted as a url, but less the path
    pub base_endpoint: String,
    /// The time the server started
    pub start_time: DateTime,
    /// The list of namespaces
    pub namespaces: Vec<String>,
    /// The list of servers (by urn)
    pub servers: Vec<String>,
    /// Server configuration
    pub config: Arc<RwLock<ServerConfig>>,
    /// Server public certificate read from config location or null if there is none
    pub server_certificate: Option<X509>,
    /// Server private key
    pub server_pkey: Option<PrivateKey>,
    /// The next subscription id - subscriptions are shared across the whole server. Initial value
    /// is a random u32.
    pub last_subscription_id: u32,
    /// Maximum number of subscriptions per session, 0 means no limit (danger)
    pub max_subscriptions: usize,
    /// Minimum publishing interval
    pub min_publishing_interval: Duration,
    /// Default keep alive count
    pub default_keep_alive_count: u32,
    /// Maxmimum keep alive count
    pub max_keep_alive_count: u32,
    /// Maximum lifetime count (3 times as large as max keep alive)
    pub max_lifetime_count: u32,
    /// Limits on method service
    pub max_method_calls: usize,
    /// Limits on node management service
    pub max_nodes_per_node_management: usize,
    /// Limits on view service
    pub max_browse_paths_per_translate: usize,
    //// Current state
    pub state: ServerStateType,
    /// Sets the abort flag that terminates the associated server
    pub abort: bool,
    /// Diagnostic information
    pub diagnostics: Arc<RwLock<ServerDiagnostics>>,
    /// Callback for register nodes
    pub(crate) register_nodes_callback: Option<Box<RegisterNodes + Send + Sync>>,
    /// Callback for unregister nodes
    pub(crate) unregister_nodes_callback: Option<Box<UnregisterNodes + Send + Sync>>,

}

impl ServerState {
    pub fn endpoints(&self, transport_profile_uris: &Option<Vec<UAString>>) -> Option<Vec<EndpointDescription>> {
        // Filter endpoints based on profile_uris
        debug!("Endpoints requested {:?}", transport_profile_uris);
        if let Some(ref transport_profile_uris) = *transport_profile_uris {
            if !transport_profile_uris.is_empty() {
                // As we only support binary transport, the result is None if the supplied profile_uris does not contain that profile
                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;
                }
            }
        }
        // Return the endpoints
        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()
    }

    /// Make matching endpoint descriptions for the specified url.
    /// If none match then None will be passed, therefore if Some is returned it will be guaranteed
    /// to contain at least one result.
    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)| {
            // Test end point's security_policy_uri and matching url
            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) }
    }

    /// Constructs a new endpoint description using the server's info and that in an Endpoint
    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()),
            });
        }

        // CreateSession doesn't need all the endpoint description
        // and docs say not to bother sending the server and server
        // certificate info.
        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_urls.is_empty() {
            None
        } else {
            Some(config.discovery_urls.iter().map(|url| UAString::from(url.as_ref())).collect())
        }
    }

    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 max_method_calls(&self) -> usize {
        self.max_method_calls
    }

    pub fn max_nodes_per_node_management(&self) -> usize {
        self.max_nodes_per_node_management
    }

    pub fn max_browse_paths_per_translate(&self) -> usize {
        self.max_browse_paths_per_translate
    }

    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()]);
        // Server names
        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
    }

    /// Authenticates access to an endpoint. The endpoint is described by its path, policy, mode and
    /// the token is supplied in an extension object that must be extracted and authenticated.
    ///
    /// It is possible that the endpoint does not exist, or that the token is invalid / unsupported
    /// or that the token cannot be used with the end point. The return codes reflect the responses
    /// that ActivateSession would expect from a service call.
    pub fn authenticate_endpoint(&self, endpoint_url: &str, security_policy: SecurityPolicy, security_mode: MessageSecurityMode, user_identity_token: &ExtensionObject) -> StatusCode {
        // Get security from endpoint url
        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) {
            // Now validate the user identity token
            if user_identity_token.is_null() || user_identity_token.is_empty() {
                // Empty tokens are treated as anonymous
                Self::authenticate_anonymous_token(endpoint)
            } else {
                // Read the token out from the extension object
                if let Ok(object_id) = user_identity_token.node_id.as_object_id() {
                    match object_id {
                        ObjectId::AnonymousIdentityToken_Encoding_DefaultBinary => {
                            // Anonymous
                            Self::authenticate_anonymous_token(endpoint)
                        }
                        ObjectId::UserNameIdentityToken_Encoding_DefaultBinary => {
                            // Username / password
                            let result = user_identity_token.decode_inner::<UserNameIdentityToken>(&decoding_limits);
                            if let Ok(token) = result {
                                self.authenticate_username_identity_token(&config, endpoint, &token)
                            } else {
                                // Garbage in the extension object
                                error!("User name identity token could not be decoded");
                                StatusCode::BadIdentityTokenInvalid
                            }
                        }
                        ObjectId::X509IdentityToken_Encoding_DefaultBinary => {
                            // X509 certs could be recognized here
                            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 {
                                // Garbage in the extension object
                                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
        }
    }

    pub fn set_register_nodes_callbacks(&mut self, register_nodes_callback: Box<RegisterNodes + Send + Sync>, unregister_nodes_callback: Box<UnregisterNodes + Send + Sync>) {
        self.register_nodes_callback = Some(register_nodes_callback);
        self.unregister_nodes_callback = Some(unregister_nodes_callback);
    }

    /// Authenticates an anonymous token, i.e. does the endpoint support anonymous access or not
    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
        }
    }

    /// Authenticates the username identity token with the supplied endpoint
    fn authenticate_username_identity_token(&self, config: &ServerConfig, endpoint: &ServerEndpoint, token: &UserNameIdentityToken) -> StatusCode {
        // TODO Server's user token policy should be checked here.
        // The policy_id should be used to determine the algorithm for encoding passwords etc.
        if !token.encryption_algorithm.is_null() {
            // Plaintext is the only supported algorithm at this time
            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 {
            // Iterate ids in endpoint
            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() {
                        // test for empty password
                        let result = if server_user_token.pass.is_none() {
                            // Empty password for user
                            token.authenticate(&server_user_token.user, b"")
                        } else {
                            // Password compared as UTF-8 bytes
                            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
        }
    }
}