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
use {App, AppContext};
use errors::AppError;
use ffi_utils::{FFI_RESULT_OK, FfiResult, OpaqueCtx, catch_unwind_cb};
use maidsafe_utilities::serialisation::{deserialise, serialise};
use object_cache::{CipherOptHandle, EncryptPubKeyHandle};
use rust_sodium::crypto::{box_, sealedbox, secretbox};
use safe_core::{Client, CoreError};
use std::os::raw::c_void;
#[derive(Debug)]
pub enum CipherOpt {
PlainText,
Symmetric,
Asymmetric {
peer_encrypt_key: box_::PublicKey,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum WireFormat {
Plain(Vec<u8>),
Symmetric {
nonce: secretbox::Nonce,
cipher_text: Vec<u8>,
},
Asymmetric(Vec<u8>),
}
impl CipherOpt {
pub fn encrypt(&self, plain_text: &[u8], app_ctx: &AppContext) -> Result<Vec<u8>, AppError> {
match *self {
CipherOpt::PlainText => Ok(serialise(&WireFormat::Plain(plain_text.to_owned()))?),
CipherOpt::Symmetric => {
let nonce = secretbox::gen_nonce();
let cipher_text = secretbox::seal(plain_text, &nonce, app_ctx.sym_enc_key()?);
let wire_format = WireFormat::Symmetric {
nonce: nonce,
cipher_text: cipher_text,
};
Ok(serialise(&wire_format)?)
}
CipherOpt::Asymmetric { ref peer_encrypt_key } => {
let cipher_text = sealedbox::seal(plain_text, peer_encrypt_key);
Ok(serialise(&WireFormat::Asymmetric(cipher_text))?)
}
}
}
pub fn decrypt(
cipher_text: &[u8],
app_ctx: &AppContext,
client: &Client<AppContext>,
) -> Result<Vec<u8>, AppError> {
if cipher_text.is_empty() {
return Ok(Vec::new());
}
match deserialise::<WireFormat>(cipher_text)? {
WireFormat::Plain(plain_text) => Ok(plain_text),
WireFormat::Symmetric { nonce, cipher_text } => {
Ok(secretbox::open(&cipher_text, &nonce, app_ctx.sym_enc_key()?)
.map_err(|()| CoreError::SymmetricDecipherFailure)?)
}
WireFormat::Asymmetric(cipher_text) => {
let (asym_pk, asym_sk) = client.encryption_keypair()?;
Ok(sealedbox::open(&cipher_text, &asym_pk, &asym_sk)
.map_err(|()| CoreError::AsymmetricDecipherFailure)?)
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn cipher_opt_new_plaintext(
app: *const App,
user_data: *mut c_void,
o_cb: extern "C" fn(user_data: *mut c_void,
result: FfiResult,
handle: CipherOptHandle),
) {
let user_data = OpaqueCtx(user_data);
catch_unwind_cb(user_data, o_cb, || {
(*app).send(move |_, context| {
let handle = context.object_cache().insert_cipher_opt(
CipherOpt::PlainText,
);
o_cb(user_data.0, FFI_RESULT_OK, handle);
None
})
});
}
#[no_mangle]
pub unsafe extern "C" fn cipher_opt_new_symmetric(
app: *const App,
user_data: *mut c_void,
o_cb: extern "C" fn(user_data: *mut c_void,
result: FfiResult,
handle: CipherOptHandle),
) {
catch_unwind_cb(user_data, o_cb, || {
let user_data = OpaqueCtx(user_data);
(*app).send(move |_, context| {
let handle = context.object_cache().insert_cipher_opt(
CipherOpt::Symmetric,
);
o_cb(user_data.0, FFI_RESULT_OK, handle);
None
})
})
}
#[no_mangle]
pub unsafe extern "C" fn cipher_opt_new_asymmetric(
app: *const App,
peer_encrypt_key_h: EncryptPubKeyHandle,
user_data: *mut c_void,
o_cb: extern "C" fn(user_data: *mut c_void,
result: FfiResult,
handle: CipherOptHandle),
) {
let user_data = OpaqueCtx(user_data);
catch_unwind_cb(user_data, o_cb, || {
(*app).send(move |_, context| {
let pk = match context.object_cache().get_encrypt_key(peer_encrypt_key_h) {
Ok(pk) => *pk,
res @ Err(..) => {
call_result_cb!(res, user_data, o_cb);
return None;
}
};
let handle = context.object_cache().insert_cipher_opt(
CipherOpt::Asymmetric {
peer_encrypt_key: pk,
},
);
o_cb(user_data.0, FFI_RESULT_OK, handle);
None
})
});
}
#[no_mangle]
pub unsafe extern "C" fn cipher_opt_free(
app: *const App,
handle: CipherOptHandle,
user_data: *mut c_void,
o_cb: extern "C" fn(user_data: *mut c_void, result: FfiResult),
) {
let user_data = OpaqueCtx(user_data);
catch_unwind_cb(user_data, o_cb, || {
(*app).send(move |_, context| {
let res = context.object_cache().remove_cipher_opt(handle);
call_result_cb!(res, user_data, o_cb);
None
})
});
}
#[cfg(test)]
mod tests {
use super::*;
use {App, AppContext};
use errors::AppError;
use ffi_utils::ErrorCode;
use ffi_utils::test_utils::{call_0, call_1};
use object_cache::CipherOptHandle;
use rust_sodium::crypto::box_;
use safe_core::{Client, utils};
use test_utils::{create_app, run_now};
#[test]
fn app_0_to_app_0_plain() {
let app_0 = create_app();
let plain_text = unwrap!(utils::generate_random_vector::<u8>(10));
let cipher_opt_handle: CipherOptHandle =
unsafe { unwrap!(call_1(|ud, cb| cipher_opt_new_plaintext(&app_0, ud, cb))) };
let (plain_text, cipher_text) = run_now(&app_0, move |_, context| {
let cipher_opt = unwrap!(context.object_cache().get_cipher_opt(cipher_opt_handle));
let cipher_text = unwrap!(cipher_opt.encrypt(&plain_text, context));
(plain_text, cipher_text)
});
assert_ne!(cipher_text, plain_text);
assert_free(&app_0, cipher_opt_handle, 0);
run_now(&app_0, move |client, context| {
assert!(
context
.object_cache()
.get_cipher_opt(cipher_opt_handle)
.is_err()
);
assert!(decrypt_and_check(
client,
context,
&cipher_text,
&plain_text,
));
});
}
#[test]
fn app_0_to_app_0_sym() {
let app_0 = create_app();
let plain_text = unwrap!(utils::generate_random_vector::<u8>(10));
let cipher_opt_handle: CipherOptHandle =
unsafe { unwrap!(call_1(|ud, cb| cipher_opt_new_symmetric(&app_0, ud, cb))) };
let (plain_text, cipher_text) = run_now(&app_0, move |_, context| {
let cipher_opt = unwrap!(context.object_cache().get_cipher_opt(cipher_opt_handle));
let cipher_text = unwrap!(cipher_opt.encrypt(&plain_text, context));
(plain_text, cipher_text)
});
assert_ne!(cipher_text, plain_text);
assert_free(&app_0, cipher_opt_handle, 0);
run_now(&app_0, move |client, context| {
assert!(
context
.object_cache()
.get_cipher_opt(cipher_opt_handle)
.is_err()
);
assert!(decrypt_and_check(
client,
context,
&cipher_text,
&plain_text,
));
});
}
#[cfg_attr(rustfmt, rustfmt_skip)]
#[test]
fn app_0_to_app_1_asym() {
let app_0 = create_app();
let app_1 = create_app();
let enc_pk = run_now(&app_1,
move |client, _| unwrap!(client.public_encryption_key()));
let enc_pk_h = run_now(&app_0, move |_, context| {
context.object_cache().insert_encrypt_key(enc_pk)
});
let cipher_opt_h = unsafe {
unwrap!(call_1(|ud, cb| cipher_opt_new_asymmetric(&app_0, enc_pk_h, ud, cb)))
};
let plain_text = unwrap!(utils::generate_random_vector::<u8>(10));
let (plain_text, cipher_text) = run_now(&app_0, move |_, context| {
let cipher_opt = unwrap!(context.object_cache().get_cipher_opt(cipher_opt_h));
let cipher_text = unwrap!(cipher_opt.encrypt(&plain_text, context));
(plain_text, cipher_text)
});
assert_ne!(cipher_text, plain_text);
assert_free(&app_0, cipher_opt_h, 0);
run_now(&app_0, move |_, context| {
assert!(context.object_cache().get_cipher_opt(cipher_opt_h).is_err());
});
let (plain_text, cipher_text) = run_now(&app_0, move |client, context| {
assert!(!decrypt_and_check(client, context, &cipher_text, &plain_text));
(plain_text, cipher_text)
});
run_now(&app_1, move |client, context| {
assert!(decrypt_and_check(client, context, &cipher_text, &plain_text));
});
}
#[test]
fn create_and_free() {
let app = create_app();
let peer_encrypt_key_handle = run_now(&app, |_, context| {
let (pk, _) = box_::gen_keypair();
context.object_cache().insert_encrypt_key(pk)
});
let cipher_opt_handle_pt =
unsafe { unwrap!(call_1(|ud, cb| cipher_opt_new_plaintext(&app, ud, cb))) };
let cipher_opt_handle_sym =
unsafe { unwrap!(call_1(|ud, cb| cipher_opt_new_symmetric(&app, ud, cb))) };
let cipher_opt_handle_asym = unsafe {
let err_code = AppError::InvalidEncryptPubKeyHandle.error_code();
let res: Result<CipherOptHandle, _> =
call_1(|ud, cb| cipher_opt_new_asymmetric(&app, 29293290, ud, cb));
assert_eq!(unwrap!(res.err()), err_code);
unwrap!(call_1(|ud, cb| {
cipher_opt_new_asymmetric(&app, peer_encrypt_key_handle, ud, cb)
}))
};
run_now(&app, move |_, context| {
let obj_cache = context.object_cache();
let _ = unwrap!(obj_cache.get_cipher_opt(cipher_opt_handle_pt));
let _ = unwrap!(obj_cache.get_cipher_opt(cipher_opt_handle_sym));
let _ = unwrap!(obj_cache.get_cipher_opt(cipher_opt_handle_asym));
});
assert_free(&app, cipher_opt_handle_pt, 0);
assert_free(&app, cipher_opt_handle_sym, 0);
assert_free(&app, cipher_opt_handle_asym, 0);
let err_code = AppError::InvalidCipherOptHandle.error_code();
assert_free(&app, cipher_opt_handle_pt, err_code);
assert_free(&app, cipher_opt_handle_sym, err_code);
assert_free(&app, cipher_opt_handle_asym, err_code);
run_now(&app, move |_, context| {
let obj_cache = context.object_cache();
assert!(obj_cache.get_cipher_opt(cipher_opt_handle_pt).is_err());
assert!(obj_cache.get_cipher_opt(cipher_opt_handle_sym).is_err());
assert!(obj_cache.get_cipher_opt(cipher_opt_handle_asym).is_err());
})
}
fn decrypt_and_check(
client: &Client<AppContext>,
context: &AppContext,
cipher_text: &[u8],
orig_plain_text: &[u8],
) -> bool {
let plain_text = match CipherOpt::decrypt(cipher_text, context, client) {
Ok(text) => text,
Err(_) => return false,
};
orig_plain_text == &plain_text[..]
}
fn assert_free(app_ptr: *const App, cipher_opt_handle: CipherOptHandle, expected: i32) {
let res = unsafe {
call_0(|user_data, cb| {
cipher_opt_free(app_ptr, cipher_opt_handle, user_data, cb)
})
};
match res {
Ok(()) => assert_eq!(expected, 0),
Err(code) => assert_eq!(expected, code),
}
}
}