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
// Copyright 2020 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! This module wraps around all functions following the pattern `olm_sas_*`.
//!
//! # Example
//!
//! ```
//! # use olm_rs::sas::OlmSas;
//! let mut alice = OlmSas::new();
//! let mut bob = OlmSas::new();
//!
//! alice.set_their_public_key(bob.public_key()).unwrap();
//! bob.set_their_public_key(alice.public_key()).unwrap();
//!
//! assert_eq!(
//!     alice.generate_bytes("", 5).unwrap(),
//!     bob.generate_bytes("", 5).unwrap()
//! );
//!
//! ```

use std::ffi::CStr;

use zeroize::Zeroizing;

use crate::errors;
use crate::errors::OlmSasError;
use crate::getrandom;

pub struct OlmSas {
    sas_ptr: *mut olm_sys::OlmSAS,
    _sas_buf: Vec<u8>,
    public_key_set: bool,
}

impl Drop for OlmSas {
    fn drop(&mut self) {
        unsafe {
            olm_sys::olm_clear_sas(self.sas_ptr);
        }
    }
}

impl Default for OlmSas {
    fn default() -> Self {
        Self::new()
    }
}

impl OlmSas {
    pub fn new() -> Self {
        // allocate buffer for OlmAccount to be written into
        let mut buf: Vec<u8> = vec![0; unsafe { olm_sys::olm_sas_size() }];
        let ptr = unsafe { olm_sys::olm_sas(buf.as_mut_ptr() as *mut _) };

        let random_len = unsafe { olm_sys::olm_create_sas_random_length(ptr) };
        let mut random_buf: Zeroizing<Vec<u8>> = Zeroizing::new(vec![0; random_len]);
        getrandom(&mut random_buf);

        let ret =
            unsafe { olm_sys::olm_create_sas(ptr, random_buf.as_mut_ptr() as *mut _, random_len) };

        if ret == errors::olm_error() {
            errors::handle_fatal_error(Self::last_error(ptr));
        }

        Self {
            sas_ptr: ptr,
            _sas_buf: buf,
            public_key_set: false,
        }
    }

    /// Get the public key for the SAS object.
    ///
    /// This returns the public key of the SAS object that can then be shared
    /// with another user to perform the authentication process.
    pub fn public_key(&self) -> String {
        let pubkey_length = unsafe { olm_sys::olm_sas_pubkey_length(self.sas_ptr) };

        let mut buffer: Vec<u8> = vec![0; pubkey_length];

        let ret = unsafe {
            olm_sys::olm_sas_get_pubkey(self.sas_ptr, buffer.as_mut_ptr() as *mut _, pubkey_length)
        };

        if ret == errors::olm_error() {
            errors::handle_fatal_error(Self::last_error(self.sas_ptr));
        }

        unsafe { String::from_utf8_unchecked(buffer) }
    }

    /// Returns the last error that occurred for an OlmSas object.
    /// Since error codes are encoded as CStrings by libolm,
    /// OlmSasError::Unknown is returned on an unknown error code.
    fn last_error(sas_ptr: *mut olm_sys::OlmSAS) -> OlmSasError {
        let error = unsafe {
            let error_raw = olm_sys::olm_sas_last_error(sas_ptr);
            CStr::from_ptr(error_raw).to_str().unwrap()
        };

        match error {
            "NOT_ENOUGH_RANDOM" => OlmSasError::NotEnoughRandom,
            "OUTPUT_BUFFER_TOO_SMALL" => OlmSasError::OutputBufferTooSmall,
            "INPUT_BUFFER_TOO_SMALL" => OlmSasError::OutputBufferTooSmall,
            _ => OlmSasError::Unknown,
        }
    }

    /// Set the public key of the other user.
    ///
    /// This sets the public key of the other user, it needs to be set before
    /// bytes can be generated for the authentication string and a MAC can be
    /// calculated.
    ///
    /// Returns an error if the public key was too short or invalid.
    ///
    /// # Arguments
    ///
    /// * `public_key` - The public key of the other user.
    pub fn set_their_public_key(&mut self, public_key: String) -> Result<(), OlmSasError> {
        let ret = unsafe {
            olm_sys::olm_sas_set_their_key(
                self.sas_ptr,
                public_key.as_ptr() as *mut _,
                public_key.len(),
            )
        };

        if ret == errors::olm_error() {
            Err(Self::last_error(self.sas_ptr))
        } else {
            self.public_key_set = true;
            Ok(())
        }
    }

