lib.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 private key for bucket reachability credentials
  165. reachability_priv: IssuerPrivKey,
  166. /// The public key for bucket reachability credentials
  167. pub reachability_pub: IssuerPubKey,
  168. /// The public key of the BridgeDb issuing open invitations
  169. pub bridgedb_pub: PublicKey,
  170. /// The bridge table
  171. bridge_table: bridge_table::BridgeTable,
  172. /// The migration table
  173. migration_table: migration_table::MigrationTable,
  174. /// Duplicate filter for open invitations
  175. openinv_filter: dup_filter::DupFilter<Scalar>,
  176. /// Duplicate filter for credential ids
  177. id_filter: dup_filter::DupFilter<Scalar>,
  178. /// Duplicate filter for trust promotions (from untrusted level 0 to
  179. /// trusted level 1)
  180. trust_promotion_filter: dup_filter::DupFilter<Scalar>,
  181. /// For testing only: offset of the true time to the simulated time
  182. time_offset: time::Duration,
  183. }
  184. impl BridgeAuth {
  185. pub fn new(bridgedb_pub: PublicKey) -> Self {
  186. // Create the private and public keys for each of the types of
  187. // credential, each with the appropriate number of attributes
  188. let lox_priv = IssuerPrivKey::new(6);
  189. let lox_pub = IssuerPubKey::new(&lox_priv);
  190. let migration_priv = IssuerPrivKey::new(3);
  191. let migration_pub = IssuerPubKey::new(&migration_priv);
  192. let migrationkey_priv = IssuerPrivKey::new(2);
  193. let migrationkey_pub = IssuerPubKey::new(&migrationkey_priv);
  194. let reachability_priv = IssuerPrivKey::new(2);
  195. let reachability_pub = IssuerPubKey::new(&reachability_priv);
  196. Self {
  197. lox_priv,
  198. lox_pub,
  199. migration_priv,
  200. migration_pub,
  201. migrationkey_priv,
  202. migrationkey_pub,
  203. reachability_priv,
  204. reachability_pub,
  205. bridgedb_pub,
  206. bridge_table: Default::default(),
  207. migration_table: Default::default(),
  208. openinv_filter: Default::default(),
  209. id_filter: Default::default(),
  210. trust_promotion_filter: Default::default(),
  211. time_offset: time::Duration::zero(),
  212. }
  213. }
  214. #[cfg(test)]
  215. /// For testing only: manually advance the day by 1 day
  216. pub fn advance_day(&mut self) {
  217. self.time_offset += time::Duration::days(1);
  218. }
  219. #[cfg(test)]
  220. /// For testing only: manually advance the day by the given number
  221. /// of days
  222. pub fn advance_days(&mut self, days: u16) {
  223. self.time_offset += time::Duration::days(days.into());
  224. }
  225. /// Get today's (real or simulated) date
  226. fn today(&self) -> u32 {
  227. // We will not encounter negative Julian dates (~6700 years ago)
  228. // or ones larger than 32 bits
  229. (time::OffsetDateTime::now_utc().date() + self.time_offset)
  230. .julian_day()
  231. .try_into()
  232. .unwrap()
  233. }
  234. /// Get a reference to the encrypted bridge table.
  235. ///
  236. /// Be sure to call this function when you want the latest version
  237. /// of the table, since it will put fresh Bucket Reachability
  238. /// credentials in the buckets each day.
  239. pub fn enc_bridge_table(&mut self) -> &Vec<[u8; bridge_table::ENC_BUCKET_BYTES]> {
  240. let today = self.today();
  241. if self.bridge_table.date_last_enc != today {
  242. self.bridge_table
  243. .encrypt_table(today, &self.reachability_priv);
  244. }
  245. &self.bridge_table.encbuckets
  246. }
  247. #[cfg(test)]
  248. /// Verify the two MACs on a Lox credential
  249. pub fn verify_lox(&self, cred: &cred::Lox) -> bool {
  250. if cred.P.is_identity() {
  251. return false;
  252. }
  253. let Q = (self.lox_priv.x[0]
  254. + cred.id * self.lox_priv.x[1]
  255. + cred.bucket * self.lox_priv.x[2]
  256. + cred.trust_level * self.lox_priv.x[3]
  257. + cred.level_since * self.lox_priv.x[4]
  258. + cred.invites_remaining * self.lox_priv.x[5]
  259. + cred.blockages * self.lox_priv.x[6])
  260. * cred.P;
  261. Q == cred.Q
  262. }
  263. #[cfg(test)]
  264. /// Verify the MAC on a Migration credential
  265. pub fn verify_migration(&self, cred: &cred::Migration) -> bool {
  266. if cred.P.is_identity() {
  267. return false;
  268. }
  269. let Q = (self.migration_priv.x[0]
  270. + cred.lox_id * self.migration_priv.x[1]
  271. + cred.from_bucket * self.migration_priv.x[2]
  272. + cred.to_bucket * self.migration_priv.x[3])
  273. * cred.P;
  274. Q == cred.Q
  275. }
  276. #[cfg(test)]
  277. /// Verify the MAC on a Bucket Reachability credential
  278. pub fn verify_reachability(&self, cred: &cred::BucketReachability) -> bool {
  279. if cred.P.is_identity() {
  280. return false;
  281. }
  282. let Q = (self.reachability_priv.x[0]
  283. + cred.date * self.reachability_priv.x[1]
  284. + cred.bucket * self.reachability_priv.x[2])
  285. * cred.P;
  286. Q == cred.Q
  287. }
  288. }
  289. /// Try to extract a u64 from a Scalar
  290. pub fn scalar_u64(s: &Scalar) -> Option<u64> {
  291. // Check that the top 24 bytes of the Scalar are 0
  292. let sbytes = s.as_bytes();
  293. if sbytes[8..].ct_eq(&[0u8; 24]).unwrap_u8() == 0 {
  294. return None;
  295. }
  296. Some(u64::from_le_bytes(sbytes[..8].try_into().unwrap()))
  297. }
  298. /// Try to extract a u32 from a Scalar
  299. pub fn scalar_u32(s: &Scalar) -> Option<u32> {
  300. // Check that the top 28 bytes of the Scalar are 0
  301. let sbytes = s.as_bytes();
  302. if sbytes[4..].ct_eq(&[0u8; 28]).unwrap_u8() == 0 {
  303. return None;
  304. }
  305. Some(u32::from_le_bytes(sbytes[..4].try_into().unwrap()))
  306. }
  307. /// Double a Scalar
  308. pub fn scalar_dbl(s: &Scalar) -> Scalar {
  309. s + s
  310. }
  311. /// Double a RistrettoPoint
  312. pub fn pt_dbl(P: &RistrettoPoint) -> RistrettoPoint {
  313. P + P
  314. }
  315. /// The protocol modules.
  316. ///
  317. /// Each protocol lives in a submodule. Each submodule defines structs
  318. /// for Request (the message from the client to the bridge authority),
  319. /// State (the state held by the client while waiting for the reply),
  320. /// and Response (the message from the bridge authority to the client).
  321. /// Each submodule defines functions request, which produces a (Request,
  322. /// State) pair, and handle_response, which consumes a State and a
  323. /// Response. It also adds a handle_* function to the BridgeAuth struct
  324. /// that consumes a Request and produces a Result<Response, ProofError>.
  325. pub mod proto {
  326. pub mod level_up;
  327. pub mod migration;
  328. pub mod open_invite;
  329. pub mod trust_promotion;
  330. }
  331. // Unit tests
  332. #[cfg(test)]
  333. mod tests;