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
//! This crate defines simple wrappers around Rust's integer type to guarantee they are used in
//! a constant-time fashion. Hence, division and direct comparison of these "secret" integers is
//! disallowed.
//!
//! These integers are intended to be the go-to type to use when implementing cryptographic
//! software, as they provide an extra automated check against use of variable-time operations.
//!
//! To use the crate, just import everything (`use secret_integers::*;`) and replace your integer
//! types with uppercase versions of their names (e.g. `u8` -> `U8`).
//!
//! # Examples
//!
//! In order to print information or test code involving your secret integers, you need first to
//! declassify them. Your crypto code should not contain any `declassify` occurence though to
//! guarantee constant-timedness. Make sure to specify the type of your literals when classifying
//! (e.g. `0x36u16`) or else you'll get a casting error.
//!
//! ```
//! # use secret_integers::*;
//! let x = U32::classify(1u32);
//! let y : U32 = 2u32.into();
//! assert_eq!((x + y).declassify(), 3);
//! ```
//!
//! Using an illegal operation will get you a compile-time error:
//!
//! ```compile_fail
//! # use secret_integers::*;
//! let x = U32::classify(4u32);
//! let y : U32 = 2u32.into();
//! assert_eq!((x / y).declassify(), 2);
//! ```
//!
//! Since indexing arrays and vectors is only possible with `usize`, these secret integers also
//! prevent you from using secret values to index memory (which is a breach to constant-timedness
//! due to cache behaviour).
//!
//! ```
//! # use secret_integers::*;
//! fn xor_block(block1: &mut [U64;16], block2: &[U64;16]) {
//!    for i in 0..16 {
//!      block1[i] ^= block2[i]
//!    }
//! }
//! ```
//! See the [Dalek](https://github.com/denismerigoux/rust-secret-integers/tree/master/examples/dalek.rs)
//! and [Chacha20](https://github.com/denismerigoux/rust-secret-integers/tree/master/examples/chacha20.rs)
//! examples for more details on how to use this crate.
//!
//!
//! # Const-compatibility
//!
//! Because stable Rust does not allow constant functions for now, it is impossible to use those
//! wrappers in const declarations. Even classifying directly inside the declaration does not work:
//!
//! ```compile_fail
//! const IV : [U32;2] = [U32::classify(0xbe6548u32),U32::classify(0xaec6d48u32)]
//! ```
//!
//! For now, the solution is to map your const items with `classify` once you're inside a function,
//! or call `into`.
//!
//! ```
//! # use secret_integers::*;
//! const IV : [u32;2] = [0xbe6548, 0xaec6d48];
//!
//! fn start_cipher(plain: &mut Vec<U32>) {
//!    for i in 0..plain.len() {
//!      plain[i] |= plain[i] ^ IV[i].into();
//!    }
//! }
//! ```
//!



use std::num::Wrapping;
use std::ops::*;

macro_rules! define_wrapping_op {
    ($name:ident, $op:tt, $op_name:ident, $func_op:ident, $assign_name:ident, $assign_func:ident, $checked_func_op:ident) => {

        /// **Warning:** has wrapping semantics.
        impl $op_name for $name {
            type Output = Self;
            #[inline]
            fn $func_op(self, rhs: Self) -> Self {
                let $name(i1) = self;
                let $name(i2) = rhs;
                $name((Wrapping(i1) $op Wrapping(i2)).0)
            }
        }

        impl $name {
            /// **Warning:** panics when overflow.
            pub fn $checked_func_op(self, rhs: Self) -> Self {
                let $name(i1) = self;
                let $name(i2) = rhs;
                match i1.$checked_func_op(i2) {
                    None => panic!("Secret integer {} overflow!", stringify!($func_op)),
                    Some(r) => $name(r)
                }
            }
        }

        /// **Warning:** has wrapping semantics.
        impl $assign_name for $name {
            #[inline]
            fn $assign_func(&mut self, rhs: Self) {
                *self = *self $op rhs
            }
        }
    }
}

macro_rules! define_bitwise_op {
    ($name:ident, $op:tt, $op_name:ident, $func_op:ident, $assign_name:ident, $assign_func:ident) => {
        impl $op_name for $name {
            type Output = Self;
            #[inline]
            fn $func_op(self, rhs: Self) -> Self {
                let $name(i1) = self;
                let $name(i2) = rhs;
                $name(i1 $op i2)
            }
        }

        impl $assign_name for $name {
            #[inline]
            fn $assign_func(&mut self, rhs: Self) {
                *self = *self $op rhs
            }
        }
    }
}

macro_rules! define_unary_op {
    ($name:ident, $op:tt, $op_name:ident, $func_op:ident) => {
        impl $op_name for $name {
            type Output = Self;
            #[inline]
            fn $func_op(self) -> Self {
                let $name(i1) = self;
                $name($op i1)
            }
        }
    }
}