    /// Generate bytes to use for the short authentication string.
    ///
    /// Note the other public key needs to be set for this method to work.
    /// Returns an error if it isn't set.
    ///
    /// # Arguments
    ///
    /// * `extra_info` - Extra information to mix in when generating the
    ///     bytes.
    ///
    /// * `length` - The number of bytes to generate.
    pub fn generate_bytes(&self, extra_info: &str, length: usize) -> Result<Vec<u8>, OlmSasError> {
        if !self.public_key_set {
            return Err(OlmSasError::OtherPublicKeyUnset);
        } else if length < 1 {
            return Err(OlmSasError::InvalidLength);
        }

        let mut out_buffer = vec![0; length];

        let ret = unsafe {
            olm_sys::olm_sas_generate_bytes(
                self.sas_ptr,
                extra_info.as_ptr() as *mut _,
                extra_info.len(),
                out_buffer.as_mut_ptr() as *mut _,
                length,
            )
        };

        if ret == errors::olm_error() {
            Err(Self::last_error(self.sas_ptr))
        } else {
            Ok(out_buffer)
        }
    }

    /// Generate a message authentication code based on the shared secret.
    ///
    /// Note the other public key needs to be set for this method to work.
    /// Returns an error if it isn't set.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to produce the authentication code for.
    ///
    /// * `extra_info` - Extra information to mix in when generating the MAC.
    pub fn calculate_mac(&self, message: &str, extra_info: &str) -> Result<String, OlmSasError> {
        if !self.public_key_set {
            return Err(OlmSasError::OtherPublicKeyUnset);
        }

        let mac_length = unsafe { olm_sys::olm_sas_mac_length(self.sas_ptr) };
        let mut mac_buffer = vec![0; mac_length];

        let ret = unsafe {
            olm_sys::olm_sas_calculate_mac(
                self.sas_ptr,
                message.as_ptr() as *mut _,
                message.len(),
                extra_info.as_ptr() as *mut _,
                extra_info.len(),
                mac_buffer.as_mut_ptr() as *mut _,
                mac_length,
            )
        };

        if ret == errors::olm_error() {
            Err(Self::last_error(self.sas_ptr))
        } else {
            Ok(unsafe { String::from_utf8_unchecked(mac_buffer) })
        }
    }
}

#[cfg(test)]
mod test {
    use crate::sas::OlmSas;

    #[test]
    fn test_creation() {
        let alice = OlmSas::new();
        assert!(!alice.public_key().is_empty());
    }

    #[test]
    fn test_set_pubkey() {
        let mut alice = OlmSas::new();

        assert!(alice.set_their_public_key(alice.public_key()).is_ok());
        assert!(alice.set_their_public_key("".to_string()).is_err());
    }

    #[test]
    fn test_generate_bytes() {
        let mut alice = OlmSas::new();
        let mut bob = OlmSas::new();

        assert!(alice.generate_bytes("", 5).is_err());

        assert!(alice.set_their_public_key(bob.public_key()).is_ok());
        assert!(bob.set_their_public_key(alice.public_key()).is_ok());

        assert_eq!(
            alice.generate_bytes("", 5).unwrap(),
            bob.generate_bytes("", 5).unwrap()
        );
        assert_ne!(
            alice.generate_bytes("fake", 5).unwrap(),
            bob.generate_bytes("", 5).unwrap()
        );
    }

    #[test]
    fn test_calculate_mac() {
        let mut alice = OlmSas::new();
        let mut bob = OlmSas::new();

        let message = "It's a secret to everyone";

        assert!(alice.calculate_mac(message, "").is_err());

        assert!(alice.set_their_public_key(bob.public_key()).is_ok());
        assert!(bob.set_their_public_key(alice.public_key()).is_ok());

        assert_eq!(
            alice.calculate_mac(message, "").unwrap(),
            bob.calculate_mac(message, "").unwrap()
        );
        assert_ne!(
            alice.calculate_mac("fake", "").unwrap(),
            bob.calculate_mac(message, "").unwrap()
        );
    }
}