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
// Copyright 2020 Johannes Hayeß
//
// 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_utility_*`.

use crate::errors::{self, OlmUtilityError};
use std::ffi::CStr;

pub struct OlmUtility {
    olm_utility_ptr: *mut olm_sys::OlmUtility,
    olm_utility_buf_ptr: *mut [u8],
}

/// Allows you to make use of crytographic hashing via SHA-2 and
/// verifying ed25519 signatures.
impl OlmUtility {
    /// Creates a new instance of OlmUtility.
    ///
    /// # C-API equivalent
    /// `olm_utility`
    ///
    pub fn new() -> Self {
        // allocate the buffer for OlmUtility to be written into
        let olm_utility_buf: Vec<u8> = vec![0; unsafe { olm_sys::olm_utility_size() }];
        let olm_utility_buf_ptr = Box::into_raw(olm_utility_buf.into_boxed_slice());

        let olm_utility_ptr = unsafe { olm_sys::olm_utility(olm_utility_buf_ptr as *mut _) };

        Self {
            olm_utility_ptr,
            olm_utility_buf_ptr,
        }
    }

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

        match error {
            "BAD_MESSAGE_MAC" => OlmUtilityError::BadMessageMac,
            "OUTPUT_BUFFER_TOO_SMALL" => OlmUtilityError::OutputBufferTooSmall,
            "INVALID_BASE64" => OlmUtilityError::InvalidBase64,
            _ => OlmUtilityError::Unknown,
        }
    }

    /// Returns a sha256 of the supplied byte slice.
    ///
    /// # C-API equivalent
    /// `olm_sha256`
    ///
    /// # Panics
    /// * `OUTPUT_BUFFER_TOO_SMALL` for supplied output buffer
    /// * on malformed UTF-8 coding of the hash provided by libolm
    ///
    pub fn sha256_bytes(&self, input_buf: &[u8]) -> String {
        let output_len = unsafe { olm_sys::olm_sha256_length(self.olm_utility_ptr) };
        let mut output_buf = vec![0; output_len];

        let sha256_error = unsafe {
            olm_sys::olm_sha256(
                self.olm_utility_ptr,
                input_buf.as_ptr() as *const _,
                input_buf.len(),
                output_buf.as_mut_ptr() as *mut _,
                output_len,
            )
        };

        // We assume a correct implementation of the SHA256 function here,
        // that always returns a valid UTF-8 string.
        let sha256_result = String::from_utf8(output_buf).unwrap();

        // Errors from sha256 are fatal
        if sha256_error == errors::olm_error() {
            errors::handle_fatal_error(Self::last_error(self.olm_utility_ptr));
        }

        sha256_result
    }

    /// Convenience function that converts the UTF-8 message
    /// to bytes and then calls `sha256_bytes()`, returning its output.
    pub fn sha256_utf8_msg(&self, msg: &str) -> String {
        self.sha256_bytes(msg.as_bytes())
    }

    /// Verify a ed25519 signature.
    ///
    /// # Arugments
    /// * `key` - The public part of the ed25519 key that signed the message.
    /// * `message` - The message that was signed.
    /// * `signature` - The signature of the message.
    ///
    /// # C-API equivalent
    /// `olm_ed25519_verify`
    ///
    pub fn ed25519_verify(
        &self,
        key: &str,
        message: &str,
        signature: &str,
    ) -> Result<bool, OlmUtilityError> {
        let ed25519_verify_error = unsafe {
            olm_sys::olm_ed25519_verify(
                self.olm_utility_ptr,
                key.as_ptr() as *const _,
                key.len(),
                message.as_ptr() as *const _,
                message.len(),
                signature.as_ptr() as *mut _,
                signature.len(),
            )
        };

        // Since the two values are the same it is safe to copy
        let ed25519_verify_result: usize = ed25519_verify_error;

        if ed25519_verify_error == errors::olm_error() {
            Err(Self::last_error(self.olm_utility_ptr))
        } else {
            Ok(ed25519_verify_result == 0)
        }
    }
}

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

impl Drop for OlmUtility {
    fn drop(&mut self) {
        unsafe {
            olm_sys::olm_clear_utility(self.olm_utility_ptr);
            let _drop_utility_buf = Box::from_raw(self.olm_utility_buf_ptr);
        }
    }
}