macro_rules! define_shift {
    ($name:ident, $op:tt, $op_name:ident, $func_op:ident, $assign_name:ident, $assign_func:ident) => {
        impl $op_name<u32> for $name {
            type Output = Self;
            #[inline]
            fn $func_op(self, rhs: u32) -> Self {
                let $name(i1) = self;
                $name(i1 $op rhs)
            }
        }

        impl $assign_name<u32> for $name {
            #[inline]
            fn $assign_func(&mut self, rhs: u32) {
                *self = *self $op rhs
            }
        }
    }
}

macro_rules! define_secret_integer {
    ($name:ident, $repr:ty, $bits:tt) => {
        #[derive(Clone, Copy, Default)]
        pub struct $name(pub(crate) $repr);

        impl $name {
            pub fn classify<T : Into<$repr>>(x: T) -> Self {
                $name(x.into())
            }


            /// **Warning:** use with caution, breaks the constant-time guarantee.
            pub fn declassify(self) -> $repr {
                self.0
            }


            pub fn zero() -> Self {
                $name(0)
            }

            pub fn one() -> Self {
                $name(1)
            }

            pub fn ones() -> Self {
                !Self::zero()
            }
        }

        impl From<$repr> for $name {
            fn from(x:$repr) -> Self {
                Self::classify(x)
            }
        }

        define_wrapping_op!($name, +, Add, add, AddAssign, add_assign, checked_add);
        define_wrapping_op!($name, -, Sub, sub, SubAssign, sub_assign, checked_sub);
        define_wrapping_op!($name, *, Mul, mul, MulAssign, mul_assign, checked_mul);

        define_shift!($name, <<, Shl, shl, ShlAssign, shl_assign);
        define_shift!($name, >>, Shr, shr, ShrAssign, shr_assign);

        impl $name {
            pub fn rotate_left(self, rotval:u32) -> Self {
                let $name(i) = self;
                $name(i.rotate_left(rotval))
            }

            pub fn rotate_right(self, rotval:u32) -> Self {
                let $name(i) = self;
                $name(i.rotate_right(rotval))
            }
        }

        define_bitwise_op!($name, &, BitAnd, bitand, BitAndAssign, bitand_assign);
        define_bitwise_op!($name, |, BitOr, bitor, BitOrAssign, bitor_assign);
        define_bitwise_op!($name, ^, BitXor, bitxor, BitXorAssign, bitxor_assign);

        /// `Not` has bitwise semantics for integers
        define_unary_op!($name, !, Not, not);
    }
}

macro_rules! define_secret_unsigned_integer {
    ($name:ident, $repr:ty, $bits:tt) => {
        /// Secret unsigned integer.
        define_secret_integer!($name, $repr, $bits);
        impl Neg for $name {
            type Output = Self;
            #[inline]
            fn neg(self) -> Self {
                let $name(i1) = self;
                $name((Wrapping(!i1) + Wrapping(1)).0)
            }
        }

        /// # Constant-time comparison operators
        impl $name {
            /// Produces a new integer which is all ones if the two arguments are equal and
            /// all zeroes otherwise. With inspiration from
            /// [Wireguard](https://git.zx2c4.com/WireGuard/commit/src/crypto/curve25519-hacl64.h?id=2e60bb395c1f589a398ec606d611132ef9ef764b).
            pub fn comp_eq(self, rhs: Self) -> Self {
                let a = self; let b = rhs;
                let x = a | b;
                let minus_x = - x;
                let x_or_minus_x = x | minus_x;
                let xnx = x_or_minus_x >> ($bits - 1);
                let c = xnx - Self::one();
                c
            }

            /// Produces a new integer which is all ones if the first argument is different from
            /// the second argument, and all zeroes otherwise.
            pub fn comp_ne(self, rhs:Self) -> Self {
                !self.comp_eq(rhs) ^ Self::ones()
            }

            /// Produces a new integer which is all ones if the first argument is greater than or
            /// equal to the second argument, and all zeroes otherwise. With inspiration from
            /// [WireGuard](https://git.zx2c4.com/WireGuard/commit/src/crypto/curve25519-hacl64.h?id=0a483a9b431d87eca1b275463c632f8d5551978a).
            pub fn comp_gte(self, rhs: Self) -> Self {
                let x = self; let y = rhs;
                let x_xor_y = x | y;
                let x_sub_y = x - y;
                let x_sub_y_xor_y = x_sub_y ^ y;
                let q = x_xor_y ^ x_sub_y_xor_y;
                let x_xor_q = x ^ q;
                let x_xor_q_ = x_xor_q >> ($bits - 1 );
                let c = x_xor_q_ - Self::one();
                c
            }

            /// Produces a new integer which is all ones if the first argumentis strictly greater
            /// than the second argument, and all zeroes otherwise.
            pub fn comp_gt(self, rhs:Self) -> Self {
                self.comp_gte(rhs) ^ self.comp_eq(rhs)
            }

            /// Produces a new integer which is all ones if the first argumentis less than or
            /// equal to the second argument, and all zeroes otherwise.
            pub fn comp_lte(self, rhs:Self) -> Self {
                !self.comp_gt(rhs)
            }

            /// Produces a new integer which is all ones if the first argumentis strictly less than
            /// the second argument, and all zeroes otherwise.
            pub fn comp_lt(self, rhs:Self) -> Self {
                !self.comp_gte(rhs)
            }

        }
    };
}

