otr_utils/
decoding.rs

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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use anyhow::{anyhow, Context};
use base64::{engine::general_purpose, Engine};
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cbc, Ecb};
use blowfish::BlowfishLE;
use chrono::Datelike;
use log::*;
use md5::{Digest, Md5};
use std::{
    clone::Clone,
    collections::HashMap,
    fmt::Debug,
    fs::remove_file,
    fs::File,
    io::prelude::*,
    marker::Copy,
    path::Path,
    str,
    sync::mpsc::{channel, Receiver},
    thread,
};

/// URL of OTR web service to request decoding key
const OTR_URL: &str = "http://onlinetvrecorder.com/quelle_neu1.php";
/// Decoder version to be used in decoding key requests
const DECODER_VERSION: &str = "0.4.1133";
/// Sizes of different parts of the encoded video file
const FILETYPE_LENGTH: usize = 10;
const PREAMBLE_LENGTH: usize = 512;
const HEADER_LENGTH: usize = FILETYPE_LENGTH + PREAMBLE_LENGTH;
/// OTR key values
const PREAMBLE_KEY: &str = "EF3AB29CD19F0CAC5759C7ABD12CC92BA3FE0AFEBF960D63FEBD0F45";
const IK: &str = "aFzW1tL7nP9vXd8yUfB5kLoSyATQ";
/// String to verify that the encoded video file has the right type
const OTRKEY_FILETYPE: &str = "OTRKEYFILE";
/// error indicator in OTR response
const OTR_ERROR_INDICATOR: &str = "MessageToBePrintedInDecoder";
/// Keys of parameters contained in the file header
const PARAM_FILENAME: &str = "FN";
const PARAM_FILESIZE: &str = "SZ";
const PARAM_ENCODED_HASH: &str = "OH";
const PARAM_DECODED_HASH: &str = "FH";
/// Keys of parameters contained in the response to the decoding key request
const PARAM_DECODING_KEY: &str = "HP";
/// Sizes for decoding. MAX_CHUNK_SIZE must be a multiple of BLOCK_SIZE
const BLOCK_SIZE: usize = 8;
const MAX_CHUNK_SIZE: usize = 10 * 1024 * 1024;

/// Map parameter keys to its values (key->value)
type OTRParams = HashMap<String, String>;

/// Part of a video file for concurrent decoding
type Chunk = Vec<u8>;

/// Decode a encoded video file. in_video is the path of the decoded video file.
/// out_video is the path of the cut video file.
pub fn decode<P, Q>(in_video: P, out_video: Q, user: &str, password: &str) -> anyhow::Result<()>
where
    P: AsRef<Path>,
    Q: AsRef<Path> + Debug + Copy,
{
    // MAX_CHUNK_SIZE must be a multiple of BLOCK_SIZE
    if MAX_CHUNK_SIZE % BLOCK_SIZE != 0 {
        return Err(anyhow!(
            "Chunk size [{}] is not a multiple of block size [{}]",
            MAX_CHUNK_SIZE,
            BLOCK_SIZE
        ));
    }

    // Retrieve parameters from header of encoded video file
    let mut in_file = File::open(&in_video)?;
    let header_params =
        header_params(&mut in_file).with_context(|| "Could not extract video header from")?;

    // Check size of encoded video file
    if (in_file.metadata()?.len() as usize) < file_size_from_params(&header_params) {
        return Err(anyhow!("Video file seems to be corrupt: it is too small"));
    }

    // Current date
    let now = current_date();
    // Get key that is needed to encrypt the payload of the decoding key request
    let cbc_key = cbc_key(user, password, &now).with_context(|| {
        "Could not determine CBC key for encryption of decoding key request payload"
    })?;
    // Get parameters for decoding (particularly the decoding key)
    let decoding_params = decoding_params(
        &cbc_key,
        &decoding_params_request(&cbc_key, &header_params, user, password, &now)
            .with_context(|| "Could not assemble request for decoding key")?,
    )
    .with_context(|| "Could not retrieve decoding key")?;

    // Decode encoded video file in concurrent threads using the decoding key
    if let Err(err) = decode_in_parallel(
        &mut in_file,
        out_video,
        &header_params,
        decoding_params.get(PARAM_DECODING_KEY).unwrap(),
    ) {
        remove_file(out_video).unwrap_or_else(|_| {
            panic!(
                "Could not delete file \"{}\" after error when decoding video",
                out_video.as_ref().display()
            )
        });
        return Err(err);
    }

    // Remove encoded video file
    remove_file(&in_video).with_context(|| "Could not delete video after successful decoding")?;

    Ok(())
}

