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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Various utility and memory safety functions.
use ;
use ;
use slice;
use str;
extern "C"
/// After use, sensitive data should be overwritten, but *memset()* and
/// hand-written code can be silently stripped out by an optimizing compiler or
/// by the linker.
///
/// The *memzero()* function tries to effectively zero the bytes in *mem*, even
/// if optimizations are being applied to the code. This function safely wraps
/// a call to *sodium_memzero()*.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::secmem::memzero;
///
/// let v = [0, 1, 2, 3, 4, 5, 6, 7];
/// memzero(&v);
/// assert!(v == [0; 8]);
/// ```
/// When a comparison involves secret data (e.g. key, authentication tag), is it
/// critical to use a constant-time comparison function in order to mitigate
/// side-channel attacks.
///
/// The *memcmp()* function can be used for this purpose.
///
/// The function returns 0 if the bytes pointed to by *m1* match the bytes
/// pointed to by *m2*. Otherwise, it returns -1.
///
/// Note: *memcmp* safely wraps *sodium_memcmp*. *sodium_memcmp()* is not a
/// lexicographic comparator and is not a generic replacement for *memcmp()*.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::secmem::memcmp;
///
/// let v0 = [0, 1, 2, 3, 4, 5, 6, 7];
/// let v1 = [0, 1, 2, 3, 4, 5, 6, 7];
/// let v2 = [7, 6, 5, 4, 3, 2, 1, 0];
/// assert!(memcmp(&v0,&v1) == 0);
/// assert!(memcmp(&v0,&v2) == -1);
/// assert!(memcmp(&v1,&v2) == -1);
/// ```
/// The *bin2hex()* function converts a byte sequence into a hexadecimal string.
///
/// The *bin2hex()* function safely wraps the *sodium_bin2hex()* function.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::secmem::bin2hex;
///
/// let v = [0, 1, 254, 255];
/// assert!(bin2hex(&v).unwrap() == "0001feff");
/// ```
/// The *hex2bin()* function parses a hexadecimal string and converts it to a
/// byte sequence.
///
/// *ignore* is a string of characters to skip. For example, the string ": "
/// allows columns and spaces to be present at any locations in the hexadecimal
/// string. These characters will just be ignored. As a result, "69:FC",
/// "69 FC", "69 : FC" and "69FC" will be valid inputs, and will produce the
/// same output.
///
/// *ignore* can be set to None in order to disallow any non-hexadecimal
/// character.
///
/// The function returns -1 on failure. It returns 0 on success and sets
/// *output* to the byte sequence.
///
/// It evaluates in constant time for a given length and format.
///
/// *hex2bin()* safely wraps the *sodium_hex2bin()* function.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::secmem::hex2bin;
///
/// let hex = String::from("0001feff");
/// let mut output = Vec::new();
/// assert!(hex2bin(hex, &mut output, None) == 0);
/// assert!(output == [0, 1, 254, 255]);
///
/// let hex = String::from("00:01:fe:ff");
/// let ignore = Some(String::from(":"));
/// let mut output = Vec::new();
/// assert!(hex2bin(hex, &mut output, ignore) == 0);
/// assert!(output == [0, 1, 254, 255]);
///
/// let hex = String::from("00 01 fe ff");
/// let ignore = Some(String::from(" "));
/// let mut output = Vec::new();
/// assert!(hex2bin(hex, &mut output, ignore) == 0);
/// assert!(output == [0, 1, 254, 255]);
///
/// let hex = String::from("00 01:fe ff");
/// let ignore = Some(String::from(": "));
/// let mut output = Vec::new();
/// assert!(hex2bin(hex, &mut output, ignore) == 0);
/// assert!(output == [0, 1, 254, 255]);
/// ```
/// The *mlock()* function locks the bytes of the given array. This can help
/// avoid swapping sensitive data to disk.
///
/// In addition, it is recommended to totally disable swap partitions on
/// machines processing senstive data, or, as a second choice, use encrypted
/// swap partitions.
///
/// For similar reasons, on Unix systems, one should also disable core dumps
/// when running crypto code outside a development environment. This can be
/// achieved using a shell built-in such as ulimit or programatically using
/// ```setrlimit(RLIMIT_CORE, &(struct rlimit) {0, 0})```. On operating systems
/// where this feature is implemented, kernel crash dumps should also be
/// disabled.
///
/// *mlock()* safely wraps *sodium_mlock()* which wraps *mlock()* and
/// *VirtualLock()*. Note: Many systems place limits on the amount of memory
/// that may be locked by a process. Care should be taken to raise those limits
/// (e.g. Unix ulimits) where neccessary. *mlock()* will return -1 when any
/// limit is reached.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::secmem::mlock;
///
/// let v = [0, 1, 2, 3, 4, 5, 6, 7];
/// assert!(mlock(&v) == 0);
/// ```
/// The *munlock()* function should be called after locked memory is not being
/// used any more. It will zero the bytes in the array before actually flagging
/// the pages as swappable again. Calling *memzero()* prior to *munlock()* is
/// thus not required.
///
/// On systems where it is supported, *sodium_mlock()* also wraps *madvise()*
/// and advises the kernel not to include the locked memory in coredumps.
/// *ss_unlock()* also undoes this additional protection.
///
/// *munlock* safely wraps *sodium_munlock*.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::secmem::{mlock, munlock};
///
/// let v = [0, 1, 2, 3, 4, 5, 6, 7];
/// assert!(mlock(&v) == 0);
/// assert!(munlock(&v) == 0);
/// assert!(v == [0; 8]);
/// ```
/// The *malloc()* function returns a mutable array of bytes.
///
/// The allocated region is placed at the end of a page boundary, immediately
/// followed by a guard page. As a result, accessing memory past the end of the
/// region will immediately terminate the application.
///
/// A canary is also placed right before the returned pointer. Modification of
/// this canary are detected when trying to free the allocated region with
/// *free()*, and also cause the application to immediately terminate.
///
/// An additional guard page is placed before this canary to make it less
/// likely for sensitive data to be accessible when reading past the end of an
/// unrelated region.
///
/// The allocated region is filled with 0xd0 bytes in order to help catch bugs
/// due to initialized data.
///
/// In addition, *sodium_mlock()* is called on the region to help avoid it being
/// swapped to disk. On operating systems supporting MAP_NOCORE or
/// MADV_DONTDUMP, memory allocated this way will also not be part of core
/// dumps.
///
/// The returned address will not be aligned if the allocation size is not a
/// multiple of the
/// required alignment.
///
/// For this reason, *malloc()* should not be used with packed or
/// variable-length structures, unless the size given to *malloc()* is rounded
/// up in order to ensure proper alignment.
///
/// All the structures used by libsodium can safely be allocated using
/// *sodium_malloc()*, the only one requiring extra care being
/// crypto_generichash_state, whose size needs to be rounded up to a multiple
/// of 64 bytes.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init::init;
/// use sodium_sys::crypto::utils::secmem::{malloc,free};
///
/// let _ = init();
/// let mut v = malloc(64);
/// v[0] = 1;
/// assert!(v.len() == 64);
/// assert!(v[0] == 1);
/// free(v);
/// ```
/// The *allocarray()* function returns a mutable byte array.
///
/// It provides the same guarantees as *malloc()* but also protects against
/// arithmetic overflows when count * size exceeds SIZE_MAX.
///
/// *allocarray()* safely wraps *sodium_allocarray()*.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init::init;
/// use sodium_sys::crypto::utils::secmem::{allocarray,free};
///
/// let _ = init();
/// let mut v = allocarray(2, 16);
/// v[0] = 1;
/// assert!(v.len() == 32);
/// assert!(v[0] == 1);
/// free(v);
/// ```
/// The *free()* function unlocks and deallocates memory allocated using
/// *malloc()* or *allocarray()*.
///
/// Prior to this, the canary is checked in order to detect possible buffer
/// underflows and terminate the process if required.
///
/// *free()* also fills the memory region with zeros before the deallocation.
///
/// This function can be called even if the region was previously protected
/// using *mprotect_readonly()*; the protection will automatically be changed
/// as needed.
///
/// The *free()* function safely wraps the *sodium_free* function.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init::init;
/// use sodium_sys::crypto::utils::secmem::{malloc,free};
///
/// let _ = init();
/// let mut v = malloc(128);
/// v[0] = 1;
/// v[127] = 255;
/// assert!(v.len() == 128);
/// assert!(v[0] == 1);
/// assert!(v[127] == 255);
/// free(v);
/// ```
/// The *mprotect_noaccess()* function makes a region allocated using *malloc()*
/// or *allocarray()* inaccessible. It cannot be read or written, but the data
/// are preserved.
///
/// This function can be used to make confidential data inacessible except when
/// actually needed for a specific operation.
///
/// *mprotect_noaccess()* safely wraps the *sodium_mprotect_noaccess()*
/// function.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init::init;
/// use sodium_sys::crypto::utils::secmem::{free,malloc,mprotect_noaccess};
///
/// let _ = init();
/// let mut v = malloc(64);
/// v[0] = 1;
/// assert!(v.len() == 64);
/// assert!(v[0] == 1);
/// mprotect_noaccess(&mut v);
/// // If you uncomment the following line the program will fail (no read).
/// // assert!(v[0] == 1);
/// // If you uncomment the following line the program will fail (no write).
/// // v[1] = 1;
/// free(&mut v);
/// ```
/// The *mprotect_readonly()* function marks a region allocated using *malloc()*
/// or *allocarray()* as read-only.
///
/// Attempting to modify the data will cause the process to terminate.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init::init;
/// use sodium_sys::crypto::utils::secmem::{free,malloc,mprotect_readonly};
///
/// let _ = init();
/// let mut v = malloc(64);
/// v[0] = 1;
/// assert!(v.len() == 64);
/// assert!(v[0] == 1);
/// mprotect_readonly(&mut v);
/// assert!(v[0] == 1);
/// // If you uncomment the following line the program will fail (no write).
/// // v[1] = 1;
/// free(&mut v);
/// ```
/// The *mprotect_readwrite()* function marks a region allocated using
/// *malloc()* or *allocarray()* as readable and writable, after having been
/// protected using *mprotect_readonly()* or *mprotect_noaccess()*.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::init::init;
/// use sodium_sys::crypto::utils::secmem::{
/// free,
/// malloc,
/// mprotect_noaccess,
/// mprotect_readwrite
/// };
///
/// let _ = init();
/// let mut v = malloc(64);
/// v[0] = 1;
/// assert!(v.len() == 64);
/// assert!(v[0] == 1);
/// mprotect_noaccess(&mut v);
/// // If you uncomment the following line the program will fail (no read).
/// // assert!(v[0] == 1);
/// // If you uncomment the following line the program will fail (no write).
/// // v[1] = 1;
/// mprotect_readwrite(&mut v);
/// assert!(v[0] == 1);
/// v[1] = 1;
/// assert!(v[1] == 1);
/// free(&mut v);
/// ```
/// The *increment()* function takes a pointer to an arbitrary length unsigned
/// number, and increments it.
///
/// It runs in constant-time for a given length, and considers the number to be
/// encoded in little-endian format.
///
/// *increment()* can be used to increment nonces.
///
/// # Examples
///
/// ```
/// use sodium_sys::crypto::utils::secmem;
///
/// let mut nonce = [0];
/// secmem::increment(&mut nonce);
/// assert!(nonce == [1]);
/// secmem::increment(&mut nonce);
/// assert!(nonce == [2]);
/// ```