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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::vault_types::{FfiSecretAttributes, SecretKeyHandle};
use crate::{check_buffer, FfiError, FfiObjectMutexStorage, FfiOckamError};
use crate::{FfiVaultFatPointer, FfiVaultType};
use core::convert::{TryFrom, TryInto};
use core::ops::DerefMut;
use core::slice;
use lazy_static::lazy_static;
use ockam_core::compat::sync::{Arc, Mutex};
use ockam_vault::SoftwareVault;
use ockam_vault_core::{
    AsymmetricVault, Hasher, PublicKey, Secret, SecretAttributes, SecretType, SecretVault,
    SymmetricVault,
};

/// FFI Vault trait. See documentation for individual sub-traits for details.
pub trait FfiVault: SecretVault + Hasher + SymmetricVault + AsymmetricVault + Send {}

impl<D> FfiVault for D where D: SecretVault + Hasher + SymmetricVault + AsymmetricVault + Send {}

lazy_static! {
    pub(crate) static ref DEFAULT_VAULTS: FfiObjectMutexStorage<SoftwareVault> =
        FfiObjectMutexStorage::default();
}

fn call<F, R>(context: FfiVaultFatPointer, callback: F) -> Result<R, FfiOckamError>
where
    F: FnOnce(&mut dyn FfiVault) -> Result<R, FfiOckamError>,
{
    match context.vault_type() {
        FfiVaultType::Software => {
            let item = DEFAULT_VAULTS.get_object(context.handle())?;
            let mut item = item.lock().unwrap();

            callback(item.deref_mut())
        }
    }
}

/// Create and return a default Ockam Vault.
#[no_mangle]
pub extern "C" fn ockam_vault_default_init(context: &mut FfiVaultFatPointer) -> FfiOckamError {
    // TODO: handle logging
    let handle = match DEFAULT_VAULTS.insert_object(Arc::new(Mutex::new(SoftwareVault::default())))
    {
        Ok(handle) => handle,
        Err(err) => return err,
    };

    *context = FfiVaultFatPointer::new(handle, FfiVaultType::Software);

    FfiOckamError::none()
}

/// Compute the SHA-256 hash on `input` and put the result in `digest`.
/// `digest` must be 32 bytes in length.
#[no_mangle]
pub extern "C" fn ockam_vault_sha256(
    context: FfiVaultFatPointer,
    input: *const u8,
    input_length: u32,
    digest: *mut u8,
) -> FfiOckamError {
    check_buffer!(input);
    check_buffer!(digest);

    let input = unsafe { std::slice::from_raw_parts(input, input_length as usize) };

    match call(context, |v| -> Result<(), FfiOckamError> {
        let d = v.sha256(input)?;

        unsafe {
            std::ptr::copy_nonoverlapping(d.as_ptr(), digest, d.len());
        }

        Ok(())
    }) {
        Ok(_) => FfiOckamError::none(),
        Err(err) => err,
    }
}

/// Generate a secret key with the specific attributes.
/// Returns a handle for the secret.
#[no_mangle]
pub extern "C" fn ockam_vault_secret_generate(
    context: FfiVaultFatPointer,
    secret: &mut SecretKeyHandle,
    attributes: FfiSecretAttributes,
) -> FfiOckamError {
    *secret = match call(context, |v| -> Result<SecretKeyHandle, FfiOckamError> {
        let atts = attributes.try_into()?;
        let ctx = v.secret_generate(atts)?;
        Ok(ctx.index() as u64)
    }) {
        Ok(h) => h,
        Err(err) => return err,
    };

    FfiOckamError::none()
}