/// Key that is needed to encrypt the payload of the decoding key request
fn cbc_key(user: &str, password: &str, now: &str) -> anyhow::Result<String> {
    let user_hash = format!("{:02x}", Md5::digest(user.as_bytes()));
    let password_hash = format!("{:02x}", Md5::digest(password.as_bytes()));
    let cbc_key: String = user_hash[0..13].to_string()
        + &now[..4]
        + &password_hash[0..11]
        + &now[4..6]
        + &user_hash[21..32]
        + &now[6..]
        + &password_hash[19..32];

    debug!("CBC_KEY:\n{}", cbc_key);

    Ok(cbc_key)
}

/// Calculate the sizes of the different chunks for parallel decoding. The
/// result is a vector [MAX_CHUNK_SIZE, ..., MAX_CHUNK_SIZE, CHUNK_SIZE,
/// REMAINDER], whereas CHUNK_SIZE is less than MAX_CHUNK_SIZE but is a multiple
/// of BLOCK_SIZE. REMAINDER is less than BLOCK_SIZE.
fn chunk_sizes(file_size: usize) -> Vec<usize> {
    let (full_chunks, remainder) = (file_size / MAX_CHUNK_SIZE, file_size % MAX_CHUNK_SIZE);
    let mut sizes: Vec<usize> = vec![MAX_CHUNK_SIZE; full_chunks];
    if remainder / BLOCK_SIZE > 0 {
        sizes.push(remainder / BLOCK_SIZE * BLOCK_SIZE);
    }
    if remainder % BLOCK_SIZE > 0 {
        sizes.push(remainder % BLOCK_SIZE);
    }
    sizes
}

/// Current date and returns it as numeric string of format "YYYYMMDD"
fn current_date() -> String {
    let now = chrono::Local::now().date_naive();
    format!("{:04}{:02}{:02}", now.year(), now.month(), now.day())
}

/// Decode one chunk of an encoded video file and return the corresponding
/// decoded chunk. This function is called in a dedicated thread for each
/// chunk.
fn decode_chunk(key: &str, mut chunk: Chunk) -> Chunk {
    // Chunks can only be decoded if their size is greater than
    // BLOCK_SIZE. Otherwise, the chunk is returned encoded
    if chunk.capacity() >= BLOCK_SIZE {
        Ecb::<BlowfishLE, NoPadding>::new_from_slices(
            &hex::decode(key).expect("Could not turn decoding key into hex string"),
            &hex::decode("").unwrap(),
        )
        .unwrap_or_else(|_| panic!("Could not create cipher object for decoding of chunk"))
        .decrypt(&mut chunk)
        .unwrap_or_else(|_| panic!("Could not decode chunk"));
    }
    chunk
}

