lib.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*! Implementation of a new style of bridge authority for Tor that
  2. allows users to invite other users, while protecting the social graph
  3. from the bridge authority itself.
  4. We use CMZ14 credentials (GGM version, which is more efficient, but
  5. makes a stronger security assumption): "Algebraic MACs and
  6. Keyed-Verification Anonymous Credentials" (Chase, Meiklejohn, and
  7. Zaverucha, CCS 2014)
  8. The notation follows that of the paper "Hyphae: Social Secret Sharing"
  9. (Lovecruft and de Valence, 2017), Section 4. */
  10. // We really want points to be capital letters and scalars to be
  11. // lowercase letters
  12. #![allow(non_snake_case)]
  13. #[macro_use]
  14. extern crate zkp;
  15. pub mod bridge_table;
  16. pub mod cred;
  17. pub mod dup_filter;
  18. pub mod migration_table;
  19. use sha2::Sha512;
  20. use rand::rngs::OsRng;
  21. use rand::RngCore;
  22. use std::convert::{TryFrom, TryInto};
  23. use curve25519_dalek::constants as dalek_constants;
  24. use curve25519_dalek::ristretto::RistrettoBasepointTable;
  25. use curve25519_dalek::ristretto::RistrettoPoint;
  26. use curve25519_dalek::scalar::Scalar;
  27. #[cfg(test)]
  28. use curve25519_dalek::traits::IsIdentity;
  29. use ed25519_dalek::{Keypair, PublicKey, Signature, SignatureError, Signer, Verifier};
  30. use subtle::ConstantTimeEq;
  31. use lazy_static::lazy_static;
  32. lazy_static! {
  33. pub static ref CMZ_A: RistrettoPoint =
  34. RistrettoPoint::hash_from_bytes::<Sha512>(b"CMZ Generator A");
  35. pub static ref CMZ_B: RistrettoPoint = dalek_constants::RISTRETTO_BASEPOINT_POINT;
  36. pub static ref CMZ_A_TABLE: RistrettoBasepointTable = RistrettoBasepointTable::create(&CMZ_A);
  37. pub static ref CMZ_B_TABLE: RistrettoBasepointTable =
  38. dalek_constants::RISTRETTO_BASEPOINT_TABLE;
  39. }
  40. #[derive(Clone, Debug)]
  41. pub struct IssuerPrivKey {
  42. x0tilde: Scalar,
  43. x: Vec<Scalar>,
  44. }
  45. impl IssuerPrivKey {
  46. /// Create an IssuerPrivKey for credentials with the given number of
  47. /// attributes.
  48. pub fn new(n: u16) -> IssuerPrivKey {
  49. let mut rng = rand::thread_rng();
  50. let x0tilde = Scalar::random(&mut rng);
  51. let mut x: Vec<Scalar> = Vec::with_capacity((n + 1) as usize);
  52. // Set x to a vector of n+1 random Scalars
  53. x.resize_with((n + 1) as usize, || Scalar::random(&mut rng));
  54. IssuerPrivKey { x0tilde, x }
  55. }
  56. }
  57. #[derive(Clone, Debug)]
  58. pub struct IssuerPubKey {
  59. X: Vec<RistrettoPoint>,
  60. }
  61. impl IssuerPubKey {
  62. /// Create an IssuerPubKey from the corresponding IssuerPrivKey
  63. pub fn new(privkey: &IssuerPrivKey) -> IssuerPubKey {
  64. let Atable: &RistrettoBasepointTable = &CMZ_A_TABLE;
  65. let Btable: &RistrettoBasepointTable = &CMZ_B_TABLE;
  66. let n_plus_one = privkey.x.len();
  67. let mut X: Vec<RistrettoPoint> = Vec::with_capacity(n_plus_one);
  68. // The first element is a special case; it is
  69. // X[0] = x0tilde*A + x[0]*B
  70. X.push(&privkey.x0tilde * Atable + &privkey.x[0] * Btable);
  71. // The other elements (1 through n) are X[i] = x[i]*A
  72. for i in 1..n_plus_one {
  73. X.push(&privkey.x[i] * Atable);
  74. }
  75. IssuerPubKey { X }
  76. }
  77. }
  78. /// The BridgeDb. This will typically be a singleton object. The
  79. /// BridgeDb's role is simply to issue signed "open invitations" to
  80. /// people who are not yet part of the system.
  81. #[derive(Debug)]
  82. pub struct BridgeDb {
  83. /// The keypair for signing open invitations
  84. keypair: Keypair,
  85. /// The public key for verifying open invitations
  86. pub pubkey: PublicKey,
  87. /// The number of open-invitation buckets
  88. num_openinv_buckets: u32,
  89. }
  90. /// An open invitation is a [u8; OPENINV_LENGTH] where the first 32
  91. /// bytes are the serialization of a random Scalar (the invitation id),
  92. /// the next 4 bytes are a little-endian bucket number, and the last
  93. /// SIGNATURE_LENGTH bytes are the signature on the first 36 bytes.
  94. pub const OPENINV_LENGTH: usize = 32 // the length of the random
  95. // invitation id (a Scalar)
  96. + 4 // the length of the u32 for the bucket number
  97. + ed25519_dalek::SIGNATURE_LENGTH; // the length of the signature
  98. impl BridgeDb {
  99. /// Create the BridgeDb.
  100. pub fn new(num_openinv_buckets: u32) -> Self {
  101. let mut csprng = OsRng {};
  102. let keypair = Keypair::generate(&mut csprng);
  103. let pubkey = keypair.public;
  104. Self {
  105. keypair,
  106. pubkey,
  107. num_openinv_buckets,
  108. }
  109. }
  110. /// Produce an open invitation. In this example code, we just
  111. /// choose a random open-invitation bucket.
  112. pub fn invite(&self) -> [u8; OPENINV_LENGTH] {
  113. let mut res: [u8; OPENINV_LENGTH] = [0; OPENINV_LENGTH];
  114. let mut rng = rand::thread_rng();
  115. // Choose a random invitation id (a Scalar) and serialize it
  116. let id = Scalar::random(&mut rng);
  117. res[0..32].copy_from_slice(&id.to_bytes());
  118. // Choose a random bucket number (mod num_openinv_buckets) and
  119. // serialize it
  120. let bucket_num = rng.next_u32() % self.num_openinv_buckets;
  121. res[32..(32 + 4)].copy_from_slice(&bucket_num.to_le_bytes());
  122. // Sign the first 36 bytes and serialize it
  123. let sig = self.keypair.sign(&res[0..(32 + 4)]);
  124. res[(32 + 4)..].copy_from_slice(&sig.to_bytes());
  125. res
  126. }
  127. /// Verify an open invitation. Returns the invitation id and the
  128. /// bucket number if the signature checked out. It is up to the
  129. /// caller to then check that the invitation id has not been used
  130. /// before.
  131. pub fn verify(
  132. invitation: [u8; OPENINV_LENGTH],
  133. pubkey: PublicKey,
  134. ) -> Result<(Scalar, u32), SignatureError> {
  135. // Pull out the signature and verify it
  136. let sig = Signature::try_from(&invitation[(32 + 4)..])?;
  137. pubkey.verify(&invitation[0..(32 + 4)], &sig)?;
  138. // The signature passed. Pull out the bucket number and then
  139. // the invitation id
  140. let bucket = u32::from_le_bytes(invitation[32..(32 + 4)].try_into().unwrap());
  141. match Scalar::from_canonical_bytes(invitation[0..32].try_into().unwrap()) {
  142. // It should never happen that there's a valid signature on
  143. // an invalid serialization of a Scalar, but check anyway.
  144. None => Err(SignatureError::new()),
  145. Some(s) => Ok((s, bucket)),
  146. }
  147. }
  148. }
  149. /// The bridge authority. This will typically be a singleton object.
  150. #[derive(Debug)]
  151. pub struct BridgeAuth {
  152. /// The private key for the main Lox credential
  153. lox_priv: IssuerPrivKey,
  154. /// The public key for the main Lox credential
  155. pub lox_pub: IssuerPubKey,
  156. /// The private key for migration credentials
  157. migration_priv: IssuerPrivKey,
  158. /// The public key for migration credentials
  159. pub migration_pub: IssuerPubKey,
  160. /// The private key for migration key credentials
  161. migrationkey_priv: IssuerPrivKey,
  162. /// The public key for migration key credentials
  163. pub migrationkey_pub: IssuerPubKey,
  164. /// The public key of the BridgeDb issuing open invitations
  165. pub bridgedb_pub: PublicKey,
  166. /// The bridge table
  167. bridge_table: bridge_table::BridgeTable,
  168. /// The migration table
  169. migration_table: migration_table::MigrationTable,
  170. /// Duplicate filter for open invitations
  171. openinv_filter: dup_filter::DupFilter<Scalar>,
  172. /// Duplicate filter for credential ids
  173. id_filter: dup_filter::DupFilter<Scalar>,
  174. /// Duplicate filter for trust promotions (from untrusted level 0 to
  175. /// trusted level 1)
  176. trust_promotion_filter: dup_filter::DupFilter<Scalar>,
  177. /// For testing only: offset of the true time to the simulated time
  178. time_offset: time::Duration,
  179. }
  180. impl BridgeAuth {
  181. pub fn new(bridgedb_pub: PublicKey) -> Self {
  182. // Create the private and public keys for each of the types of
  183. // credential, each with the appropriate number of attributes
  184. let lox_priv = IssuerPrivKey::new(6);
  185. let lox_pub = IssuerPubKey::new(&lox_priv);
  186. let migration_priv = IssuerPrivKey::new(3);
  187. let migration_pub = IssuerPubKey::new(&migration_priv);
  188. let migrationkey_priv = IssuerPrivKey::new(2);
  189. let migrationkey_pub = IssuerPubKey::new(&migrationkey_priv);
  190. Self {
  191. lox_priv,
  192. lox_pub,
  193. migration_priv,
  194. migration_pub,
  195. migrationkey_priv,
  196. migrationkey_pub,
  197. bridgedb_pub,
  198. bridge_table: Default::default(),
  199. migration_table: Default::default(),
  200. openinv_filter: Default::default(),
  201. id_filter: Default::default(),
  202. trust_promotion_filter: Default::default(),
  203. time_offset: time::Duration::zero(),
  204. }
  205. }
  206. #[cfg(test)]
  207. /// For testing only: manually advance the day by 1 day
  208. pub fn advance_day(&mut self) {
  209. self.time_offset += time::Duration::days(1);
  210. }
  211. #[cfg(test)]
  212. /// For testing only: manually advance the day by the given number
  213. /// of days
  214. pub fn advance_days(&mut self, days: u16) {
  215. self.time_offset += time::Duration::days(days.into());
  216. }
  217. /// Get today's (real or simulated) date
  218. fn today(&self) -> u64 {
  219. // We will not encounter negative Julian dates (~6700 years ago)
  220. (time::OffsetDateTime::now_utc().date() + self.time_offset)
  221. .julian_day()
  222. .try_into()
  223. .unwrap()
  224. }
  225. #[cfg(test)]
  226. /// Verify the two MACs on a Lox credential
  227. pub fn verify_lox(&self, cred: &cred::Lox) -> bool {
  228. if cred.P.is_identity() || cred.P_noopmigration.is_identity() {
  229. return false;
  230. }
  231. let Q = (self.lox_priv.x[0]
  232. + cred.id * self.lox_priv.x[1]
  233. + cred.bucket * self.lox_priv.x[2]
  234. + cred.trust_level * self.lox_priv.x[3]
  235. + cred.level_since * self.lox_priv.x[4]
  236. + cred.invites_remaining * self.lox_priv.x[5]
  237. + cred.invites_issued * self.lox_priv.x[6])
  238. * cred.P;
  239. let Q_noopmigration = (self.migration_priv.x[0]
  240. + cred.id * self.migration_priv.x[1]
  241. + cred.bucket * self.migration_priv.x[2]
  242. + cred.bucket * self.migration_priv.x[3])
  243. * cred.P_noopmigration;
  244. return Q == cred.Q && Q_noopmigration == cred.Q_noopmigration;
  245. }
  246. #[cfg(test)]
  247. /// Verify the MAC on a Migration credential
  248. pub fn verify_migration(&self, cred: &cred::Migration) -> bool {
  249. if cred.P.is_identity() {
  250. return false;
  251. }
  252. let Q = (self.migration_priv.x[0]
  253. + cred.lox_id * self.migration_priv.x[1]
  254. + cred.from_bucket * self.migration_priv.x[2]
  255. + cred.to_bucket * self.migration_priv.x[3])
  256. * cred.P;
  257. return Q == cred.Q;
  258. }
  259. }
  260. /// Try to extract a u64 from a Scalar
  261. pub fn scalar_u64(s: &Scalar) -> Option<u64> {
  262. // Check that the top 24 bytes of the Scalar are 0
  263. let sbytes = s.as_bytes();
  264. if sbytes[8..].ct_eq(&[0u8; 24]).unwrap_u8() == 0 {
  265. return None;
  266. }
  267. Some(u64::from_le_bytes(sbytes[..8].try_into().unwrap()))
  268. }
  269. /// Double a Scalar
  270. pub fn scalar_dbl(s: &Scalar) -> Scalar {
  271. s + s
  272. }
  273. /// Double a RistrettoPoint
  274. pub fn pt_dbl(P: &RistrettoPoint) -> RistrettoPoint {
  275. P + P
  276. }
  277. /// The protocol modules.
  278. ///
  279. /// Each protocol lives in a submodule. Each submodule defines structs
  280. /// for Request (the message from the client to the bridge authority),
  281. /// State (the state held by the client while waiting for the reply),
  282. /// and Response (the message from the bridge authority to the client).
  283. /// Each submodule defines functions request, which produces a (Request,
  284. /// State) pair, and handle_response, which consumes a State and a
  285. /// Response. It also adds a handle_* function to the BridgeAuth struct
  286. /// that consumes a Request and produces a Result<Response, ProofError>.
  287. pub mod proto {
  288. pub mod migration;
  289. pub mod open_invite;
  290. pub mod trust_promotion;
  291. }
  292. // Unit tests
  293. #[cfg(test)]
  294. mod tests;