migration_table.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. migration_type: &Scalar,
  71. Pktable: &RistrettoBasepointTable,
  72. migration_priv: &IssuerPrivKey,
  73. migrationkey_priv: &IssuerPrivKey,
  74. ) -> ([u8; 16], [u8; ENC_MIGRATION_BYTES]) {
  75. let Btable: &RistrettoBasepointTable = &CMZ_B_TABLE;
  76. let mut rng = rand::thread_rng();
  77. // Compute the Migration Key credential MAC Qk
  78. let Qk = &(migrationkey_priv.x[0]
  79. + migrationkey_priv.x[1] * id
  80. + migrationkey_priv.x[2] * from_bucket)
  81. * Pktable;
  82. // Compute a MAC (P, Q) on the Migration credential
  83. let b = Scalar::random(&mut rng);
  84. let P = &b * Btable;
  85. let Q = &(b
  86. * (migration_priv.x[0]
  87. + migration_priv.x[1] * id
  88. + migration_priv.x[2] * from_bucket
  89. + migration_priv.x[3] * to_bucket
  90. + migration_priv.x[4] * migration_type))
  91. * Btable;
  92. // Serialize (to_bucket, P, Q)
  93. let mut credbytes: [u8; MIGRATION_BYTES] = [0; MIGRATION_BYTES];
  94. credbytes[0..32].copy_from_slice(to_bucket.as_bytes());
  95. credbytes[32..64].copy_from_slice(P.compress().as_bytes());
  96. credbytes[64..].copy_from_slice(Q.compress().as_bytes());
  97. // Pick a random nonce
  98. let mut noncebytes: [u8; 12] = [0; 12];
  99. rng.fill_bytes(&mut noncebytes);
  100. let nonce = GenericArray::from_slice(&noncebytes);
  101. // Compute the hash of (id, from_bucket, Qk)
  102. let mut hasher = Sha256::new();
  103. hasher.update(id.as_bytes());
  104. hasher.update(from_bucket.as_bytes());
  105. hasher.update(Qk.compress().as_bytes());
  106. let fullhash = hasher.finalize();
  107. // Create the encryption key from the 2nd half of the hash
  108. let aeskey = GenericArray::from_slice(&fullhash[16..]);
  109. // Encrypt
  110. let cipher = Aes128Gcm::new(aeskey);
  111. let ciphertext: Vec<u8> = cipher.encrypt(nonce, credbytes.as_ref()).unwrap();
  112. let mut enccredbytes: [u8; ENC_MIGRATION_BYTES] = [0; ENC_MIGRATION_BYTES];
  113. enccredbytes[..12].copy_from_slice(&noncebytes);
  114. enccredbytes[12..].copy_from_slice(ciphertext.as_slice());
  115. // Use the first half of the above hash as the label
  116. let mut label: [u8; 16] = [0; 16];
  117. label[..].copy_from_slice(&fullhash[..16]);
  118. (label, enccredbytes)
  119. }
  120. /// Create an encrypted Migration credential for returning to the user
  121. /// in the trust promotion protocol, given the ids of the from and to
  122. /// buckets, and the migration type, and using a BridgeTable to get the
  123. /// bucket keys.
  124. ///
  125. /// Otherwise the same as encrypt_cred, above, except it returns an
  126. /// Option in case the passed ids were invalid.
  127. pub fn encrypt_cred_ids(
  128. id: &Scalar,
  129. from_id: u32,
  130. to_id: u32,
  131. migration_type: &Scalar,
  132. bridgetable: &bridge_table::BridgeTable,
  133. Pktable: &RistrettoBasepointTable,
  134. migration_priv: &IssuerPrivKey,
  135. migrationkey_priv: &IssuerPrivKey,
  136. ) -> Option<([u8; 16], [u8; ENC_MIGRATION_BYTES])> {
  137. // Look up the bucket keys and form the attributes (Scalars)
  138. let fromkey = bridgetable.keys.get(from_id as usize)?;
  139. let tokey = bridgetable.keys.get(to_id as usize)?;
  140. Some(encrypt_cred(
  141. id,
  142. &bridge_table::to_scalar(from_id, fromkey),
  143. &bridge_table::to_scalar(to_id, tokey),
  144. migration_type,
  145. Pktable,
  146. migration_priv,
  147. migrationkey_priv,
  148. ))
  149. }
  150. impl MigrationTable {
  151. /// Create a MigrationTable of the given MigrationType
  152. pub fn new(table_type: MigrationType) -> Self {
  153. Self {
  154. table: Default::default(),
  155. migration_type: table_type.into(),
  156. }
  157. }
  158. /// For each entry in the MigrationTable, use encrypt_cred_ids to
  159. /// produce an entry in an output HashMap (from labels to encrypted
  160. /// Migration credentials).
  161. pub fn encrypt_table(
  162. &self,
  163. id: &Scalar,
  164. bridgetable: &bridge_table::BridgeTable,
  165. Pktable: &RistrettoBasepointTable,
  166. migration_priv: &IssuerPrivKey,
  167. migrationkey_priv: &IssuerPrivKey,
  168. ) -> HashMap<[u8; 16], [u8; ENC_MIGRATION_BYTES]> {
  169. self.table
  170. .iter()
  171. .filter_map(|(from_id, to_id)| {
  172. encrypt_cred_ids(
  173. id,
  174. *from_id,
  175. *to_id,
  176. &self.migration_type,
  177. bridgetable,
  178. Pktable,
  179. migration_priv,
  180. migrationkey_priv,
  181. )
  182. })
  183. .collect()
  184. }
  185. }
  186. /// Decrypt an encrypted Migration credential given Qk, the known
  187. /// attributes id and from_bucket for the Migration credential as well
  188. /// as the known migration type, and a HashMap mapping labels to
  189. /// ciphertexts.
  190. pub fn decrypt_cred(
  191. Qk: &RistrettoPoint,
  192. lox_id: &Scalar,
  193. from_bucket: &Scalar,
  194. migration_type: MigrationType,
  195. enc_migration_table: &HashMap<[u8; 16], [u8; ENC_MIGRATION_BYTES]>,
  196. ) -> Option<Migration> {
  197. // Compute the hash of (id, from_bucket, Qk)
  198. let mut hasher = Sha256::new();
  199. hasher.update(lox_id.as_bytes());
  200. hasher.update(from_bucket.as_bytes());
  201. hasher.update(Qk.compress().as_bytes());
  202. let fullhash = hasher.finalize();
  203. // Use the first half of the above hash as the label
  204. let mut label: [u8; 16] = [0; 16];
  205. label[..].copy_from_slice(&fullhash[..16]);
  206. // Look up the label in the HashMap
  207. let ciphertext = enc_migration_table.get(&label)?;
  208. // Create the decryption key from the 2nd half of the hash
  209. let aeskey = GenericArray::from_slice(&fullhash[16..]);
  210. // Decrypt
  211. let nonce = GenericArray::from_slice(&ciphertext[..12]);
  212. let cipher = Aes128Gcm::new(aeskey);
  213. let plaintext: Vec<u8> = match cipher.decrypt(nonce, ciphertext[12..].as_ref()) {
  214. Ok(v) => v,
  215. Err(_) => return None,
  216. };
  217. let plaintextbytes = plaintext.as_slice();
  218. let mut to_bucket_bytes: [u8; 32] = [0; 32];
  219. to_bucket_bytes.copy_from_slice(&plaintextbytes[..32]);
  220. let to_bucket = Scalar::from_bytes_mod_order(to_bucket_bytes);
  221. let P = CompressedRistretto::from_slice(&plaintextbytes[32..64]).decompress()?;
  222. let Q = CompressedRistretto::from_slice(&plaintextbytes[64..]).decompress()?;
  223. Some(Migration {
  224. P,
  225. Q,
  226. lox_id: *lox_id,
  227. from_bucket: *from_bucket,
  228. to_bucket,
  229. migration_type: migration_type.into(),
  230. })
  231. }