/// Import a secret key with the specific handle and attributes.
#[no_mangle]
pub extern "C" fn ockam_vault_secret_import(
    context: FfiVaultFatPointer,
    secret: &mut SecretKeyHandle,
    attributes: FfiSecretAttributes,
    input: *mut u8,
    input_length: u32,
) -> FfiOckamError {
    check_buffer!(input, input_length);

    *secret = match call(context, |v| -> Result<SecretKeyHandle, FfiOckamError> {
        let atts = attributes.try_into()?;

        let secret_data = unsafe { std::slice::from_raw_parts(input, input_length as usize) };

        let ctx = v.secret_import(secret_data, atts)?;
        Ok(ctx.index() as u64)
    }) {
        Ok(s) => s,
        Err(err) => return err,
    };

    FfiOckamError::none()
}

/// Export a secret key with the specific handle to the `output_buffer`.
#[no_mangle]
pub extern "C" fn ockam_vault_secret_export(
    context: FfiVaultFatPointer,
    secret: SecretKeyHandle,
    output_buffer: &mut u8,
    output_buffer_size: u32,
    output_buffer_length: &mut u32,
) -> FfiOckamError {
    *output_buffer_length = 0;
    match call(context, |v| -> Result<(), FfiOckamError> {
        let ctx = Secret::new(secret as usize);
        let key = v.secret_export(&ctx)?;
        if output_buffer_size < key.as_ref().len() as u32 {
            return Err(FfiError::BufferTooSmall.into());
        }
        *output_buffer_length = key.as_ref().len() as u32;

        unsafe {
            std::ptr::copy_nonoverlapping(key.as_ref().as_ptr(), output_buffer, key.as_ref().len());
        };
        Ok(())
    }) {
        Ok(_) => FfiOckamError::none(),
        Err(err) => err,
    }
}

/// Get the public key, given a secret key, and copy it to the output buffer.
#[no_mangle]
pub extern "C" fn ockam_vault_secret_publickey_get(
    context: FfiVaultFatPointer,
    secret: SecretKeyHandle,
    output_buffer: &mut u8,
    output_buffer_size: u32,
    output_buffer_length: &mut u32,
) -> FfiOckamError {
    *output_buffer_length = 0;
    match call(context, |v| -> Result<(), FfiOckamError> {
        let ctx = Secret::new(secret as usize);
        let key = v.secret_public_key_get(&ctx)?;
        if output_buffer_size < key.as_ref().len() as u32 {
            return Err(FfiError::BufferTooSmall.into());
        }
        *output_buffer_length = key.as_ref().len() as u32;

        unsafe {
            std::ptr::copy_nonoverlapping(key.as_ref().as_ptr(), output_buffer, key.as_ref().len());
        };
        Ok(())
    }) {
        Ok(_) => FfiOckamError::none(),
        Err(err) => err,
    }
}

/// Retrieve the attributes for a specified secret.
#[no_mangle]
pub extern "C" fn ockam_vault_secret_attributes_get(
    context: FfiVaultFatPointer,
    secret: SecretKeyHandle,
    attributes: &mut FfiSecretAttributes,
) -> FfiOckamError {
    *attributes = match call(context, |v| -> Result<FfiSecretAttributes, FfiOckamError> {
        let ctx = Secret::new(secret as usize);
        let atts = v.secret_attributes_get(&ctx)?;
        Ok(atts.into())
    }) {
        Ok(a) => a,
        Err(err) => return err,
    };

    FfiOckamError::none()
}

/// Delete an ockam vault secret.
#[no_mangle]
pub extern "C" fn ockam_vault_secret_destroy(
    context: FfiVaultFatPointer,
    secret: SecretKeyHandle,
) -> FfiOckamError {
    match call(context, |v| -> Result<(), FfiOckamError> {
        let ctx = Secret::new(secret as usize);
        v.secret_destroy(ctx)?;
        Ok(())
    }) {
        Ok(_) => FfiOckamError::none(),
        Err(err) => err,
    }
}