/// Decode a video file (in_file) in concurrent threads using key as decoding
/// key and write the result to out_video
fn decode_in_parallel<P>(
    in_file: &mut File,
    out_video: P,
    header_params: &OTRParams,
    key: &str,
) -> anyhow::Result<()>
where
    P: AsRef<Path> + Debug,
{
    // Output file
    let mut out_file = File::create(&out_video).with_context(|| {
        format!(
            "Could not create result file \"{}\"",
            out_video.as_ref().display()
        )
    })?;

    // Thread handle to be able to wait until all threads are done
    let mut thread_handles = vec![];

    // Create channels and start threads to determine the checksums of the video
    // file before and after decoding, if that is required
    let (enc_hash_sender, enc_hash_receiver) = channel();
    let (dec_hash_sender, dec_hash_receiver) = channel();
    let (enc_hash_handle, dec_hash_handle) = (
        thread::spawn(move || -> [u8; 16] { hashing_queue(enc_hash_receiver) }),
        thread::spawn(move || -> [u8; 16] { hashing_queue(dec_hash_receiver) }),
    );

    // Read the chunks sequentially and start and decode each chunk in a
    // separate thread
    for chunk_size in chunk_sizes(file_size_from_params(header_params) - HEADER_LENGTH) {
        // Allocate next chunk
        let mut chunk = vec![0u8; chunk_size];

        // Read chunk from encoded file and check number of bytes that were read
        if in_file
            .read(&mut chunk[..chunk_size])
            .with_context(|| "Could not read chunk")?
            < chunk_size
        {
            return Err(anyhow!("Chunk is too short"));
        }

        // Update hasher to determine the checksum of the encoded file
        enc_hash_sender.send(chunk.clone()).unwrap();

        // Decode chunk in new thread. Each thread returns the decoded chunk
        let dec_key = key.to_string();
        thread_handles.push(thread::spawn(move || -> Chunk {
            decode_chunk(&dec_key, chunk)
        }));
    }

    // Sender must be dropped explicitly to make hasher thread terminating
    drop(enc_hash_sender);

    // Join thread results. I.e., receive chunks and write them to the output
    // file. The chunk sequence is kept by the sequence of thread handles in the
    // thread handles vector
    for handle in thread_handles {
        match handle.join() {
            Ok(chunk) => {
                // update hasher to determine the checksum of the decoded file
                dec_hash_sender.send(chunk.clone()).unwrap();
                // write content to output file
                out_file.write_all(&chunk).with_context(|| {
                    format!(
                        "Could not write to decoded video file \"{}\"",
                        out_video.as_ref().display(),
                    )
                })?;
            }
            Err(_) => {
                return Err(anyhow!(
                    "Could not create decoded video file \"{}\"",
                    out_video.as_ref().display()
                ));
            }
        }
    }

    // Sender must be dropped explicitly to make hasher thread terminating
    drop(dec_hash_sender);

    // Check MD5 checksums
    if !verify_checksum(
        &enc_hash_handle.join().unwrap(),
        &header_params[PARAM_ENCODED_HASH],
    )
    .context("Could not verify checksum of encoded video file")?
    {
        return Err(anyhow!("MD5 checksum of encoded video file is not correct"));
    }
    if !verify_checksum(
        &dec_hash_handle.join().unwrap(),
        &header_params[PARAM_DECODED_HASH],
    )
    .context("Could not verify checksum of decoded video file")?
    {
        return Err(anyhow!("MD5 checksum of decoded video file is not correct"));
    }

    Ok(())
}

