Skip to content

Commit

Permalink
proc derive macro for ConstantTimeEq
Browse files Browse the repository at this point in the history
  • Loading branch information
varsha888 committed May 3, 2023
1 parent 6b6a81a commit 1baa58e
Show file tree
Hide file tree
Showing 8 changed files with 669 additions and 2 deletions.
9 changes: 9 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
[workspace]
members = [
"subtle-derive"
]

[package]
name = "subtle"
# Before incrementing:
Expand Down Expand Up @@ -25,13 +30,17 @@ exclude = [
[badges]
travis-ci = { repository = "dalek-cryptography/subtle", branch = "master"}

[dependencies]
subtle-derive = { version = "0.1.0", optional = true, path = "subtle-derive" }

[dev-dependencies]
rand = { version = "0.8" }

[features]
const-generics = []
core_hint_black_box = []
default = ["std", "i128"]
derive = ["subtle-derive"]
std = []
i128 = []
# DEPRECATED: As of 2.4.1, this feature does nothing.
Expand Down
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,38 @@ barrier ([`core::hint::black_box`]). To use the new optimization barrier,
enable the `core_hint_black_box` feature.

Rust versions from 1.51 or higher have const generics support. You may enable
`const-generics` feautre to have `subtle` traits implemented for arrays `[T; N]`.
`const-generics` feature to have `subtle` traits implemented for arrays `[T; N]`.

Versions prior to `2.2` recommended use of the `nightly` feature to enable an
optimization barrier; this is not required in versions `2.2` and above.

Enable `derive` feature to generate implementations for traits using procedural
macros in [`subtle-derive`].

```toml
subtle = { version = "2.6", features = ["derive"] }
```

## Example

```ignore
use subtle::ConstantTimeEq;
#[derive(ConstantTimeEq)]
struct MyStruct {
data: [u8; 16]
}
fn main() {
let first = MyStruct { data: [1u8;16]};
let second = MyStruct { data: [1u8;16]};
assert!(bool::from(first.ct_eq(&second)));
}
```


Note: the `subtle` crate contains `debug_assert`s to check invariants during
debug builds. These invariant checks involve secret-dependent branches, and
are not present when compiled in release mode. This crate is intended to be
Expand Down Expand Up @@ -80,3 +107,4 @@ effort is fundamentally limited.
[docs]: https://docs.rs/subtle
[`core::hint::black_box`]: https://doc.rust-lang.org/core/hint/fn.black_box.html
[rust-timing-shield]: https://www.chosenplaintext.ca/open-source/rust-timing-shield/security
[`subtle-derive`]: https://crates.io/crates/subtle-derive
36 changes: 35 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,37 @@
//! enable the `core_hint_black_box` feature.
//!
//! Rust versions from 1.51 or higher have const generics support. You may enable
//! `const-generics` feautre to have `subtle` traits implemented for arrays `[T; N]`.
//! `const-generics` feature to have `subtle` traits implemented for arrays `[T; N]`.
//!
//! Versions prior to `2.2` recommended use of the `nightly` feature to enable an
//! optimization barrier; this is not required in versions `2.2` and above.
//!
//! Enable `derive` feature to generate implementations for traits using procedural macros
//! in [`subtle-derive`].
//!
//! ```toml
//! subtle = { version = "2.6", features = ["derive"] }
//! ```
//!
//! ## Example
//!
//! ```ignore
//! use subtle::ConstantTimeEq;
//!
//! #[derive(ConstantTimeEq)]
//! struct MyStruct {
//! data: [u8; 16]
//! }
//!
//! fn main() {
//! use subtle::ConstantTimeEq;
//! let first = MyStruct { data: [1u8;16]};
//! let second = MyStruct { data: [1u8;16]};
//!
//! assert!(bool::from(first.ct_eq(&second)));
//! }
//! ```
//!
//! Note: the `subtle` crate contains `debug_assert`s to check invariants during
//! debug builds. These invariant checks involve secret-dependent branches, and
//! are not present when compiled in release mode. This crate is intended to be
Expand Down Expand Up @@ -95,15 +121,23 @@
//! [docs]: https://docs.rs/subtle
//! [`core::hint::black_box`]: https://doc.rust-lang.org/core/hint/fn.black_box.html
//! [rust-timing-shield]: https://www.chosenplaintext.ca/open-source/rust-timing-shield/security
//! [`subtle-derive`]: https://crates.io/crates/subtle-derive

#[cfg(feature = "std")]
#[macro_use]
extern crate std;

#[cfg(feature = "subtle-derive")]
#[macro_use]
extern crate subtle_derive;

use core::cmp;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Neg, Not};
use core::option::Option;

#[cfg(feature = "subtle-derive")]
pub use subtle_derive::ConstantTimeEq;

/// The `Choice` struct represents a choice for use in conditional assignment.
///
/// It is a wrapper around a `u8`, which should have the value either `1` (true)
Expand Down
24 changes: 24 additions & 0 deletions subtle-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "subtle-derive"
version = "0.1.0"
edition = "2021"
authors = ["Varsha Jayadev <varsha@mobilecoin.com>"]
readme = "README.md"
license = "BSD-3-Clause"
repository = "https://github.com/dalek-cryptography/subtle"
homepage = "https://dalek.rs/"
documentation = "https://docs.rs/crate/subtle-derive"
categories = ["cryptography", "no-std"]
keywords = ["cryptography", "crypto", "constant-time", "utilities"]
description = "Macros implementation of #[derive(ConstantTimeEq)]"

[features]
default = []

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1.0.8"
quote = "1.0"
syn = "2.0.15"
28 changes: 28 additions & 0 deletions subtle-derive/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Copyright (c) 2016-2017 Isis Agora Lovecruft, Henry de Valence. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 changes: 29 additions & 0 deletions subtle-derive/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# subtle