/// Perform an ECDH operation on the supplied Ockam Vault `secret` and `peer_publickey`. The result
/// is an Ockam Vault secret of unknown type.
#[no_mangle]
pub extern "C" fn ockam_vault_ecdh(
    context: FfiVaultFatPointer,
    secret: SecretKeyHandle,
    peer_publickey: *const u8,
    peer_publickey_length: u32,
    shared_secret: &mut SecretKeyHandle,
) -> FfiOckamError {
    check_buffer!(peer_publickey, peer_publickey_length);

    let peer_publickey =
        unsafe { std::slice::from_raw_parts(peer_publickey, peer_publickey_length as usize) };
    *shared_secret = match call(context, |v| -> Result<u64, FfiOckamError> {
        let ctx = Secret::new(secret as usize);
        let atts = v.secret_attributes_get(&ctx)?;
        let pubkey = match atts.stype() {
            SecretType::Curve25519 => {
                if peer_publickey.len() != 32 {
                    Err(FfiError::InvalidPublicKey)
                } else {
                    Ok(PublicKey::new(peer_publickey.to_vec()))
                }
            }
            SecretType::P256 => {
                if peer_publickey.len() != 65 {
                    Err(FfiError::InvalidPublicKey)
                } else {
                    Ok(PublicKey::new(peer_publickey.to_vec()))
                }
            }
            _ => Err(FfiError::UnknownPublicKeyType),
        }?;
        let shared_ctx = v.ec_diffie_hellman(&ctx, &pubkey)?;
        Ok(shared_ctx.index() as u64)
    }) {
        Ok(s) => s,
        Err(err) => return err,
    };

    FfiOckamError::none()
}

/// Perform an HMAC-SHA256 based key derivation function on the supplied salt and input key
/// material.
#[no_mangle]
pub extern "C" fn ockam_vault_hkdf_sha256(
    context: FfiVaultFatPointer,
    salt: SecretKeyHandle,
    input_key_material: *const SecretKeyHandle,
    derived_outputs_attributes: *const FfiSecretAttributes,
    derived_outputs_count: u8,
    derived_outputs: *mut SecretKeyHandle,
) -> FfiOckamError {
    let derived_outputs_count = derived_outputs_count as usize;
    match call(context, |v| -> Result<(), FfiOckamError> {
        let salt_ctx = Secret::new(salt as usize);
        let ikm_ctx = if input_key_material.is_null() {
            None
        } else {
            let ctx = unsafe { Secret::new(*input_key_material as usize) };
            Some(ctx)
        };
        let ikm_ctx = ikm_ctx.as_ref();

        let array: &[FfiSecretAttributes] =
            unsafe { slice::from_raw_parts(derived_outputs_attributes, derived_outputs_count) };

        let mut output_attributes = Vec::<SecretAttributes>::with_capacity(array.len());
        for x in array.iter() {
            output_attributes.push(SecretAttributes::try_from(*x)?);
        }

        // TODO: Hardcoded to be empty for now because any changes
        // to the C layer requires an API change.
        // This change was necessary to implement Enrollment since the info string is not
        // left blank for that protocol, but is blank for the XX key exchange pattern.
        // If we agree to change the API, then this wouldn't be hardcoded but received
        // from a parameter in the C API. Elixir and other consumers would be expected
        // to pass the appropriate flag. The other option is to not expose the vault
        // directly since it may confuse users about what to pass here and
        // I don't like the idea of yelling at consumers through comments.
        // Instead the vault could be encapsulated in channels and key exchanges.
        // Either way, I don't want to change the API until this decision is finalized.
        let hkdf_output = v.hkdf_sha256(&salt_ctx, b"", ikm_ctx, output_attributes)?;

        let hkdf_output: Vec<SecretKeyHandle> =
            hkdf_output.into_iter().map(|x| x.index() as u64).collect();

        unsafe {
            std::ptr::copy_nonoverlapping(
                hkdf_output.as_ptr(),
                derived_outputs,
                derived_outputs_count,
            )
        };
        Ok(())
    }) {
        Ok(_) => FfiOckamError::none(),
        Err(err) => err,
    }
}