/// Request decoding parameters (incl. decoding key) via OTR web service and
/// return them as hash map: key -> value.
fn decoding_params(cbc_key: &str, request: &str) -> anyhow::Result<OTRParams> {
    // Request decoding key from OTR
    let response = reqwest::blocking::Client::builder()
        .user_agent("Windows-OTR-Decoder/".to_string() + DECODER_VERSION)
        .build()
        .with_context(|| "Could not create HTTP client to request decoding key")?
        .get(request)
        .send()
        .with_context(|| "Did not get a response for decoding key request")?
        .text()
        .with_context(|| {
            "Response to decoding key request is corrupted: could not turn into text"
        })?;

    // Check for error reported by OTR web service. The first if statement checks
    // if there was an error message at all.
    if response.len() < OTR_ERROR_INDICATOR.len() {
        return Err(anyhow!(
            "Unidentifiable error while requesting decoding key"
        ));
    }
    if &response[..OTR_ERROR_INDICATOR.len()] == OTR_ERROR_INDICATOR {
        return Err(anyhow!(
            "Error while requesting decoding key: \"{}\"",
            response[OTR_ERROR_INDICATOR.len()..].to_string()
        ));
    }

    // Decode response from base64 format
    let mut response = general_purpose::STANDARD
        .decode(&response)
        .with_context(|| "Could not decode response to decoding key request from base64")?;

    // Check response length
    if response.len() < 2 * BLOCK_SIZE || response.len() % BLOCK_SIZE != 0 {
        return Err(anyhow!(
            "Response to decoding key request is corrupted: must be a multiple of {}",
            BLOCK_SIZE
        ));
    }

    // Decode response
    let init_vector = &response[..BLOCK_SIZE];
    let response_decrypted = Cbc::<BlowfishLE, NoPadding>::new_from_slices(
        &hex::decode(cbc_key).with_context(|| "Could not turn CBC key into byte array")?,
        init_vector,
    )
    .with_context(|| "Could not create cipher object for decryption of decoding key response")?
    .decrypt(&mut response[BLOCK_SIZE..])
    .with_context(|| "Could not decrypt decryption key response")?;

    // Extract parameters into hash map
    let decoding_params = params_from_str(
        str::from_utf8(response_decrypted)
            .with_context(|| "Reponse to decoding key request is corrupt")?,
        vec![PARAM_DECODING_KEY],
    )
    .with_context(|| "Could not extract decoding parameters")?;

    Ok(decoding_params)
}

/// Assemble the URL for requesting the decoding key via the OTR web service.
fn decoding_params_request(
    cbc_key: &str,
    header: &OTRParams,
    user: &str,
    password: &str,
    now: &str,
) -> anyhow::Result<String> {
    // Assemble payload
    let mut payload: String = "&A=".to_string()
        + user
        + "&P="
        + password
        + "&FN="
        + header.get(PARAM_FILENAME).unwrap()
        + "&OH="
        + header.get(PARAM_ENCODED_HASH).unwrap()
        + "&M="
        + &format!("{:02x}", Md5::digest(b"something"))
        + "&OS="
        + &format!("{:02x}", Md5::digest(b"Windows"))
        + "&LN=DE"
        + "&VN="
        + DECODER_VERSION
        + "&IR=TRUE"
        + "&IK="
        + IK
        + "&D=";
    payload += &random_hex_string(512 - BLOCK_SIZE - payload.len());

    debug!("Payload for decoding parameters request:\n{}", payload);

    // Encrypt payload
    let init_vector = random_byte_vector(BLOCK_SIZE);
    let payload_as_bytes = unsafe { payload.as_bytes_mut() };
    let payload_encrypted = Cbc::<BlowfishLE, NoPadding>::new_from_slices(
        &hex::decode(cbc_key).with_context(|| "Could not turn CBC key into byte array")?,
        &init_vector,
    )
    .with_context(|| {
        "Could not create cipher object for encryption of decryption key request payload"
    })?
    .encrypt(payload_as_bytes, 512 - BLOCK_SIZE)
    .with_context(|| "Could not encrypt decryption key request payload")?;

    // Assemble value for code parameter
    let mut code = init_vector;
    code.extend_from_slice(payload_encrypted);

    // Finally assemble URL
    let request: String = OTR_URL.to_string()
        + "?code="
        + &general_purpose::STANDARD.encode(code)
        + "&AA="
        + user
        + "&ZZ="
        + now;

    Ok(request)
}

/// Extract the parameter SZ (= file size) from the header parameter hash map
/// and return it as unsigned integer
fn file_size_from_params(header_params: &OTRParams) -> usize {
    header_params
        .get(PARAM_FILESIZE)
        .unwrap()
        .parse::<usize>()
        .unwrap()
}

/// Calculate the MD5 checksum of video file (in this case the data is received
/// via a queue)
fn hashing_queue(queue: Receiver<Chunk>) -> [u8; 16] {
    let mut hasher = Md5::new();

    for data in queue {
        hasher.update(data);
    }

    // Retrieve and return checksum
    let mut checksum = [0u8; 16];
    checksum.clone_from_slice(&hasher.finalize()[..]);
    checksum
}

