opcua_core/comms/
secure_channel.rs

1// OPCUA for Rust
2// SPDX-License-Identifier: MPL-2.0
3// Copyright (C) 2017-2022 Adam Lock
4
5use std::{
6    io::{Cursor, Write},
7    ops::Range,
8    sync::{Arc, RwLock},
9};
10
11use chrono::Duration;
12
13use opcua_crypto::{
14    aeskey::AesKey,
15    CertificateStore,
16    pkey::{KeySize, PrivateKey, PublicKey},
17    random,
18    SecurityPolicy, x509::X509,
19};
20use opcua_types::{
21    BinaryEncoder, ByteString, DateTime, DecodingOptions,
22    MessageSecurityMode, service_types::ChannelSecurityToken, status_code::StatusCode, write_bytes, write_u8,
23};
24
25use crate::comms::{
26    message_chunk::{MessageChunk, MessageChunkHeader, MessageChunkType},
27    security_header::{AsymmetricSecurityHeader, SecurityHeader, SymmetricSecurityHeader},
28};
29
30#[derive(Debug, PartialEq)]
31pub enum Role {
32    Unknown,
33    Client,
34    Server,
35}
36
37/// Holds all of the security information related to this session
38#[derive(Debug)]
39pub struct SecureChannel {
40    // The side of the secure channel that this role belongs to, client or server
41    role: Role,
42    /// The security policy for the connection, None or Encryption/Signing settings
43    security_policy: SecurityPolicy,
44    /// The security mode for the connection, None, Sign, SignAndEncrypt
45    security_mode: MessageSecurityMode,
46    /// Secure channel id
47    secure_channel_id: u32,
48    /// Token creation time.
49    token_created_at: DateTime,
50    /// Token lifetime
51    token_lifetime: u32,
52    /// Token identifier
53    token_id: u32,
54    /// Our certificate
55    cert: Option<X509>,
56    /// Our private key
57    private_key: Option<PrivateKey>,
58    /// Their certificate
59    remote_cert: Option<X509>,
60    /// Their nonce provided by open secure channel
61    remote_nonce: Vec<u8>,
62    /// Our nonce generated while handling open secure channel
63    local_nonce: Vec<u8>,
64    /// Client (i.e. other end's set of keys) Symmetric Signing Key, Encrypt Key, IV
65    remote_keys: Option<(Vec<u8>, AesKey, Vec<u8>)>,
66    /// Server (i.e. our end's set of keys) Symmetric Signing Key, Decrypt Key, IV
67    local_keys: Option<(Vec<u8>, AesKey, Vec<u8>)>,
68    /// Decoding options
69    decoding_options: DecodingOptions,
70}
71
72impl From<(SecurityPolicy, MessageSecurityMode)> for SecureChannel {
73    fn from(v: (SecurityPolicy, MessageSecurityMode)) -> Self {
74        SecureChannel {
75            role: Role::Unknown,
76            security_policy: v.0,
77            security_mode: v.1,
78            secure_channel_id: 0,
79            token_id: 0,
80            token_created_at: DateTime::now(),
81            token_lifetime: 0,
82            local_nonce: Vec::new(),
83            remote_nonce: Vec::new(),
84            cert: None,
85            private_key: None,
86            remote_cert: None,
87            local_keys: None,
88            remote_keys: None,
89            decoding_options: DecodingOptions::default(),
90        }
91    }
92}
93
94impl SecureChannel {
95    /// For testing purposes only
96    #[cfg(test)]
97    pub fn new_no_certificate_store() -> SecureChannel {
98        (SecurityPolicy::None, MessageSecurityMode::None).into()
99    }
100
101    pub fn new(
102        certificate_store: Arc<RwLock<CertificateStore>>,
103        role: Role,
104        decoding_options: DecodingOptions,
105    ) -> SecureChannel {
106        let (cert, private_key) = {
107            let certificate_store = certificate_store.read().unwrap();
108            if let Ok((cert, pkey)) = certificate_store.read_own_cert_and_pkey() {
109                (Some(cert), Some(pkey))
110            } else {
111                error!("Cannot read our own certificate and private key. Check paths. Crypto won't work");
112                (None, None)
113            }
114        };
115        SecureChannel {
116            role,
117            security_mode: MessageSecurityMode::None,
118            security_policy: SecurityPolicy::None,
119            secure_channel_id: 0,
120            token_id: 0,
121            token_created_at: DateTime::now(),
122            token_lifetime: 0,
123            local_nonce: Vec::new(),
124            remote_nonce: Vec::new(),
125            cert,
126            private_key,
127            remote_cert: None,
128            local_keys: None,
129            remote_keys: None,
130            decoding_options,
131        }
132    }
133
134    pub fn is_client_role(&self) -> bool {
135        self.role == Role::Client
136    }
137
138    pub fn set_cert(&mut self, cert: Option<X509>) {
139        self.cert = cert;
140    }
141
142    pub fn cert(&self) -> Option<X509> {
143        self.cert.clone()
144    }
145
146    pub fn set_remote_cert(&mut self, remote_cert: Option<X509>) {
147        self.remote_cert = remote_cert;
148    }
149
150    pub fn remote_cert(&self) -> Option<X509> {
151        self.remote_cert.clone()
152    }
153
154    pub fn set_private_key(&mut self, private_key: Option<PrivateKey>) {
155        self.private_key = private_key;
156    }
157
158    pub fn security_mode(&self) -> MessageSecurityMode {
159        self.security_mode
160    }
161
162    pub fn set_security_mode(&mut self, security_mode: MessageSecurityMode) {
163        self.security_mode = security_mode;
164    }
165
166    pub fn security_policy(&self) -> SecurityPolicy {
167        self.security_policy
168    }
169
170    pub fn set_security_policy(&mut self, security_policy: SecurityPolicy) {
171        self.security_policy = security_policy;
172    }
173
174    pub fn clear_security_token(&mut self) {
175        self.secure_channel_id = 0;
176        self.token_id = 0;
177        self.token_created_at = DateTime::now();
178        self.token_lifetime = 0;
179    }
180
181    pub fn set_security_token(&mut self, channel_token: ChannelSecurityToken) {
182        self.secure_channel_id = channel_token.channel_id;
183        self.token_id = channel_token.token_id;
184        self.token_created_at = channel_token.created_at;
185        self.token_lifetime = channel_token.revised_lifetime;
186    }
187
188    pub fn set_secure_channel_id(&mut self, secure_channel_id: u32) {
189        self.secure_channel_id = secure_channel_id;
190    }
191
192    pub fn secure_channel_id(&self) -> u32 {
193        self.secure_channel_id
194    }
195
196    pub fn token_created_at(&self) -> DateTime {
197        self.token_created_at
198    }
199
200    pub fn token_lifetime(&self) -> u32 {
201        self.token_lifetime
202    }
203
204    pub fn set_token_id(&mut self, token_id: u32) {
205        self.token_id = token_id;
206    }
207
208    pub fn token_id(&self) -> u32 {
209        self.token_id
210    }
211
212    pub fn set_client_offset(&mut self, client_offset: Duration) {
213        self.decoding_options.client_offset = client_offset;
214    }
215
216    pub fn set_decoding_options(&mut self, decoding_options: DecodingOptions) {
217        self.decoding_options = DecodingOptions {
218            client_offset: self.decoding_options.client_offset,
219            ..decoding_options
220        }
221    }
222
223    pub fn decoding_options(&self) -> DecodingOptions {
224        self.decoding_options
225    }
226
227    /// Test if the secure channel token needs to be renewed. The algorithm determines it needs
228    /// to be renewed if the issue period has elapsed by 75% or more.
229    pub fn should_renew_security_token(&self) -> bool {
230        if self.token_id() == 0 {
231            false
232        } else {
233            // Check if secure channel 75% close to expiration in which case send a renew
234            let renew_lifetime = (self.token_lifetime() * 3) / 4;
235            let renew_lifetime = Duration::milliseconds(renew_lifetime as i64);
236            // Renew the token?
237            DateTime::now() - self.token_created_at() > renew_lifetime
238        }
239    }
240
241    /// Makes a security header according to the type of message being sent, symmetric or asymmetric
242    pub fn make_security_header(&self, message_type: MessageChunkType) -> SecurityHeader {
243        match message_type {
244            MessageChunkType::OpenSecureChannel => {
245                let asymmetric_security_header = if self.security_policy == SecurityPolicy::None {
246                    trace!("AsymmetricSecurityHeader security policy none");
247                    AsymmetricSecurityHeader::none()
248                } else {
249                    let receiver_certificate_thumbprint =
250                        if let Some(ref remote_cert) = self.remote_cert {
251                            remote_cert.thumbprint().as_byte_string()
252                        } else {
253                            ByteString::null()
254                        };
255                    AsymmetricSecurityHeader::new(
256                        self.security_policy,
257                        self.cert.as_ref().unwrap(),
258                        receiver_certificate_thumbprint,
259                    )
260                };
261                debug!(
262                    "AsymmetricSecurityHeader = {:?}",
263                    asymmetric_security_header
264                );
265                SecurityHeader::Asymmetric(asymmetric_security_header)
266            }
267            _ => SecurityHeader::Symmetric(SymmetricSecurityHeader {
268                token_id: self.token_id,
269            }),
270        }
271    }
272
273    /// Creates a nonce for the connection. The nonce should be the same size as the symmetric key
274    pub fn create_random_nonce(&mut self) {
275        self.local_nonce.resize(self.security_policy.secure_channel_nonce_length(), 0);
276        random::bytes(&mut self.local_nonce);
277    }
278
279    /// Sets the remote certificate
280    pub fn set_remote_cert_from_byte_string(
281        &mut self,
282        remote_cert: &ByteString,
283    ) -> Result<(), StatusCode> {
284        self.remote_cert = if remote_cert.is_null() {
285            None
286        } else {
287            Some(X509::from_byte_string(remote_cert)?)
288        };
289        Ok(())
290    }
291
292    /// Obtains the remote certificate as a byte string
293    pub fn remote_cert_as_byte_string(&self) -> ByteString {
294        if let Some(ref remote_cert) = self.remote_cert {
295            remote_cert.as_byte_string()
296        } else {
297            ByteString::null()
298        }
299    }
300
301    /// Set their nonce which should be the same as the symmetric key
302    pub fn set_remote_nonce_from_byte_string(
303        &mut self,
304        remote_nonce: &ByteString,
305    ) -> Result<(), StatusCode> {
306        if let Some(ref remote_nonce) = remote_nonce.value {
307            if self.security_policy != SecurityPolicy::None
308                && remote_nonce.len() != self.security_policy.secure_channel_nonce_length()
309            {
310                error!(
311                    "Remote nonce is invalid length {}, expecting {}. {:?}",
312                    remote_nonce.len(),
313                    self.security_policy.secure_channel_nonce_length(),
314                    remote_nonce
315                );
316                Err(StatusCode::BadNonceInvalid)
317            } else {
318                self.remote_nonce = remote_nonce.to_vec();
319                Ok(())
320            }
321        } else if self.security_policy != SecurityPolicy::None {
322            error!("Remote nonce is invalid {:?}", remote_nonce);
323            Err(StatusCode::BadNonceInvalid)
324        } else {
325            Ok(())
326        }
327    }
328
329    /// Part 6
330    /// 6.7.5
331    /// Deriving keys Once the SecureChannel is established the Messages are signed and encrypted with
332    /// keys derived from the Nonces exchanged in the OpenSecureChannel call. These keys are derived by passing the Nonces to a pseudo-random function which produces a sequence of bytes from a set of inputs. A pseudo-random function is represented by the following function declaration:
333    ///
334    /// ```c++
335    /// Byte[] PRF( Byte[] secret,  Byte[] seed,  Int32 length,  Int32 offset)
336    /// ```
337    ///
338    /// Where length is the number of bytes to return and offset is a number of bytes from the beginning of the sequence.
339    ///
340    /// The lengths of the keys that need to be generated depend on the SecurityPolicy used for the channel.
341    /// The following information is specified by the SecurityPolicy:
342    ///
343    /// a) SigningKeyLength (from the DerivedSignatureKeyLength);
344    /// b) EncryptingKeyLength (implied by the SymmetricEncryptionAlgorithm);
345    /// c) EncryptingBlockSize (implied by the SymmetricEncryptionAlgorithm).
346    ///
347    /// The parameters passed to the pseudo random function are specified in Table 33.
348    ///
349    /// Table 33 – Cryptography key generation parameters
350    ///
351    /// Key | Secret | Seed | Length | Offset
352    /// ClientSigningKey | ServerNonce | ClientNonce | SigningKeyLength | 0
353    /// ClientEncryptingKey | ServerNonce | ClientNonce | EncryptingKeyLength | SigningKeyLength
354    /// ClientInitializationVector | ServerNonce | ClientNonce | EncryptingBlockSize | SigningKeyLength + EncryptingKeyLength
355    /// ServerSigningKey | ClientNonce | ServerNonce | SigningKeyLength | 0
356    /// ServerEncryptingKey | ClientNonce | ServerNonce | EncryptingKeyLength | SigningKeyLength
357    /// ServerInitializationVector | ClientNonce | ServerNonce | EncryptingBlockSize | SigningKeyLength + EncryptingKeyLength
358    ///
359    /// The Client keys are used to secure Messages sent by the Client. The Server keys
360    /// are used to secure Messages sent by the Server.
361    ///
362    pub fn derive_keys(&mut self) {
363        self.remote_keys = Some(
364            self.security_policy
365                .make_secure_channel_keys(&self.local_nonce, &self.remote_nonce),
366        );
367        self.local_keys = Some(
368            self.security_policy
369                .make_secure_channel_keys(&self.remote_nonce, &self.local_nonce),
370        );
371        trace!("Remote nonce = {:?}", self.remote_nonce);
372        trace!("Local nonce = {:?}", self.local_nonce);
373        trace!("Derived remote keys = {:?}", self.remote_keys);
374        trace!("Derived local keys = {:?}", self.local_keys);
375    }
376
377    /// Test if the token has expired yet
378    pub fn token_has_expired(&self) -> bool {
379        let token_created_at = self.token_created_at;
380        let token_expires = token_created_at + Duration::seconds(self.token_lifetime as i64);
381        DateTime::now().ge(&token_expires)
382    }
383
384    /// Calculates the signature size for a message depending on the supplied security header
385    pub fn signature_size(&self, security_header: &SecurityHeader) -> usize {
386        // Signature size in bytes
387        match security_header {
388            SecurityHeader::Asymmetric(security_header) => {
389                if !security_header.sender_certificate.is_null() {
390                    let x509 = X509::from_byte_string(&security_header.sender_certificate).unwrap();
391                    x509.public_key().unwrap().size()
392                } else {
393                    trace!("No certificate / public key was supplied in the asymmetric security header");
394                    0
395                }
396            }
397            SecurityHeader::Symmetric(_) => {
398                // Signature size comes from policy
399                self.security_policy.symmetric_signature_size()
400            }
401        }
402    }
403
404    // Extra padding required for keysize > 2048 bits (256 bytes)
405    fn minimum_padding(key_length: usize) -> usize {
406        if key_length <= 256 {
407            1
408        } else {
409            2
410        }
411    }
412
413    /// Calculate the padding size
414    ///
415    /// Padding adds bytes to the body to make it a multiple of the block size so it can be encrypted.
416    pub fn padding_size(
417        &self,
418        security_header: &SecurityHeader,
419        body_size: usize,
420        signature_size: usize,
421    ) -> (usize, usize) {
422        if self.security_policy != SecurityPolicy::None
423            && self.security_mode != MessageSecurityMode::None
424        {
425            // Signature size in bytes
426            let (plain_text_block_size, key_length) = match security_header {
427                SecurityHeader::Asymmetric(security_header) => {
428                    if security_header.sender_certificate.is_null() {
429                        error!("Sender has not supplied a certificate so it is doubtful that this will work");
430                        (self.security_policy.plain_block_size(), signature_size)
431                    } else {
432                        // Padding requires we look at the remote certificate and security policy
433                        let padding = self.security_policy.asymmetric_encryption_padding();
434                        let x509 = self.remote_cert().unwrap();
435                        let pk = x509.public_key().unwrap();
436                        (pk.plain_text_block_size(padding), pk.size())
437                    }
438                }
439                SecurityHeader::Symmetric(_) => {
440                    // Plain text block size comes from policy
441                    (self.security_policy.plain_block_size(), signature_size)
442                }
443            };
444
445            // PaddingSize = PlainTextBlockSize – ((BytesToWrite + SignatureSize + 1) % PlainTextBlockSize);
446            let minimum_padding = Self::minimum_padding(key_length);
447            let encrypt_size = 8 + body_size + signature_size + minimum_padding;
448            let padding_size = if encrypt_size % plain_text_block_size != 0 {
449                plain_text_block_size - (encrypt_size % plain_text_block_size)
450            } else {
451                0
452            };
453            trace!("sequence_header(8) + body({}) + signature ({}) = plain text size = {} / with padding {} = {}, plain_text_block_size = {}", body_size, signature_size, encrypt_size, padding_size, encrypt_size + padding_size, plain_text_block_size);
454            (minimum_padding + padding_size, minimum_padding)
455        } else {
456            (0, 0)
457        }
458    }
459
460    // Takes an unpadded message chunk and adds padding as well as space to the end to accomodate a signature.
461    // Also modifies the message size to include the new padding/signature
462    fn add_space_for_padding_and_signature(
463        &self,
464        message_chunk: &MessageChunk,
465    ) -> Result<Vec<u8>, StatusCode> {
466        let chunk_info = message_chunk.chunk_info(self)?;
467        let data = &message_chunk.data[..];
468
469        let security_header = chunk_info.security_header;
470
471        let buffer = Vec::with_capacity(message_chunk.data.len() + 4096);
472        let mut stream = Cursor::new(buffer);
473
474        // First off just write out the src to the buffer. The message header, security header, sequence header and payload
475        let _ = stream.write(data);
476
477        // Signature size (if required)
478        let signature_size = self.signature_size(&security_header);
479
480        // Write padding
481        let body_size = chunk_info.body_length;
482
483        let (padding_size, minimum_padding) =
484            self.padding_size(&security_header, body_size, signature_size);
485        if padding_size > 0 {
486            // A number of bytes are written out equal to the padding size.
487            // Each byte is the padding size. So if padding size is 15 then
488            // there will be 15 bytes all with the value 15
489            if minimum_padding == 1 {
490                let padding_byte = ((padding_size - 1) & 0xff) as u8;
491                let _ = write_bytes(&mut stream, padding_byte, padding_size)?;
492            } else if minimum_padding == 2 {
493                // Padding and then extra padding
494                let padding_byte = ((padding_size - 2) & 0xff) as u8;
495                let extra_padding_byte = ((padding_size - 2) >> 8) as u8;
496                trace!(
497                    "adding extra padding - padding_byte = {}, extra_padding_byte = {}",
498                    padding_byte,
499                    extra_padding_byte
500                );
501                let _ = write_bytes(&mut stream, padding_byte, padding_size - 1)?;
502                write_u8(&mut stream, extra_padding_byte)?;
503            }
504        }
505
506        // Write zeros for the signature
507        let _ = write_bytes(&mut stream, 0u8, signature_size)?;
508
509        // Update message header to reflect size with padding + signature
510        let message_size = data.len() + padding_size + signature_size;
511        Self::update_message_size_and_truncate(
512            stream.into_inner(),
513            message_size,
514            &self.decoding_options,
515        )
516    }
517
518    fn update_message_size(
519        data: &mut [u8],
520        message_size: usize,
521        decoding_options: &DecodingOptions,
522    ) -> Result<(), StatusCode> {
523        // Read and rewrite the message_size in the header
524        let mut stream = Cursor::new(data);
525        let mut message_header = MessageChunkHeader::decode(&mut stream, decoding_options)?;
526        stream.set_position(0);
527        let old_message_size = message_header.message_size;
528        message_header.message_size = message_size as u32;
529        message_header.encode(&mut stream)?;
530        trace!(
531            "Message header message size being modified from {} to {}",
532            old_message_size,
533            message_size
534        );
535        Ok(())
536    }
537
538    // Truncates a vec and writes the message size
539    pub fn update_message_size_and_truncate(
540        mut data: Vec<u8>,
541        message_size: usize,
542        decoding_options: &DecodingOptions,
543    ) -> Result<Vec<u8>, StatusCode> {
544        Self::update_message_size(&mut data[..], message_size, decoding_options)?;
545        // Truncate vector to the size
546        data.truncate(message_size);
547        Ok(data)
548    }
549
550    fn log_crypto_data(message: &str, data: &[u8]) {
551        use crate::debug;
552        debug::log_buffer(message, data);
553    }
554
555    /// Applies security to a message chunk and yields a encrypted/signed block to be streamed
556    pub fn apply_security(
557        &self,
558        message_chunk: &MessageChunk,
559        dst: &mut [u8],
560    ) -> Result<usize, StatusCode> {
561        let size = if self.security_policy != SecurityPolicy::None
562            && (self.security_mode == MessageSecurityMode::Sign
563                || self.security_mode == MessageSecurityMode::SignAndEncrypt)
564        {
565            let chunk_info = message_chunk.chunk_info(self)?;
566
567            // S - Message Header
568            // S - Security Header
569            // S - Sequence Header - E
570            // S - Body            - E
571            // S - Padding         - E
572            //     Signature       - E
573
574            let data = self.add_space_for_padding_and_signature(message_chunk)?;
575            Self::log_crypto_data("Chunk before padding", &message_chunk.data[..]);
576            Self::log_crypto_data("Chunk after padding", &data[..]);
577
578            // Encrypted range is from the sequence header to the end
579            let encrypted_range = chunk_info.sequence_header_offset..data.len();
580
581            // Encrypt and sign - open secure channel
582            let encrypted_size = if message_chunk.is_open_secure_channel(&self.decoding_options) {
583                self.asymmetric_sign_and_encrypt(self.security_policy, &data, encrypted_range, dst)?
584            } else {
585                // Symmetric encrypt and sign
586                let signed_range =
587                    0..(data.len() - self.security_policy.symmetric_signature_size());
588                self.symmetric_sign_and_encrypt(&data, signed_range, encrypted_range, dst)?
589            };
590
591            Self::log_crypto_data("Chunk after encryption", &dst[..encrypted_size]);
592
593            encrypted_size
594        } else {
595            let size = message_chunk.data.len();
596            if size > dst.len() {
597                panic!("The size of the message chunk {} exceeds the size of the destination buffer {}", size, dst.len())
598            }
599            dst[..size].copy_from_slice(&message_chunk.data[..]);
600            size
601        };
602        Ok(size)
603    }
604
605    /// Decrypts and verifies the body data if the mode / policy requires it
606    pub fn verify_and_remove_security(&mut self, src: &[u8]) -> Result<MessageChunk, StatusCode> {
607        self.verify_and_remove_security_forensic(src, None)
608    }
609
610    /// Decrypts and verifies the body data if the mode / policy requires it
611    ///
612    /// Note, that normally we do not have "their" key but for testing purposes and forensics, we
613    /// might have the key
614    pub fn verify_and_remove_security_forensic(
615        &mut self,
616        src: &[u8],
617        their_key: Option<PrivateKey>,
618    ) -> Result<MessageChunk, StatusCode> {
619        // Get message & security header from data
620        let (message_header, security_header, encrypted_data_offset) = {
621            let mut stream = Cursor::new(&src);
622            let message_header = MessageChunkHeader::decode(&mut stream, &self.decoding_options)?;
623            let security_header = if message_header.message_type.is_open_secure_channel() {
624                SecurityHeader::Asymmetric(AsymmetricSecurityHeader::decode(
625                    &mut stream,
626                    &self.decoding_options,
627                )?)
628            } else {
629                SecurityHeader::Symmetric(SymmetricSecurityHeader::decode(
630                    &mut stream,
631                    &self.decoding_options,
632                )?)
633            };
634            let encrypted_data_offset = stream.position() as usize;
635            (message_header, security_header, encrypted_data_offset)
636        };
637
638        let message_size = message_header.message_size as usize;
639        if message_size != src.len() {
640            error!(
641                "The message size {} is not the same as the supplied buffer {}",
642                message_size,
643                src.len()
644            );
645            return Err(StatusCode::BadUnexpectedError);
646        }
647
648        // S - Message Header
649        // S - Security Header
650        // S - Sequence Header - E
651        // S - Body            - E
652        // S - Padding         - E
653        //     Signature       - E
654        let data = if message_header.message_type.is_open_secure_channel() {
655            // The OpenSecureChannel is the first thing we receive so we must examine
656            // the security policy and use it to determine if the packet must be decrypted.
657            let encrypted_range = encrypted_data_offset..message_size;
658
659            trace!("Decrypting OpenSecureChannel");
660
661            let security_header = match security_header {
662                SecurityHeader::Asymmetric(security_header) => security_header,
663                _ => {
664                    panic!();
665                }
666            };
667
668            // The security policy dictates the encryption / signature algorithms used by the request
669            let security_policy_uri = security_header.security_policy_uri.as_ref();
670            let security_policy = SecurityPolicy::from_uri(security_policy_uri);
671            match security_policy {
672                SecurityPolicy::Unknown => {
673                    error!("Security policy \"{}\" provided by client is unknown so it is has been rejected", security_policy_uri);
674                    return Err(StatusCode::BadSecurityPolicyRejected);
675                }
676                SecurityPolicy::None => {
677                    // Nothing to do
678                    return Ok(MessageChunk { data: src.to_vec() });
679                }
680                _ => {}
681            }
682            self.security_policy = security_policy;
683
684            // Asymmetric decrypt and verify
685
686            // The OpenSecureChannel Messages are always signed and encrypted if the SecurityMode
687            // is not None. Even if the SecurityMode is Sign and not SignAndEncrypt.
688
689            // An OpenSecureChannelRequest uses Asymmetric encryption - decrypt using the server's private
690            // key, verify signature with client's public key.
691
692            // This code doesn't *care* if the cert is trusted, merely that it was used to sign the message
693            if security_header.sender_certificate.is_null() {
694                error!("Sender certificate is NULL!!!");
695                // TODO return
696            }
697
698            let sender_certificate_len = security_header
699                .sender_certificate
700                .value
701                .as_ref()
702                .unwrap()
703                .len();
704            trace!(
705                "Sender certificate byte length = {}",
706                sender_certificate_len
707            );
708            let sender_certificate = X509::from_byte_string(&security_header.sender_certificate)?;
709
710            let verification_key = sender_certificate.public_key()?;
711            let receiver_thumbprint = security_header.receiver_certificate_thumbprint;
712            trace!("Receiver thumbprint = {:?}", receiver_thumbprint);
713
714            let mut decrypted_data = vec![0u8; message_size];
715            let decrypted_size = self.asymmetric_decrypt_and_verify(
716                security_policy,
717                &verification_key,
718                receiver_thumbprint,
719                src,
720                encrypted_range,
721                their_key,
722                &mut decrypted_data,
723            )?;
724
725            Self::update_message_size_and_truncate(
726                decrypted_data,
727                decrypted_size,
728                &self.decoding_options,
729            )?
730        } else if self.security_policy != SecurityPolicy::None
731            && (self.security_mode == MessageSecurityMode::Sign
732                || self.security_mode == MessageSecurityMode::SignAndEncrypt)
733        {
734            // Symmetric decrypt and verify
735            let signature_size = self.security_policy.symmetric_signature_size();
736            let encrypted_range = encrypted_data_offset..message_size;
737            let signed_range = 0..(message_size - signature_size);
738            trace!(
739                "Decrypting block with signature info {:?} and encrypt info {:?}",
740                signed_range,
741                encrypted_range
742            );
743
744            let mut decrypted_data = vec![0u8; message_size];
745            let decrypted_size = self.symmetric_decrypt_and_verify(
746                src,
747                signed_range,
748                encrypted_range,
749                &mut decrypted_data,
750            )?;
751
752            // Now we need to strip off signature
753            Self::update_message_size_and_truncate(
754                decrypted_data,
755                decrypted_size - signature_size,
756                &self.decoding_options,
757            )?
758        } else {
759            src.to_vec()
760        };
761
762        Ok(MessageChunk { data })
763    }
764
765    /// Use the security policy to asymmetric encrypt and sign the specified chunk of data
766    fn asymmetric_sign_and_encrypt(
767        &self,
768        security_policy: SecurityPolicy,
769        src: &[u8],
770        encrypted_range: Range<usize>,
771        dst: &mut [u8],
772    ) -> Result<usize, StatusCode> {
773        let header_size = encrypted_range.start;
774
775        let signing_key = self.private_key.as_ref().unwrap();
776        let signing_key_size = signing_key.size();
777
778        let signed_range = 0..(encrypted_range.end - signing_key_size);
779        let signature_range = signed_range.end..encrypted_range.end;
780
781        trace!("Header size = {}, Encrypted range = {:?}, Signed range = {:?}, Signature range = {:?}, signature size = {}", header_size, encrypted_range, signed_range, signature_range, signing_key_size);
782
783        let mut signature = vec![0u8; signing_key_size];
784        let encryption_key = self.remote_cert.as_ref().unwrap().public_key()?;
785
786        let mut tmp = vec![0u8; encrypted_range.end];
787        tmp[signed_range.clone()].copy_from_slice(&src[signed_range.clone()]);
788
789        // Encryption will change the size of the chunk. Since we sign before encrypting, we need to
790        // compute that size and change the message header to be that new size
791        let cipher_text_size = {
792            let padding = security_policy.asymmetric_encryption_padding();
793            let plain_text_size = encrypted_range.end - encrypted_range.start;
794            let cipher_text_size =
795                encryption_key.calculate_cipher_text_size(plain_text_size, padding);
796            trace!(
797                "plain_text_size = {}, encrypted_text_size = {}",
798                plain_text_size,
799                cipher_text_size
800            );
801            cipher_text_size
802        };
803        Self::update_message_size(
804            &mut tmp[..],
805            header_size + cipher_text_size,
806            &self.decoding_options,
807        )?;
808
809        // Sign the message header, security header, sequence header, body, padding
810        security_policy.asymmetric_sign(signing_key, &tmp[signed_range], &mut signature)?;
811        tmp[signature_range.clone()].copy_from_slice(&signature);
812        assert_eq!(encrypted_range.end, signature_range.end);
813
814        Self::log_crypto_data("Chunk after signing", &tmp[..signature_range.end]);
815
816        // Copy the unencrypted message header / security header portion to dst
817        dst[..encrypted_range.start].copy_from_slice(&tmp[..encrypted_range.start]);
818
819        // Encrypt the sequence header, payload, signature portion into dst
820        let encrypted_size = security_policy.asymmetric_encrypt(
821            &encryption_key,
822            &tmp[encrypted_range.clone()],
823            &mut dst[encrypted_range.start..],
824        )?;
825
826        // Validate encrypted size is right
827        if encrypted_size != cipher_text_size {
828            panic!(
829                "Encrypted block size {} is not the same as calculated cipher text size {}",
830                encrypted_size, cipher_text_size
831            );
832        }
833
834        //{
835        //    debug!("Encrypted size in bytes = {} compared to encrypted range {:?}", encrypted_size, encrypted_range);
836        //    Self::log_crypto_data("Decrypted data", src);
837        //    Self::log_crypto_data("Encrypted data", &dst[0..encrypted_size]);
838        //}
839
840        Ok(header_size + encrypted_size)
841    }
842
843    fn check_padding_bytes(
844        padding_bytes: &[u8],
845        expected_padding_byte: u8,
846        padding_range_start: usize,
847    ) -> Result<(), StatusCode> {
848        for (i, b) in padding_bytes.iter().enumerate() {
849            if *b != expected_padding_byte {
850                error!(
851                    "Expected padding byte {}, got {} at index {}",
852                    expected_padding_byte,
853                    *b,
854                    padding_range_start + i
855                );
856                return Err(StatusCode::BadSecurityChecksFailed);
857            }
858        }
859        Ok(())
860    }
861
862    /// Verify that the padding is correct. Padding is expected to be before the supplied padding end index.
863    ///
864    /// Function returns the padding range so caller can strip the range if it so desires.
865    fn verify_padding(
866        &self,
867        src: &[u8],
868        key_size: usize,
869        padding_end: usize,
870    ) -> Result<Range<usize>, StatusCode> {
871        let padding_range = if key_size > 256 {
872            let padding_byte = src[padding_end - 2];
873            let extra_padding_byte = src[padding_end - 1];
874            let padding_size = ((extra_padding_byte as usize) << 8) + (padding_byte as usize);
875            let padding_range = (padding_end - padding_size - 2)..padding_end;
876
877            trace!("Extra padding - extra_padding_byte = {}, padding_byte = {}, padding_end = {}, padding_size = {}", extra_padding_byte, padding_byte, padding_end, padding_size);
878
879            // Check padding bytes and extra padding byte
880            Self::check_padding_bytes(
881                &src[padding_range.start..(padding_range.end - 1)],
882                padding_byte,
883                padding_range.start,
884            )?;
885            if src[padding_range.end - 1] != extra_padding_byte {
886                error!(
887                    "Expected extra padding byte {}, at index {}",
888                    extra_padding_byte, padding_range.start
889                );
890                return Err(StatusCode::BadSecurityChecksFailed);
891            }
892            padding_range
893        } else {
894            let padding_byte = src[padding_end - 1];
895            let padding_size = padding_byte as usize;
896            let padding_range = (padding_end - padding_size - 1)..padding_end;
897            // Check padding bytes
898            Self::check_padding_bytes(
899                &src[padding_range.clone()],
900                padding_byte,
901                padding_range.start,
902            )?;
903            padding_range
904        };
905        trace!("padding_range = {:?}", padding_range);
906        Ok(padding_range)
907    }
908
909    fn asymmetric_decrypt_and_verify(
910        &self,
911        security_policy: SecurityPolicy,
912        verification_key: &PublicKey,
913        receiver_thumbprint: ByteString,
914        src: &[u8],
915        encrypted_range: Range<usize>,
916        their_key: Option<PrivateKey>,
917        dst: &mut [u8],
918    ) -> Result<usize, StatusCode> {
919        // Asymmetric encrypt requires the caller supply the security policy
920        if !security_policy.is_supported() {
921            error!("Security policy {} is not supported by asymmetric_decrypt_and_verify and has been rejected", security_policy);
922            return Err(StatusCode::BadSecurityPolicyRejected);
923        }
924
925        // Unlike the symmetric_decrypt_and_verify, this code will ALWAYS decrypt and verify regardless
926        // of security mode. This is part of the OpenSecureChannel request on a sign / signencrypt
927        // mode connection.
928
929        // The sender_certificate is is the cert used to sign the message, i.e. the client's cert
930        //
931        // The receiver certificate thumbprint identifies which of our certs was used by the client
932        // to encrypt the message. We have to work out from the thumbprint which cert to use
933
934        let our_cert = self.cert.as_ref().unwrap();
935        let our_thumbprint = our_cert.thumbprint();
936        if our_thumbprint.value() != receiver_thumbprint.as_ref() {
937            error!("Supplied thumbprint does not match application certificate's thumbprint");
938            Err(StatusCode::BadNoValidCertificates)
939        } else {
940            // Copy message, security header
941            dst[..encrypted_range.start].copy_from_slice(&src[..encrypted_range.start]);
942
943            // Decrypt and copy encrypted block
944            // Note that the unencrypted size can be less than the encrypted size due to removal
945            // of padding, so the ranges that were supplied to this function must be offset to compensate.
946            let encrypted_size = encrypted_range.end - encrypted_range.start;
947            trace!("Decrypting message range {:?}", encrypted_range);
948            let mut decrypted_tmp = vec![0u8; encrypted_size];
949
950            let private_key = self.private_key.as_ref().unwrap();
951            let decrypted_size = security_policy.asymmetric_decrypt(
952                private_key,
953                &src[encrypted_range.clone()],
954                &mut decrypted_tmp,
955            )?;
956            trace!(
957                "Decrypted bytes = {} compared to encrypted range {}",
958                decrypted_size,
959                encrypted_size
960            );
961            // Self::log_crypto_data("Decrypted Bytes = ", &decrypted_tmp[..decrypted_size]);
962
963            let verification_key_signature_size = verification_key.size();
964            trace!(
965                "Verification key size = {}",
966                verification_key_signature_size
967            );
968
969            // Copy the bytes to dst
970            dst[encrypted_range.start..(encrypted_range.start + decrypted_size)]
971                .copy_from_slice(&decrypted_tmp[0..decrypted_size]);
972
973            // The signature range is at the end of the decrypted block for the verification key's signature
974            let signature_dst_offset =
975                encrypted_range.start + decrypted_size - verification_key_signature_size;
976            let signature_range_dst =
977                signature_dst_offset..(signature_dst_offset + verification_key_signature_size);
978
979            // The signed range is from 0 to the end of the plaintext except for key size
980            let signed_range_dst = 0..signature_dst_offset;
981
982            // Self::log_crypto_data("Decrypted data = ", &dst[..signature_range_dst.end]);
983
984            // Verify signature (contained encrypted portion) using verification key
985            trace!(
986                "Verifying signature range {:?} with signature at {:?}",
987                signed_range_dst,
988                signature_range_dst
989            );
990            // Keysize for padding is publickey length if avaiable
991            let key_size = if let Some(rem) = &self.cert {
992                if let Ok(cert) = rem.public_key() {
993                    cert.size()
994                } else {
995                    verification_key.size()
996                }
997            } else {
998                verification_key.size()
999            };
1000            security_policy.asymmetric_verify_signature(
1001                verification_key,
1002                &dst[signed_range_dst],
1003                &dst[signature_range_dst.clone()],
1004                their_key,
1005            )?;
1006
1007            // Verify that the padding is correct
1008            let padding_range = self.verify_padding(dst, key_size, signature_range_dst.start)?;
1009
1010            // Decrypted and verified into dst
1011            Ok(padding_range.start)
1012        }
1013    }
1014
1015    pub fn local_nonce(&self) -> &[u8] {
1016        &self.local_nonce
1017    }
1018
1019    pub fn set_local_nonce(&mut self, local_nonce: &[u8]) {
1020        self.local_nonce.clear();
1021        self.local_nonce.extend_from_slice(local_nonce);
1022    }
1023
1024    pub fn local_nonce_as_byte_string(&self) -> ByteString {
1025        if self.local_nonce.is_empty() {
1026            ByteString::null()
1027        } else {
1028            ByteString::from(&self.local_nonce)
1029        }
1030    }
1031
1032    pub fn set_remote_nonce(&mut self, remote_nonce: &[u8]) {
1033        self.remote_nonce.clear();
1034        self.remote_nonce.extend_from_slice(remote_nonce);
1035    }
1036
1037    pub fn remote_nonce(&self) -> &[u8] {
1038        &self.remote_nonce
1039    }
1040
1041    pub fn remote_nonce_as_byte_string(&self) -> ByteString {
1042        if self.remote_nonce.is_empty() {
1043            ByteString::null()
1044        } else {
1045            ByteString::from(&self.remote_nonce)
1046        }
1047    }
1048
1049    fn local_keys(&self) -> &(Vec<u8>, AesKey, Vec<u8>) {
1050        self.local_keys.as_ref().unwrap()
1051    }
1052
1053    fn remote_keys(&self) -> &(Vec<u8>, AesKey, Vec<u8>) {
1054        self.remote_keys.as_ref().unwrap()
1055    }
1056
1057    fn encryption_keys(&self) -> (&AesKey, &[u8]) {
1058        let keys = self.local_keys();
1059        (&keys.1, &keys.2)
1060    }
1061
1062    fn signing_key(&self) -> &[u8] {
1063        &(self.local_keys()).0
1064    }
1065
1066    fn decryption_keys(&self) -> (&AesKey, &[u8]) {
1067        let keys = self.remote_keys();
1068        (&keys.1, &keys.2)
1069    }
1070
1071    fn verification_key(&self) -> &[u8] {
1072        &(self.remote_keys()).0
1073    }
1074
1075    /// Encode data using security. Destination buffer is expected to be same size as src and expected
1076    /// to have space for for a signature if a signature is to be appended
1077    ///
1078    /// Signing is done first and then encryption
1079    ///
1080    /// S - Message Header
1081    /// S - Security Header
1082    /// S - Sequence Header - E
1083    /// S - Body            - E
1084    /// S - Padding         - E
1085    ///     Signature       - E
1086    pub fn symmetric_sign_and_encrypt(
1087        &self,
1088        src: &[u8],
1089        signed_range: Range<usize>,
1090        encrypted_range: Range<usize>,
1091        dst: &mut [u8],
1092    ) -> Result<usize, StatusCode> {
1093        let encrypted_size = match self.security_mode {
1094            MessageSecurityMode::None => {
1095                trace!("encrypt_and_sign is doing nothing because security mode == None");
1096                // Just copy data to out
1097                dst.copy_from_slice(src);
1098
1099                src.len()
1100            }
1101            MessageSecurityMode::Sign => {
1102                trace!("encrypt_and_sign security mode == Sign");
1103                self.expect_supported_security_policy();
1104                self.symmetric_sign(src, signed_range, dst)?
1105            }
1106            MessageSecurityMode::SignAndEncrypt => {
1107                trace!("encrypt_and_sign security mode == SignAndEncrypt, signed_range = {:?}, encrypted_range = {:?}", signed_range, encrypted_range);
1108                self.expect_supported_security_policy();
1109
1110                let mut dst_tmp = vec![0u8; dst.len() + 16]; // tmp includes +16 for blocksize
1111
1112                // Sign the block
1113                let _ = self.symmetric_sign(src, signed_range, &mut dst_tmp)?;
1114
1115                // Encrypt the sequence header, payload, signature
1116                let (key, iv) = self.encryption_keys();
1117                let encrypted_size = self.security_policy.symmetric_encrypt(
1118                    key,
1119                    iv,
1120                    &dst_tmp[encrypted_range.clone()],
1121                    &mut dst[encrypted_range.start..(encrypted_range.end + 16)],
1122                )?;
1123                // Copy the message header / security header
1124                dst[..encrypted_range.start].copy_from_slice(&dst_tmp[..encrypted_range.start]);
1125
1126                encrypted_range.start + encrypted_size
1127            }
1128            MessageSecurityMode::Invalid => {
1129                panic!("Message security mode is invalid");
1130            }
1131        };
1132        Ok(encrypted_size)
1133    }
1134
1135    fn symmetric_sign(
1136        &self,
1137        src: &[u8],
1138        signed_range: Range<usize>,
1139        dst: &mut [u8],
1140    ) -> Result<usize, StatusCode> {
1141        let signature_size = self.security_policy.symmetric_signature_size();
1142        let mut signature = vec![0u8; signature_size];
1143        let signature_range = signed_range.end..(signed_range.end + signature_size);
1144        trace!(
1145            "signed_range = {:?}, signature range = {:?}, signature len = {}",
1146            signed_range,
1147            signature_range,
1148            signature_size
1149        );
1150
1151        // Sign the message header, security header, sequence header, body, padding
1152        let signing_key = self.signing_key();
1153        self.security_policy.symmetric_sign(
1154            signing_key,
1155            &src[signed_range.clone()],
1156            &mut signature,
1157        )?;
1158
1159        trace!("Signature, len {} = {:?}", signature.len(), signature);
1160
1161        // Copy the signed portion and the signature to the destination
1162        dst[signed_range.clone()].copy_from_slice(&src[signed_range]);
1163        dst[signature_range.clone()].copy_from_slice(&signature);
1164
1165        Ok(signature_range.end)
1166    }
1167
1168    /// Decrypts and verifies data.
1169    ///
1170    /// Returns the size of the decrypted data
1171    ///
1172    /// S - Message Header
1173    /// S - Security Header
1174    /// S - Sequence Header - E
1175    /// S - Body            - E
1176    /// S - Padding         - E
1177    ///     Signature       - E
1178    pub fn symmetric_decrypt_and_verify(
1179        &self,
1180        src: &[u8],
1181        signed_range: Range<usize>,
1182        encrypted_range: Range<usize>,
1183        dst: &mut [u8],
1184    ) -> Result<usize, StatusCode> {
1185        match self.security_mode {
1186            MessageSecurityMode::None => {
1187                // Just copy everything from src to dst
1188                dst[..].copy_from_slice(src);
1189                Ok(src.len())
1190            }
1191            MessageSecurityMode::Sign => {
1192                self.expect_supported_security_policy();
1193                // Copy everything
1194                let all = ..src.len();
1195                trace!("copying from slice {:?}", all);
1196                dst[all].copy_from_slice(&src[all]);
1197                // Verify signature
1198                trace!(
1199                    "Verifying range from {:?} to signature {}..",
1200                    signed_range,
1201                    signed_range.end
1202                );
1203                let verification_key = self.verification_key();
1204                self.security_policy.symmetric_verify_signature(
1205                    verification_key,
1206                    &dst[signed_range.clone()],
1207                    &dst[signed_range.end..],
1208                )?;
1209
1210                Ok(encrypted_range.end)
1211            }
1212            MessageSecurityMode::SignAndEncrypt => {
1213                self.expect_supported_security_policy();
1214
1215                // There is an expectation that the block is padded so, this is a quick test
1216                let ciphertext_size = encrypted_range.end - encrypted_range.start;
1217                //                if ciphertext_size % 16 != 0 {
1218                //                    error!("The cipher text size is not padded properly, size = {}", ciphertext_size);
1219                //                    return Err(StatusCode::BadUnexpectedError);
1220                //                }
1221
1222                // Copy security header
1223                dst[..encrypted_range.start].copy_from_slice(&src[..encrypted_range.start]);
1224
1225                // Decrypt encrypted portion
1226                let mut decrypted_tmp = vec![0u8; ciphertext_size + 16]; // tmp includes +16 for blocksize
1227                let (key, iv) = self.decryption_keys();
1228
1229                trace!(
1230                    "Secure decrypt called with encrypted range {:?}",
1231                    encrypted_range
1232                );
1233                let decrypted_size = self.security_policy.symmetric_decrypt(
1234                    key,
1235                    iv,
1236                    &src[encrypted_range.clone()],
1237                    &mut decrypted_tmp[..],
1238                )?;
1239
1240                // Self::log_crypto_data("Encrypted buffer", &src[..encrypted_range.end]);
1241                let encrypted_range =
1242                    encrypted_range.start..(encrypted_range.start + decrypted_size);
1243                dst[encrypted_range.clone()].copy_from_slice(&decrypted_tmp[..decrypted_size]);
1244                Self::log_crypto_data("Decrypted buffer", &dst[..encrypted_range.end]);
1245
1246                // Verify signature (after encrypted portion)
1247                let signature_range = (encrypted_range.end
1248                    - self.security_policy.symmetric_signature_size())
1249                    ..encrypted_range.end;
1250                trace!(
1251                    "signed range = {:?}, signature range = {:?}",
1252                    signed_range,
1253                    signature_range
1254                );
1255                let verification_key = self.verification_key();
1256                self.security_policy.symmetric_verify_signature(
1257                    verification_key,
1258                    &dst[signed_range],
1259                    &dst[signature_range],
1260                )?;
1261                Ok(encrypted_range.end)
1262            }
1263            MessageSecurityMode::Invalid => {
1264                // Use the security policy to decrypt the block using the token
1265                panic!("Message security mode is invalid");
1266            }
1267        }
1268    }
1269
1270    // Panic code which requires a policy
1271    fn expect_supported_security_policy(&self) {
1272        match self.security_policy {
1273            SecurityPolicy::Basic128Rsa15
1274            | SecurityPolicy::Basic256
1275            | SecurityPolicy::Basic256Sha256
1276            | SecurityPolicy::Aes128Sha256RsaOaep
1277            | SecurityPolicy::Aes256Sha256RsaPss => {}
1278            _ => {
1279                panic!("Unsupported security policy");
1280            }
1281        }
1282    }
1283}