[![Crates.io][crate-image]][crate-link]<!--
-->[![Docs Status][docs-image]][docs-link]

**Procedural macros for deriving [subtle] trait implementations.**

Derive macro implemented for traits:
- [x] ConstantTimeEq
- [ ] ConstantTimeGreater
- [ ] ConstantTimeLesser

## Documentation

Documentation is available [here][subtle-docs].

# Installation
To install, add the following to the dependencies section of your project's `Cargo.toml`:

```toml
subtle = { version = "2.6", features = ["derive"] }
```

[crate-image]: https://img.shields.io/crates/v/subtle-derive?style=flat-square
[crate-link]: https://crates.io/crates/subtle-derive
[docs-image]: https://img.shields.io/docsrs/subtle-derive?style=flat-square
[docs-link]: https://docs.rs/crate/subtle-derive
[subtle]: https://crates.io/crates/subtle
[subtle-docs]: https://docs.rs/subtle
145 changes: 145 additions & 0 deletions subtle-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// Copyright (c) 2023 The MobileCoin Foundation

//! # subtle
//!
//! [![Crates.io][crate-image]][crate-link]<!--
//! -->[![Docs Status][docs-image]][docs-link]
//!
//! **Procedural macros for deriving [subtle] trait implementations.**
//!
//! Derive macro implemented for traits:
//! - [x] ConstantTimeEq
//! - [ ] ConstantTimeGreater
//! - [ ] ConstantTimeLesser
//!
//! ## Documentation
//!
//! Documentation is available [here][subtle-docs].
//!
//! # Installation
//! To install, add the following to the dependencies section of your project's `Cargo.toml`:
//!
//! ```toml
//! subtle = { version = "2.6", features = ["derive"] }
//! ```
//!
//! [crate-image]: https://img.shields.io/crates/v/subtle-derive?style=flat-square
//! [crate-link]: https://crates.io/crates/subtle-derive
//! [docs-image]: https://img.shields.io/docsrs/subtle-derive?style=flat-square
//! [docs-link]: https://docs.rs/crate/subtle-derive
//! [subtle]: https://crates.io/crates/subtle
//! [subtle-docs]: https://docs.rs/subtle

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DataEnum, DeriveInput, Fields, GenericParam, Generics};

#[proc_macro_derive(ConstantTimeEq)]
pub fn constant_time_eq(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
derive_ct_eq(&input)
}


fn parse_fields(fields: &Fields) -> Result<proc_macro2::TokenStream, &'static str> {
match &fields {
Fields::Named(fields_named) => {
let mut token_stream = quote!();
let mut iter = fields_named.named.iter().peekable();

while let Some(field) = iter.next() {
let ident = &field.ident;
match iter.peek() {
None => token_stream.extend(quote! { {self.#ident}.ct_eq(&{other.#ident}) }),
Some(_) => {
token_stream.extend(quote! { {self.#ident}.ct_eq(&{other.#ident}) & })
}
}
}
Ok(token_stream)
}
Fields::Unnamed(unnamed_fields) => {
let mut token_stream = quote!();
let mut iter = unnamed_fields.unnamed.iter().peekable();
let mut idx = 0;
while let Some(_) = iter.next() {
let i = syn::Index::from(idx);
match iter.peek() {
None => token_stream.extend(quote! { {self.#i}.ct_eq(&{other.#i}) }),
Some(_) => {
token_stream.extend(quote! { {self.#i}.ct_eq(&{other.#i}) & });
idx += 1;
}
}
}

Ok(token_stream)
}
Fields::Unit => Err("Constant time cannot be derived for unit fields"),
}
}

fn parse_enum(data_enum: &DataEnum) -> Result<proc_macro2::TokenStream, &'static str> {
for variant in data_enum.variants.iter() {
if let Fields::Unnamed(_) = variant.fields {
panic!("Cannot derive ct_eq for fields in enums")
}
}
let token_stream = quote! {
::subtle::Choice::from((self == other) as u8)
};

Ok(token_stream)
}

fn parse_data(data: &Data) -> Result<proc_macro2::TokenStream, &'static str> {
match data {
Data::Struct(variant_data) => parse_fields(&variant_data.fields),
Data::Enum(data_enum) => parse_enum(data_enum),
Data::Union(..) => Err("Constant time cannot be derived for a union"),
}
}

fn parse_lifetime(generics: &Generics) -> u32 {
let mut count = 0;
for i in generics.params.iter() {
if let GenericParam::Lifetime(_) = i {
count += 1;
}
}
count
}

fn derive_ct_eq(input: &DeriveInput) -> TokenStream {
let ident = &input.ident;
let data = &input.data;
let generics = &input.generics;
let is_lifetime = parse_lifetime(generics);
let ct_eq_stream: proc_macro2::TokenStream =
parse_data(data).expect("Failed to parse DeriveInput data");
let data_ident = if is_lifetime != 0 {
let mut s = format!("{}<'_", ident);

for _ in 1..is_lifetime {
s.push_str(", '_");
}
s.push('>');

s
} else {
ident.to_string()
};
let ident_stream: proc_macro2::TokenStream =
data_ident.parse().expect("Should be valid lifetime tokens");

let expanded: proc_macro2::TokenStream = quote! {
impl ::subtle::ConstantTimeEq for #ident_stream {
fn ct_eq(&self, other: &Self) -> ::subtle::Choice {
use ::subtle::ConstantTimeEq;
return #ct_eq_stream
}
}
};

expanded.into()
}

0 comments on commit 1baa58e

Please sign in to comment.