/// Extract parameters from the beginning of the OTRKEY file and return them in
/// a hash map: key -> value.
fn header_params(in_file: &mut File) -> anyhow::Result<OTRParams> {
    let mut buffer = [0; HEADER_LENGTH];

    // Read file header
    if in_file
        .read(&mut buffer)
        .with_context(|| "Could not read file")?
        < HEADER_LENGTH
    {
        return Err(anyhow!("File is too short"));
    }

    // Check if file header starts with OTRKEY indicator
    if str::from_utf8(&buffer[0..FILETYPE_LENGTH])? != OTRKEY_FILETYPE {
        debug!(
            "OTRKEY file header is: \"{}\"",
            str::from_utf8(&buffer[0..FILETYPE_LENGTH]).unwrap()
        );

        return Err(anyhow!("File does not start with \"{}\"", OTRKEY_FILETYPE));
    }

    // Create Blowfish little endian cypher and decrypt rest of file header
    Ecb::<BlowfishLE, NoPadding>::new_from_slices(
        &hex::decode(PREAMBLE_KEY).with_context(|| "Could not decrypt preamble key")?,
        &hex::decode("").unwrap(),
    )
    .with_context(|| "Could not create cipher object for header decryption")?
    .decrypt(&mut buffer[FILETYPE_LENGTH..])
    .with_context(|| "Could not decode file header")?;

    // Extract parameters
    let header_params = params_from_str(
        str::from_utf8(&buffer[FILETYPE_LENGTH..])
            .with_context(|| "Decrypted file header is corrupt")?,
        vec![
            PARAM_FILENAME,
            PARAM_FILESIZE,
            PARAM_ENCODED_HASH,
            PARAM_DECODED_HASH,
        ],
    )
    .with_context(|| "Could not extract parameters from file header")?;

    Ok(header_params)
}

/// Extract parameters from a string of the "key1=value1&key2=value2&..." into
/// a hash map: key -> value. must_have is a list of keys that must be present.
/// If any of these keys is missing, an error is returned
fn params_from_str(params_str: &str, must_have: Vec<&str>) -> anyhow::Result<OTRParams> {
    let mut params: OTRParams = HashMap::new();

    for param in params_str.split('&') {
        if param.is_empty() {
            continue;
        }
        // Split in key / value and add parameter to map
        let a: Vec<&str> = param.split('=').collect();
        params.insert(a[0].to_string(), a[1].to_string());
    }

    // Print params content for debugging purposes
    if log::max_level() >= log::LevelFilter::Debug {
        debug!("OTRKEY file parameters:");
        for (key, value) in &params {
            debug!("{} => {}", key, value)
        }
    }

    // Check if all parameters are there
    for key in must_have {
        if !params.contains_key(key) {
            return Err(anyhow!("Parameter \"{}\" could not be extracted", key));
        }
    }

    Ok(params)
}

/// Assemble a random byte vector of length len
fn random_byte_vector(len: usize) -> Vec<u8> {
    let mut bytes = Vec::<u8>::new();
    for _ in 0..len {
        bytes.push(rand::random::<u8>());
    }
    bytes
}

/// Assemble a random hexadecimal string of length len
fn random_hex_string(len: usize) -> String {
    random_string::generate(len, "0123456789abcdef")
}

/// Check if checksum fits to hash. The hash must be a 48 character hex string.
fn verify_checksum(checksum: &[u8], hash: &str) -> anyhow::Result<bool> {
    if hash.len() != 48 {
        return Err(anyhow!("MD5 hash must be 48 characters long"));
    }

    // Reduce hash length to 32 characters and convert it into bytes array
    let reduced_hash = hex::decode(
        hash.chars()
            .enumerate()
            .filter_map(|(i, c)| if (i + 1) % 3 != 0 { Some(c) } else { None })
            .collect::<String>(),
    )
    .context("Could not turn hash {} into bytes")?;

    Ok(checksum == reduced_hash)
}