macro_rules! define_secret_signed_integer {
    ($name:ident, $repr:ty, $bits:tt) => {
        /// Secret signed integer.
        define_secret_integer!($name, $repr, $bits);
        define_unary_op!($name, -, Neg, neg);
    }
}

define_secret_unsigned_integer!(U8, u8, 8);
define_secret_unsigned_integer!(U16, u16, 16);
define_secret_unsigned_integer!(U32, u32, 32);
define_secret_unsigned_integer!(U64, u64, 64);
define_secret_unsigned_integer!(U128, u128, 128);
define_secret_signed_integer!(I8, i8, 8);
define_secret_signed_integer!(I16, i16, 16);
define_secret_signed_integer!(I32, i32, 32);
define_secret_signed_integer!(I64, i64, 64);
define_secret_signed_integer!(I128, i128, 128);

macro_rules! define_safe_casting {
    ($from:ident, $to:ident, $to_repr:ident) => {
        impl From<$from> for $to {
            fn from(x:$from) -> $to {
                $to(x.0 as $to_repr)
            }
        }
    }
}

macro_rules! define_unsafe_casting {
    ($from:ident, $to:ident, $to_repr:ident) => {
        /// **Warning:** wrapping semantics.
        impl From<$from> for $to {
            fn from(x:$from) -> $to {
                $to(x.0 as $to_repr)
            }
        }
    }
}

macro_rules! define_signed_unsigned_casting {
    ($unsigned:ident, $unsiged_repr:ident, $signed:ident, $signed_repr:ident) => {
        /// **Warning:** wrapping semantics.
        impl From<$unsigned> for $signed {
            fn from(x:$unsigned) -> $signed {
                $signed(x.0 as $signed_repr)
            }
        }
    }
}

// Casting

// U128 <-> Un{n < 128}
define_safe_casting!(U8, U128, u128);
define_unsafe_casting!(U128, U8, u8);
define_safe_casting!(U16, U128, u128);
define_unsafe_casting!(U128, U16, u16);
define_safe_casting!(U32, U128, u128);
define_unsafe_casting!(U128, U32, u32);
define_safe_casting!(U64, U128, u128);
define_unsafe_casting!(U128, U64, u64);

// U64 <-> Un{n < 64}
define_safe_casting!(U8, U64, u64);
define_unsafe_casting!(U64, U8, u8);
define_safe_casting!(U16, U64, u64);
define_unsafe_casting!(U64, U16, u16);
define_safe_casting!(U32, U64, u64);
define_unsafe_casting!(U64, U32, u32);

// U32 <-> Un{n < 32}
define_safe_casting!(U8, U32, u32);
define_unsafe_casting!(U32, U8, u8);
define_safe_casting!(U16, U32, u32);
define_unsafe_casting!(U32, U16, u16);

// U16 <-> Un{n < 16}
define_safe_casting!(U8, U16, u16);
define_unsafe_casting!(U16, U8, u8);

// I128 <-> In{n < 128}
define_safe_casting!(I8, I128, i128);
define_unsafe_casting!(I128, I8, i8);
define_safe_casting!(I16, I128, i128);
define_unsafe_casting!(I128, I16, i16);
define_safe_casting!(I32, I128, i128);
define_unsafe_casting!(I128, I32, i32);
define_safe_casting!(I64, I128, i128);
define_unsafe_casting!(I128, I64, i64);

// I64 <-> In{n < 64}
define_safe_casting!(I8, I64, i64);
define_unsafe_casting!(I64, I8, i8);
define_safe_casting!(I16, I64, i64);
define_unsafe_casting!(I64, I16, i16);
define_safe_casting!(I32, I64, i64);
define_unsafe_casting!(I64, I32, i32);

// I32 <-> In{n < 32}
define_safe_casting!(I8, I32, i32);
define_unsafe_casting!(I32, I8, i8);
define_safe_casting!(I16, I32, i32);
define_unsafe_casting!(I32, I16, i16);

// I16 <-> In{n < 16}
define_safe_casting!(I8, I16, i16);
define_unsafe_casting!(I16, I8, i8);

// Unsigned <-> signed
define_signed_unsigned_casting!(U128, u128, I128, i128);
define_signed_unsigned_casting!(U64, u64, I64, i64);
define_signed_unsigned_casting!(U32, u32, I32, i32);
define_signed_unsigned_casting!(U16, u16, I16, i16);
define_signed_unsigned_casting!(U8, u8, I8, i8);