///   Encrypt a payload using AES-GCM.
#[no_mangle]
pub extern "C" fn ockam_vault_aead_aes_gcm_encrypt(
    context: FfiVaultFatPointer,
    secret: SecretKeyHandle,
    nonce: u16,
    additional_data: *const u8,
    additional_data_length: u32,
    plaintext: *const u8,
    plaintext_length: u32,
    ciphertext_and_tag: &mut u8,
    ciphertext_and_tag_size: u32,
    ciphertext_and_tag_length: &mut u32,
) -> FfiOckamError {
    check_buffer!(additional_data);
    check_buffer!(plaintext);
    *ciphertext_and_tag_length = 0;

    let additional_data =
        unsafe { std::slice::from_raw_parts(additional_data, additional_data_length as usize) };

    let plaintext = unsafe { std::slice::from_raw_parts(plaintext, plaintext_length as usize) };
    match call(context, |v| -> Result<(), FfiOckamError> {
        let ctx = Secret::new(secret as usize);
        let mut nonce_vec = vec![0; 12 - 2];
        nonce_vec.extend_from_slice(&nonce.to_be_bytes());
        let ciphertext = v.aead_aes_gcm_encrypt(&ctx, plaintext, &nonce_vec, additional_data)?;

        if ciphertext_and_tag_size < ciphertext.len() as u32 {
            return Err(FfiError::BufferTooSmall.into());
        }
        *ciphertext_and_tag_length = ciphertext.len() as u32;

        unsafe {
            std::ptr::copy_nonoverlapping(ciphertext.as_ptr(), ciphertext_and_tag, ciphertext.len())
        };
        Ok(())
    }) {
        Ok(_) => FfiOckamError::none(),
        Err(err) => err,
    }
}

/// Decrypt a payload using AES-GCM.
#[no_mangle]
pub extern "C" fn ockam_vault_aead_aes_gcm_decrypt(
    context: FfiVaultFatPointer,
    secret: SecretKeyHandle,
    nonce: u16,
    additional_data: *const u8,
    additional_data_length: u32,
    ciphertext_and_tag: *const u8,
    ciphertext_and_tag_length: u32,
    plaintext: &mut u8,
    plaintext_size: u32,
    plaintext_length: &mut u32,
) -> FfiOckamError {
    check_buffer!(ciphertext_and_tag, ciphertext_and_tag_length);
    check_buffer!(additional_data);
    *plaintext_length = 0;

    let additional_data =
        unsafe { std::slice::from_raw_parts(additional_data, additional_data_length as usize) };

    let ciphertext_and_tag = unsafe {
        std::slice::from_raw_parts(ciphertext_and_tag, ciphertext_and_tag_length as usize)
    };
    match call(context, |v| -> Result<(), FfiOckamError> {
        let ctx = Secret::new(secret as usize);
        let mut nonce_vec = vec![0; 12 - 2];
        nonce_vec.extend_from_slice(&nonce.to_be_bytes());
        let plain =
            v.aead_aes_gcm_decrypt(&ctx, ciphertext_and_tag, &nonce_vec, additional_data)?;
        if plaintext_size < plain.len() as u32 {
            return Err(FfiError::BufferTooSmall.into());
        }
        *plaintext_length = plain.len() as u32;

        unsafe { std::ptr::copy_nonoverlapping(plain.as_ptr(), plaintext, plain.len()) };
        Ok(())
    }) {
        Ok(_) => FfiOckamError::none(),
        Err(err) => err,
    }
}

/// De-initialize an Ockam Vault.
#[no_mangle]
pub extern "C" fn ockam_vault_deinit(context: FfiVaultFatPointer) -> FfiOckamError {
    match context.vault_type() {
        FfiVaultType::Software => match DEFAULT_VAULTS.remove_object(context.handle()) {
            Ok(_) => FfiOckamError::none(),
            Err(_) => FfiError::VaultNotFound.into(),
        },
    }
}