1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::collections::HashSet;

use crate::Keys;
use anyhow::{anyhow, ensure};
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use sodiumoxide::crypto::{
	aead::chacha20poly1305_ietf,
	kx::{PublicKey, SecretKey},
};
use sodiumoxide::{crypto::kx::x25519blake2b, randombytes};

use super::SEGMENT_SIZE;
const MAGIC_NUMBER: &[u8; 8] = b"crypt4gh";
const VERSION: u32 = 1;

#[derive(Serialize, Deserialize, PartialEq)]
enum PacketType {
	DataEnc = 0,
	EditList = 1,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct HeaderInfo {
	pub magic_number: [u8; 8],
	pub version: u32,
	pub packets_count: u32,
}

pub fn make_packet_data_enc(encryption_method: usize, session_key: &[u8; 32]) -> Vec<u8> {
	vec![
		bincode::serialize(&PacketType::DataEnc).expect("Unable to serialize packet type"),
		(encryption_method as u32).to_le_bytes().to_vec(),
		session_key.to_vec(),
	]
	.concat()
}

fn encrypt_x25519_chacha20_poly1305(data: &Vec<u8>, seckey: &Vec<u8>, recipient_pubkey: &Vec<u8>) -> Result<Vec<u8>> {
	let pubkey = crypto::curve25519::curve25519_base(&seckey[..32]);

	// Log
	log::debug!("   packed data({}): {:02x?}", data.len(), data);
	log::debug!("   my public key({}): {:02x?}", pubkey.len(), pubkey);
	log::debug!("   my private key({}): {:02x?}", seckey[0..32].len(), &seckey[0..32]);
	log::debug!(
		"   recipient public key({}): {:02x?}",
		recipient_pubkey.len(),
		recipient_pubkey
	);

	// X25519 shared key
	let server_pk = PublicKey::from_slice(pubkey.as_ref())
		.ok_or_else(|| anyhow!("Excryption failed -> Unable to extract public server key"))?;
	let server_sk = SecretKey::from_slice(&seckey[0..32])
		.ok_or_else(|| anyhow!("Excryption failed -> Unable to extract private server key"))?;
	let client_pk = PublicKey::from_slice(recipient_pubkey)
		.ok_or_else(|| anyhow!("Excryption failed -> Unable to extract public client key"))?;
	let (_, shared_key) = x25519blake2b::server_session_keys(&server_pk, &server_sk, &client_pk)
		.map_err(|_| anyhow!("Excryption failed -> Unable to create shared key"))?;
	log::debug!("   shared key: {:02x?}", shared_key.0);

	// Nonce & chacha20 key
	let nonce = chacha20poly1305_ietf::Nonce::from_slice(&randombytes::randombytes(12))
		.ok_or_else(|| anyhow!("Excryption failed -> Unable to create random nonce"))?;
	let key = chacha20poly1305_ietf::Key::from_slice(shared_key.as_ref())
		.ok_or_else(|| anyhow!("Excryption failed -> Unable to wrap shared key"))?;

	Ok(vec![
		pubkey.to_vec(),
		nonce.0.to_vec(),
		chacha20poly1305_ietf::seal(data, None, &nonce, &key),
	]
	.concat())
}

pub fn encrypt(packet: Vec<u8>, keys: &HashSet<Keys>) -> Result<Vec<Vec<u8>>> {
	keys.iter()
		.filter(|key| key.method == 0)
		.map(
			|key| match encrypt_x25519_chacha20_poly1305(&packet, &key.privkey, &key.recipient_pubkey) {
				Ok(session_key) => Ok(vec![(key.method as u32).to_le_bytes().to_vec(), session_key].concat()),
				Err(e) => Err(e),
			},
		)
		.collect()
}

pub fn serialize(packets: Vec<Vec<u8>>) -> Vec<u8> {
	log::info!("Serializing the header ({} packets)", packets.len());
	vec![
		MAGIC_NUMBER.to_vec(),
		(VERSION as u32).to_le_bytes().to_vec(),
		(packets.len() as u32).to_le_bytes().to_vec(),
		packets
			.into_iter()
			.map(|packet| vec![((packet.len() + 4) as u32).to_le_bytes().to_vec(), packet].concat())
			.flatten()
			.collect::<Vec<u8>>(),
	]
	.concat()
}

fn decrypt(
	encrypted_packets: Vec<Vec<u8>>,
	keys: &Vec<Keys>,
	sender_pubkey: Option<Vec<u8>>,
) -> (Vec<Vec<u8>>, Vec<Vec<u8>>) {
	let (decrypted_packets_pairs, ignored_packets_pairs): (Vec<(bool, Vec<u8>)>, Vec<(bool, Vec<u8>)>) =
		encrypted_packets
			.into_iter()
			.map(|packet| match decrypt_packet(&packet, keys, &sender_pubkey) {
				Ok(decrypted_packet) => (true, decrypted_packet),
				Err(_) => (false, packet),
			})
			.partition(|(is_decrypted, _)| *is_decrypted);

	let decrypted_packets = decrypted_packets_pairs.into_iter().map(|(_, packet)| packet).collect();

	let ignored_packets = ignored_packets_pairs.into_iter().map(|(_, packet)| packet).collect();

	(decrypted_packets, ignored_packets)
}

fn decrypt_packet(packet: &Vec<u8>, keys: &Vec<Keys>, sender_pubkey: &Option<Vec<u8>>) -> Result<Vec<u8>> {
	let packet_encryption_method = bincode::deserialize::<u32>(packet)?;
	log::debug!("Header Packet Encryption Method: {}", packet_encryption_method);

	for key in keys {
		if packet_encryption_method != (key.method as u32) {
			continue;
		}

		match packet_encryption_method {
			0 => return decrypt_x25519_chacha20_poly1305(&packet[4..], key.privkey.to_owned(), &sender_pubkey),
			1 => unimplemented!("AES-256-GCM support is not implemented"),
			n => bail!("Unsupported Header Encryption Method: {}", n),
		}
	}

	Err(anyhow!("Unable to encrypt packet"))
}

fn decrypt_x25519_chacha20_poly1305(
	encrypted_part: &[u8],
	privkey: Vec<u8>,
	sender_pubkey: &Option<Vec<u8>>,
) -> Result<Vec<u8>> {
	log::debug!("    my secret key: {:02x?}", &privkey[0..32]);

	let peer_pubkey = &encrypted_part[0..32];

	if sender_pubkey.is_some() && sender_pubkey.to_owned().unwrap().as_slice() != peer_pubkey {
		return Err(anyhow!("Invalid Peer's Public Key"));
	}

	let nonce = sodiumoxide::crypto::aead::chacha20poly1305_ietf::Nonce::from_slice(&encrypted_part[32..44])
		.ok_or_else(|| anyhow!("Decryption failed -> Unable to extract nonce"))?;
	let packet_data = &encrypted_part[44..];

	log::debug!("    peer pubkey: {:02x?}", peer_pubkey);
	log::debug!("    nonce: {:02x?}", nonce.0);
	log::debug!("    encrypted data ({}): {:02x?}", packet_data.len(), packet_data);

	// X25519 shared key
	let pubkey = crypto::curve25519::curve25519_base(&privkey[0..32]);
	let client_pk = PublicKey::from_slice(&pubkey)
		.ok_or_else(|| anyhow!("Decryption failed -> Unable to extract public client key"))?;
	let client_sk = SecretKey::from_slice(&privkey[0..32])
		.ok_or_else(|| anyhow!("Decryption failed -> Unable to extract private client key"))?;
	let server_pk = PublicKey::from_slice(&peer_pubkey)
		.ok_or_else(|| anyhow!("Decryption failed -> Unable to extract public server key"))?;
	let (shared_key, _) = x25519blake2b::client_session_keys(&client_pk, &client_sk, &server_pk)
		.map_err(|_| anyhow!("Decryption failed -> Unable to create shared key"))?;
	log::debug!("shared key: {:02x?}", shared_key.0);

	// Chacha20_Poly1305
	let key = chacha20poly1305_ietf::Key::from_slice(&shared_key.0)
		.ok_or_else(|| anyhow!("Decryption failed -> Unable to wrap shared key"))?;
	chacha20poly1305_ietf::open(packet_data, None, &nonce, &key)
		.map_err(|_| anyhow!("Decryption failed -> Invalid data"))
}

fn partition_packets(packets: Vec<Vec<u8>>) -> Result<(Vec<Vec<u8>>, Option<Vec<u8>>)> {
	let mut enc_packets = Vec::new();
	let mut edits = None;

	for packet in packets.into_iter() {
		let packet_type =
			bincode::deserialize::<PacketType>(&packet[0..4]).map_err(|_| anyhow!("Invalid packet type"))?;

		match packet_type {
			PacketType::DataEnc => {
				enc_packets.push(packet[4..].to_vec());
			},
			PacketType::EditList => {
				match edits {
					None => edits = Some(packet[4..].to_vec()),
					Some(_) => return Err(anyhow!("Invalid file: Too many edit list packets")),
				};
			},
		}
	}

	Ok((enc_packets, edits))
}

fn parse_enc_packet(packet: Vec<u8>) -> Result<Vec<u8>> {
	match packet[0..4] {
		[0, 0, 0, 0] => Ok(packet[4..].to_vec()),
		_ => Err(anyhow!(
			"Unsupported bulk encryption method: {}",
			bincode::deserialize::<u32>(&packet[0..4]).expect("Unable to deserialize bulk encryption method")
		)),
	}
}

fn parse_edit_list_packet(packet: Vec<u8>) -> Result<Vec<u64>> {
	let nb_lengths: u32 = bincode::deserialize::<u32>(&packet)
		.map_err(|_| anyhow!("Edit list packet did not contain the length of the list"))?;

	log::info!("Edit list length: {}", nb_lengths);
	log::info!("packet content length: {}", packet.len() - 4);

	if ((packet.len() as u32) - 4) < (8 * nb_lengths) {
		bail!("Invalid edit list")
	}

	(4..nb_lengths * 8)
		.step_by(8)
		.map(|i| {
			bincode::deserialize::<u64>(&packet[i as usize..])
				.map_err(|_| anyhow!("Unable to parse content of the edit list packet"))
		})
		.collect()
}

pub fn deconstruct_header_body(
	encrypted_packets: Vec<Vec<u8>>,
	keys: Vec<Keys>,
	sender_pubkey: Option<Vec<u8>>,
) -> Result<(Vec<Vec<u8>>, Option<Vec<u64>>)> {
	let (packets, _) = decrypt(encrypted_packets, &keys, sender_pubkey);

	if packets.is_empty() {
		bail!("No supported encryption method");
	}

	let (data_packets, edit_packet) = partition_packets(packets)?;

	let session_keys = data_packets
		.into_iter()
		.map(|packet| parse_enc_packet(packet))
		.collect::<Result<Vec<_>>>()?;

	let edit_list = match edit_packet {
		Some(packet) => Some(parse_edit_list_packet(packet)?),
		None => None,
	};

	Ok((session_keys, edit_list))
}

pub fn deconstruct_header_info(header_info_file: &[u8; std::mem::size_of::<HeaderInfo>()]) -> Result<HeaderInfo> {
	let header_info = bincode::deserialize::<HeaderInfo>(header_info_file)
		.map_err(|_| anyhow!("Unable to deconstruct header info"))?;

	ensure!(
		&header_info.magic_number == MAGIC_NUMBER,
		"Not a CRYPT4GH formatted file"
	);
	ensure!(
		header_info.version == VERSION,
		"Unsupported CRYPT4GH version (version = {})",
		header_info.version
	);

	Ok(header_info)
}

pub fn reencrypt(
	header_packets: Vec<Vec<u8>>,
	keys: Vec<Keys>,
	recipient_keys: HashSet<Keys>,
	trim: bool,
) -> Result<Vec<Vec<u8>>> {
	log::info!("Reencrypting the header");

	let (decrypted_packets, mut ignored_packets) = decrypt(header_packets, &keys, None);

	if decrypted_packets.is_empty() {
		Err(anyhow!("No header packet could be decrypted"))
	}
	else {
		let mut packets: Vec<Vec<u8>> = decrypted_packets
			.into_iter()
			.flat_map(|packet| encrypt(packet, &recipient_keys).unwrap())
			.collect();

		if !trim {
			packets.append(&mut ignored_packets);
		}

		Ok(packets)
	}
}

pub fn rearrange<'a>(
	header_packets: Vec<Vec<u8>>,
	keys: Vec<Keys>,
	range_start: usize,
	range_span: Option<usize>,
	sender_pubkey: Option<Vec<u8>>,
) -> Result<(Vec<Vec<u8>>, impl Iterator<Item = bool> + 'a)> {
	log::info!("Rearranging the header");

	log::debug!("    Start coordinate: {}", range_start);
	match range_span {
		Some(span) => {
			log::debug!("    End coordinate: {}", range_start + span);
			ensure!(span > 0, "Span should be greater than 0")
		},
		None => log::debug!("    End coordinate: EOF"),
	}
	log::debug!("    Segment size: {}", SEGMENT_SIZE);

	if range_start == 0 && range_span.is_none() {
		bail!("Nothing to be done")
	}

	let (decrypted_packets, _) = decrypt(header_packets, &keys, sender_pubkey);

	if decrypted_packets.is_empty() {
		bail!("No header packet could be decrypted")
	}

	let (data_packets, edit_packet) = partition_packets(decrypted_packets)?;

	if edit_packet.is_some() {
		unimplemented!()
	}

	log::info!("No edit list present: making one");

	let start_segment = range_start / SEGMENT_SIZE;
	let start_offset = range_start % SEGMENT_SIZE;
	let end_segment = range_span.map(|span| (range_start + span) / SEGMENT_SIZE);
	let end_offset = range_span.map(|span| (range_start + span) % SEGMENT_SIZE);

	log::debug!("Start segment: {} | Offset: {}", start_segment, start_offset);
	log::debug!("End segment: {:?} | Offset: {:?}", end_segment, end_offset);

	let segment_oracle = (0..).map(move |count| {
		if count < start_segment {
			false
		}
		else {
			match end_segment {
				Some(end) => count < end || (count == end && end_offset.unwrap() > 0),
				None => true,
			}
		}
	});

	let mut edit_list = vec![start_offset];
	if let Some(span) = range_span {
		edit_list.push(span);
	}

	log::debug!("New edit list: {:?}", edit_list);
	let edit_packet = make_packet_data_edit_list(edit_list);

	log::info!("Reencrypting all packets");

	let mut packets = data_packets
		.into_iter()
		.map(|packet| vec![bincode::serialize(&PacketType::DataEnc).unwrap(), packet].concat())
		.collect::<Vec<Vec<u8>>>();

	packets.push(edit_packet);

	let hash_keys = keys.into_iter().collect();

	let final_packets = packets
		.into_iter()
		.map(|packet| encrypt(packet, &hash_keys).and_then(|encrypted_packets| Ok(encrypted_packets.concat())))
		.collect::<Result<Vec<Vec<u8>>>>()?;

	Ok((final_packets, segment_oracle))
}

pub fn make_packet_data_edit_list(edit_list: Vec<usize>) -> Vec<u8> {
	vec![
		bincode::serialize(&PacketType::EditList).unwrap(),
		(edit_list.len() as u32).to_le_bytes().to_vec(),
		edit_list
			.into_iter()
			.flat_map(|n| (n as u64).to_le_bytes().to_vec())
			.collect(),
	]
	.concat()
}

#[cfg(test)]
mod tests {

	use super::*;

	#[test]
	fn enum_serialization_0() {
		assert_eq!(bincode::serialize(&PacketType::DataEnc).unwrap(), 0u32.to_le_bytes());
	}

	#[test]
	fn enum_serialization_1() {
		assert_eq!(bincode::serialize(&PacketType::EditList).unwrap(), 1u32.to_le_bytes());
	}
}