lib.rs 14 KB

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