migration_table.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*! The migration table.
  2. This is a table listing pairs of (from_bucket_id, to_bucket_id). A pair
  3. in this table indicates that a user with a Lox credential containing
  4. from_bucket_id (and possibly meeting other conditions as well) is
  5. entitled to exchange their credential for one with to_bucket_id. (Note
  6. that the credentials contain the bucket attributes, which include both
  7. the id and the bucket decrytpion key, but the table just contains the
  8. bucket ids.) */
  9. use curve25519_dalek::ristretto::CompressedRistretto;
  10. use curve25519_dalek::ristretto::RistrettoBasepointTable;
  11. use curve25519_dalek::ristretto::RistrettoPoint;
  12. use curve25519_dalek::scalar::Scalar;
  13. use sha2::Digest;
  14. use sha2::Sha256;
  15. use aes_gcm::aead::{generic_array::GenericArray, Aead, NewAead};
  16. use aes_gcm::Aes128Gcm;
  17. use rand::RngCore;
  18. use std::collections::HashMap;
  19. use super::bridge_table;
  20. use super::cred::Migration;
  21. use super::IssuerPrivKey;
  22. use super::CMZ_B_TABLE;
  23. /// Each (plaintext) entry in the returned migration table is serialized
  24. /// into this many bytes
  25. pub const MIGRATION_BYTES: usize = 96;
  26. /// The size of an encrypted entry in the returned migration table
  27. pub const ENC_MIGRATION_BYTES: usize = MIGRATION_BYTES + 12 + 16;
  28. /// The type of migration table: TrustUpgrade is for migrations from
  29. /// untrusted (level 0) 1-bridge buckets to trusted (level 1) 3-bridge
  30. /// buckets. Blockage is for migrations that drop you down two levels
  31. /// (level 3 to 1, level 4 to 2) because the bridges in your current
  32. /// bucket were blocked.
  33. pub enum MigrationType {
  34. TrustUpgrade,
  35. Blockage,
  36. }
  37. impl From<MigrationType> for Scalar {
  38. /// Convert a MigrationType into the Scalar value that represents
  39. /// it in the Migration credential
  40. fn from(m: MigrationType) -> Self {
  41. match m {
  42. MigrationType::TrustUpgrade => 0u32,
  43. MigrationType::Blockage => 1u32,
  44. }
  45. .into()
  46. }
  47. }
  48. /// The migration table
  49. #[derive(Default, Debug)]
  50. pub struct MigrationTable {
  51. pub table: HashMap<u32, u32>,
  52. pub migration_type: Scalar,
  53. }
  54. /// Create an encrypted Migration credential for returning to the user
  55. /// in the trust promotion protocol.
  56. ///
  57. /// Given the attributes of a Migration credential, produce a serialized
  58. /// version (containing only the to_bucket and the MAC, since the
  59. /// receiver will already know the id and from_bucket), encrypted with
  60. /// H2(id, from_bucket, Qk), for the Qk portion of the MAC on the
  61. /// corresponding Migration Key credential (with fixed Pk, given as a
  62. /// precomputed multiplication table). Return the label H1(id,
  63. /// from_attr_i, Qk_i) and the encrypted Migration credential. H1 and
  64. /// H2 are the first 16 bytes and the second 16 bytes respectively of
  65. /// the SHA256 hash of the input.
  66. pub fn encrypt_cred(
  67. id: &Scalar,
  68. from_bucket: &Scalar,
  69. to_bucket: &Scalar,
  70. Pktable: &RistrettoBasepointTable,
  71. migration_priv: &IssuerPrivKey,
  72. migrationkey_priv: &IssuerPrivKey,
  73. ) -> ([u8; 16], [u8; ENC_MIGRATION_BYTES]) {
  74. let Btable: &RistrettoBasepointTable = &CMZ_B_TABLE;
  75. let mut rng = rand::thread_rng();
  76. // Compute the Migration Key credential MAC Qk
  77. let Qk = &(migrationkey_priv.x[0]
  78. + migrationkey_priv.x[1] * id
  79. + migrationkey_priv.x[2] * from_bucket)
  80. * Pktable;
  81. // Compute a MAC (P, Q) on the Migration credential
  82. let b = Scalar::random(&mut rng);
  83. let P = &b * Btable;
  84. let Q = &(b
  85. * (migration_priv.x[0]
  86. + migration_priv.x[1] * id
  87. + migration_priv.x[2] * from_bucket
  88. + migration_priv.x[3] * to_bucket))
  89. * Btable;
  90. // Serialize (to_bucket, P, Q)
  91. let mut credbytes: [u8; MIGRATION_BYTES] = [0; MIGRATION_BYTES];
  92. credbytes[0..32].copy_from_slice(to_bucket.as_bytes());
  93. credbytes[32..64].copy_from_slice(P.compress().as_bytes());
  94. credbytes[64..].copy_from_slice(Q.compress().as_bytes());
  95. // Pick a random nonce
  96. let mut noncebytes: [u8; 12] = [0; 12];
  97. rng.fill_bytes(&mut noncebytes);
  98. let nonce = GenericArray::from_slice(&noncebytes);
  99. // Compute the hash of (id, from_bucket, Qk)
  100. let mut hasher = Sha256::new();
  101. hasher.update(id.as_bytes());
  102. hasher.update(from_bucket.as_bytes());
  103. hasher.update(Qk.compress().as_bytes());
  104. let fullhash = hasher.finalize();
  105. // Create the encryption key from the 2nd half of the hash
  106. let aeskey = GenericArray::from_slice(&fullhash[16..]);
  107. // Encrypt
  108. let cipher = Aes128Gcm::new(aeskey);
  109. let ciphertext: Vec<u8> = cipher.encrypt(&nonce, credbytes.as_ref()).unwrap();
  110. let mut enccredbytes: [u8; ENC_MIGRATION_BYTES] = [0; ENC_MIGRATION_BYTES];
  111. enccredbytes[..12].copy_from_slice(&noncebytes);
  112. enccredbytes[12..].copy_from_slice(ciphertext.as_slice());
  113. // Use the first half of the above hash as the label
  114. let mut label: [u8; 16] = [0; 16];
  115. label[..].copy_from_slice(&fullhash[..16]);
  116. (label, enccredbytes)
  117. }
  118. /// Create an encrypted Migration credential for returning to the user
  119. /// in the trust promotion protocol, given the ids of the from and to
  120. /// buckets, and using a BridgeTable to get the bucket keys.
  121. ///
  122. /// Otherwise the same as encrypt_cred, above, except it returns an
  123. /// Option in case the passed ids were invalid.
  124. pub fn encrypt_cred_ids(
  125. id: &Scalar,
  126. from_id: u32,
  127. to_id: u32,
  128. bridgetable: &bridge_table::BridgeTable,
  129. Pktable: &RistrettoBasepointTable,
  130. migration_priv: &IssuerPrivKey,
  131. migrationkey_priv: &IssuerPrivKey,
  132. ) -> Option<([u8; 16], [u8; ENC_MIGRATION_BYTES])> {
  133. // Look up the bucket keys and form the attributes (Scalars)
  134. let fromkey = bridgetable.keys.get(from_id as usize)?;
  135. let tokey = bridgetable.keys.get(to_id as usize)?;
  136. Some(encrypt_cred(
  137. id,
  138. &bridge_table::to_scalar(from_id, fromkey),
  139. &bridge_table::to_scalar(to_id, tokey),
  140. Pktable,
  141. migration_priv,
  142. migrationkey_priv,
  143. ))
  144. }
  145. impl MigrationTable {
  146. /// Create a MigrationTable of the given MigrationType
  147. pub fn new(table_type: MigrationType) -> Self {
  148. Self {
  149. table: Default::default(),
  150. migration_type: table_type.into(),
  151. }
  152. }
  153. /// For each entry in the MigrationTable, use encrypt_cred_ids to
  154. /// produce an entry in an output HashMap (from labels to encrypted
  155. /// Migration credentials).
  156. pub fn encrypt_table(
  157. &self,
  158. id: &Scalar,
  159. bridgetable: &bridge_table::BridgeTable,
  160. Pktable: &RistrettoBasepointTable,
  161. migration_priv: &IssuerPrivKey,
  162. migrationkey_priv: &IssuerPrivKey,
  163. ) -> HashMap<[u8; 16], [u8; ENC_MIGRATION_BYTES]> {
  164. self.table
  165. .iter()
  166. .filter_map(|(from_id, to_id)| {
  167. encrypt_cred_ids(
  168. id,
  169. *from_id,
  170. *to_id,
  171. bridgetable,
  172. Pktable,
  173. migration_priv,
  174. migrationkey_priv,
  175. )
  176. })
  177. .collect()
  178. }
  179. }
  180. /// Decrypt an encrypted Migration credential given Qk, the known
  181. /// attributes id and from_bucket for the Migration credential, and a
  182. /// HashMap mapping labels to ciphertexts.
  183. pub fn decrypt_cred(
  184. Qk: &RistrettoPoint,
  185. lox_id: &Scalar,
  186. from_bucket: &Scalar,
  187. enc_migration_table: &HashMap<[u8; 16], [u8; ENC_MIGRATION_BYTES]>,
  188. ) -> Option<Migration> {
  189. // Compute the hash of (id, from_bucket, Qk)
  190. let mut hasher = Sha256::new();
  191. hasher.update(lox_id.as_bytes());
  192. hasher.update(from_bucket.as_bytes());
  193. hasher.update(Qk.compress().as_bytes());
  194. let fullhash = hasher.finalize();
  195. // Use the first half of the above hash as the label
  196. let mut label: [u8; 16] = [0; 16];
  197. label[..].copy_from_slice(&fullhash[..16]);
  198. // Look up the label in the HashMap
  199. let ciphertext = enc_migration_table.get(&label)?;
  200. // Create the decryption key from the 2nd half of the hash
  201. let aeskey = GenericArray::from_slice(&fullhash[16..]);
  202. // Decrypt
  203. let nonce = GenericArray::from_slice(&ciphertext[..12]);
  204. let cipher = Aes128Gcm::new(aeskey);
  205. let plaintext: Vec<u8> = match cipher.decrypt(&nonce, ciphertext[12..].as_ref()) {
  206. Ok(v) => v,
  207. Err(_) => return None,
  208. };
  209. let plaintextbytes = plaintext.as_slice();
  210. let mut to_bucket_bytes: [u8; 32] = [0; 32];
  211. to_bucket_bytes.copy_from_slice(&plaintextbytes[..32]);
  212. let to_bucket = Scalar::from_bytes_mod_order(to_bucket_bytes);
  213. let P = CompressedRistretto::from_slice(&plaintextbytes[32..64]).decompress()?;
  214. let Q = CompressedRistretto::from_slice(&plaintextbytes[64..]).decompress()?;
  215. Some(Migration {
  216. P,
  217. Q,
  218. lox_id: *lox_id,
  219. from_bucket: *from_bucket,
  220. to_bucket,
  221. })
  222. }