decryptune 1.1.3__tar.gz → 1.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. {decryptune-1.1.3 → decryptune-1.1.4}/Cargo.lock +5 -5
  2. {decryptune-1.1.3 → decryptune-1.1.4}/Cargo.toml +1 -1
  3. {decryptune-1.1.3 → decryptune-1.1.4}/PKG-INFO +1 -1
  4. {decryptune-1.1.3 → decryptune-1.1.4}/python/decryptune/__init__.py +1 -1
  5. {decryptune-1.1.3 → decryptune-1.1.4}/src/jpeg/decode.rs +6 -1
  6. {decryptune-1.1.3 → decryptune-1.1.4}/src/jpeg/tests.rs +9 -0
  7. {decryptune-1.1.3 → decryptune-1.1.4}/src/lib.rs +53 -22
  8. {decryptune-1.1.3 → decryptune-1.1.4}/tests/test_decryptune.py +17 -5
  9. {decryptune-1.1.3 → decryptune-1.1.4}/.gitattributes +0 -0
  10. {decryptune-1.1.3 → decryptune-1.1.4}/.github/workflows/build.yml +0 -0
  11. {decryptune-1.1.3 → decryptune-1.1.4}/.gitignore +0 -0
  12. {decryptune-1.1.3 → decryptune-1.1.4}/LICENSE +0 -0
  13. {decryptune-1.1.3 → decryptune-1.1.4}/README.md +0 -0
  14. {decryptune-1.1.3 → decryptune-1.1.4}/pyproject.toml +0 -0
  15. {decryptune-1.1.3 → decryptune-1.1.4}/src/boxes.rs +0 -0
  16. {decryptune-1.1.3 → decryptune-1.1.4}/src/cover.rs +0 -0
  17. {decryptune-1.1.3 → decryptune-1.1.4}/src/error.rs +0 -0
  18. {decryptune-1.1.3 → decryptune-1.1.4}/src/input.rs +0 -0
  19. {decryptune-1.1.3 → decryptune-1.1.4}/src/jpeg/encode.rs +0 -0
  20. {decryptune-1.1.3 → decryptune-1.1.4}/src/jpeg/mod.rs +0 -0
  21. {decryptune-1.1.3 → decryptune-1.1.4}/src/meta.rs +0 -0
  22. {decryptune-1.1.3 → decryptune-1.1.4}/src/process.rs +0 -0
  23. {decryptune-1.1.3 → decryptune-1.1.4}/tests/fixtures/big.jpg +0 -0
  24. {decryptune-1.1.3 → decryptune-1.1.4}/tests/fixtures/tiny.jpg +0 -0
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.3"
71
+ version = "1.1.4"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -139,9 +139,9 @@ dependencies = [
139
139
 
140
140
  [[package]]
141
141
  name = "inout"
142
- version = "0.2.4"
142
+ version = "0.2.5"
143
143
  source = "registry+https://github.com/rust-lang/crates.io-index"
144
- checksum = "3ce983bb6fb399067d101fbfc9e74174e07e9f29a2bc679efefeb8c645819c3f"
144
+ checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
145
145
  dependencies = [
146
146
  "hybrid-array",
147
147
  ]
@@ -295,9 +295,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
295
295
 
296
296
  [[package]]
297
297
  name = "tokio"
298
- version = "1.53.3"
298
+ version = "1.54.0"
299
299
  source = "registry+https://github.com/rust-lang/crates.io-index"
300
- checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
300
+ checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc"
301
301
  dependencies = [
302
302
  "pin-project-lite",
303
303
  ]
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.3"
3
+ version = "1.1.4"
4
4
  edition = "2021"
5
5
  rust-version = "1.85"
6
6
  description = "Fast native M4A/fMP4 CENC decryptor, MP4 sanitizer and iTunes tagger, sync & async Python"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: decryptune
3
- Version: 1.1.3
3
+ Version: 1.1.4
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Rust
@@ -29,7 +29,7 @@ except ImportError:
29
29
  _native = importlib.util.module_from_spec(importlib.util.spec_from_loader("decryptune", _loader))
30
30
  _loader.exec_module(_native)
31
31
 
32
- __version__ = "1.1.3"
32
+ __version__ = "1.1.4"
33
33
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
34
34
 
35
35
 
@@ -5,6 +5,11 @@
5
5
  use super::ZIGZAG;
6
6
  use crate::Err;
7
7
 
8
+ // hostile SOF dimensions can demand multi-GB coefficient buffers before any
9
+ // entropy byte is read — no real cover comes close (a 150MP medium-format
10
+ // shot sits 2x under this); anything above is a decompression bomb
11
+ const MAX_PIXELS: usize = 268_435_456; // 256 megapixels
12
+
8
13
  struct HuffTable {
9
14
  counts : [u8; 17], // symbols per code length 1..=16
10
15
  first_code: [u16; 17],
@@ -310,7 +315,7 @@ pub(crate) fn decode(raw: &[u8]) -> Result<(usize, usize, usize, Vec<u8>), Err>
310
315
  h = u16::from_be_bytes([raw[pos + 3], raw[pos + 4]]) as usize;
311
316
  w = u16::from_be_bytes([raw[pos + 5], raw[pos + 6]]) as usize;
312
317
  let nc: usize = raw[pos + 7] as usize;
313
- if w == 0 || h == 0 || (nc != 1 && nc != 3) || seg != 8 + nc * 3 { return Err(Err::BadCover); }
318
+ if w == 0 || h == 0 || w * h > MAX_PIXELS || (nc != 1 && nc != 3) || seg != 8 + nc * 3 { return Err(Err::BadCover); }
314
319
  comps.clear();
315
320
  for c in 0..nc {
316
321
  let b: usize = pos + 8 + c * 3;
@@ -116,6 +116,15 @@ fn encode_edge_blocks() {
116
116
  assert_eq!((dw, dh, dch), (w, h, 3));
117
117
  }
118
118
 
119
+ #[test]
120
+ fn hostile_huge_sof_rejected() {
121
+ // a 65535x65535 SOF claim must fail validation before any buffer is
122
+ // allocated — without the pixel cap this tries to reserve ~8GB
123
+ let sof: [u8; 11] = [0, 11, 8, 0xFF, 0xFF, 0xFF, 0xFF, 1, 1, 0x11, 0];
124
+ let jpg: Vec<u8> = [&[0xFF, 0xD8, 0xFF, 0xC0][..], &sof, &[0xFF, 0xD9][..]].concat();
125
+ assert!(decode(&jpg).is_err());
126
+ }
127
+
119
128
  // DUMP_ENC=1 + JPEG_FIXTURES: write our encode of the p444 reference so the
120
129
  // local Pillow PSNR checker can score it against the same pristine source
121
130
  #[test]
@@ -10,6 +10,7 @@ use pyo3::exceptions::PyException;
10
10
  use pyo3::prelude::*;
11
11
  use pyo3::types::PyBytes;
12
12
 
13
+ use std::io::Write;
13
14
  use std::sync::atomic::{AtomicU64, Ordering};
14
15
 
15
16
  use error::Err;
@@ -43,21 +44,24 @@ fn tmp_path(out_path: &str) -> String {
43
44
  format!("{}.{}.{}.tmp", out_path, std::process::id(), N.fetch_add(1, Ordering::Relaxed))
44
45
  }
45
46
 
46
- // write to <out>.<n>.tmp then rename — no partial outputs on crash;
47
- // a failed rename removes the tmp file (no litter in the output directory)
47
+ // write to <out>.<n>.tmp then rename — no partial outputs on crash.
48
+ // create_new (O_CREAT|O_EXCL) refuses a symlink pre-placed at the predictable
49
+ // tmp name and fails on collision instead of clobbering an existing file
48
50
  fn write_atomic(out_path: &str, data: &[u8]) -> Result<(), Err> {
49
51
  let tmp: String = tmp_path(out_path);
50
- std::fs::write(&tmp, data).map_err(|_| Err::WriteFailed)?;
51
- if std::fs::rename(&tmp, out_path).is_err() {
52
+ let mut file: std::fs::File = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)
53
+ .map_err(|_| Err::WriteFailed)?;
54
+ if file.write_all(data).is_err() || std::fs::rename(&tmp, out_path).is_err() {
52
55
  let _ = std::fs::remove_file(&tmp);
53
56
  return Err(Err::WriteFailed);
54
57
  }
55
58
  Ok(())
56
59
  }
57
60
 
58
- // strict evidence check, shared by the sync and async tails
59
- fn check_strict(fragments: &[process::FragmentStat], key: Option<[u8; 16]>, strict: bool) -> PyResult<()> {
60
- if strict && key.is_some() {
61
+ // strict evidence check, shared by the sync and async tails; `guarded` is
62
+ // precomputed (strict && key given) because the key copy dies in its worker
63
+ fn check_strict(fragments: &[process::FragmentStat], guarded: bool) -> PyResult<()> {
64
+ if guarded {
61
65
  let bad_frags: Vec<String> = fragments.iter()
62
66
  .filter(|f| f.corrupt == Some(true))
63
67
  .map(|f| format!("#{} chi2={:.0} ({}B)", f.index, f.chi2, f.bytes))
@@ -72,13 +76,22 @@ fn check_strict(fragments: &[process::FragmentStat], key: Option<[u8; 16]>, stri
72
76
  Ok(())
73
77
  }
74
78
 
79
+ // best-effort key hygiene: volatile writes defeat dead-store elimination so
80
+ // the worker's AES key copy is cleared instead of lingering in freed memory
81
+ fn wipe_key(key: &mut Option<[u8; 16]>) {
82
+ if let Some(k) = key.as_mut() {
83
+ for b in k.iter_mut() { unsafe { std::ptr::write_volatile(b, 0u8); } }
84
+ }
85
+ }
86
+
75
87
  // pass 1, shared by proc/aproc: load input, guard kid, measure the exact
76
88
  // output length — all off the GIL; the loaded data and the metadata must
77
- // survive to pass 2, so the metadata comes back out
78
- fn load_and_measure(input: input::Input, key: Option<[u8; 16]>, kid: Option<String>, meta: Option<meta::CoreMeta>)
89
+ // survive to pass 2, so the metadata comes back out. Only `has_key` crosses
90
+ // here — the key itself never needs to reach the measure phase
91
+ fn load_and_measure(input: input::Input, has_key: bool, kid: Option<String>, meta: Option<meta::CoreMeta>)
79
92
  -> Result<(InputData, usize, Option<meta::CoreMeta>), Err> {
80
93
  let d: InputData = input.load()?;
81
- if key.is_some() { guard_kid(d.bytes(), kid.as_deref())?; }
94
+ if has_key { guard_kid(d.bytes(), kid.as_deref())?; }
82
95
  let mut meta = meta;
83
96
  if let Some(m) = meta.as_mut() { meta::pre_resolve_cover(m)?; } // cover codec work once
84
97
  let len: usize = process::measure(d.bytes(), meta.as_ref())?;
@@ -220,15 +233,18 @@ fn proc<'py>(
220
233
  ) -> PyResult<Option<Bound<'py, PyAny>>> {
221
234
  let Args { input, output, key, kid, core_meta }: Args = parse_args(py, input, out, key, kid, meta)?;
222
235
  let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) =
223
- py.detach(move || load_and_measure(input, key, kid, core_meta)).map_err(PyErr::from)?;
236
+ py.detach(move || load_and_measure(input, key.is_some(), kid, core_meta)).map_err(PyErr::from)?;
237
+ let guarded: bool = strict && key.is_some();
224
238
 
225
239
  match output {
226
240
  Output::Path(p) => {
227
241
  py.detach(move || -> PyResult<()> {
242
+ let mut key: Option<[u8; 16]> = key;
228
243
  let mut buf: Vec<u8> = vec![0u8; len]; // exact-size output, no over-allocation
229
244
  let fragments: Vec<process::FragmentStat> =
230
245
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
231
- check_strict(&fragments, key, strict)?;
246
+ wipe_key(&mut key);
247
+ check_strict(&fragments, guarded)?;
232
248
  write_atomic(&p, &buf)?;
233
249
  Ok(())
234
250
  })?;
@@ -243,10 +259,14 @@ fn proc<'py>(
243
259
  // pointer would break Send (disjoint capture hoists it out)
244
260
  let base: usize = bytes.as_bytes().as_ptr() as usize;
245
261
  let fragments: Vec<process::FragmentStat> = py.detach(move || -> PyResult<Vec<process::FragmentStat>> {
262
+ let mut key: Option<[u8; 16]> = key;
246
263
  let buf: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, len) };
247
- Ok(process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?)
264
+ let fragments: Vec<process::FragmentStat> =
265
+ process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?;
266
+ wipe_key(&mut key);
267
+ Ok(fragments)
248
268
  })?;
249
- check_strict(&fragments, key, strict)?;
269
+ check_strict(&fragments, guarded)?;
250
270
  Ok(Some(bytes.into_any()))
251
271
  }
252
272
  }
@@ -274,20 +294,23 @@ fn aproc<'py>(
274
294
  strict : bool
275
295
  ) -> PyResult<Bound<'py, PyAny>> {
276
296
  let Args { input, output, key, kid, core_meta }: Args = parse_args(py, input, out, key, kid, meta)?;
297
+ let guarded: bool = strict && key.is_some();
277
298
 
278
299
  pyo3_async_runtimes::tokio::future_into_py(py, async move {
279
300
  let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) = tokio::task::spawn_blocking(
280
- move || load_and_measure(input, key, kid, core_meta),
301
+ move || load_and_measure(input, key.is_some(), kid, core_meta),
281
302
  ).await.map_err(join_err)??;
282
303
  match output {
283
304
  Output::Path(p) => {
284
305
  // write+rename run inside ONE blocking task with the build — a
285
306
  // cancelled future cannot split the pair and leave a tmp behind
286
307
  tokio::task::spawn_blocking(move || -> PyResult<()> {
308
+ let mut key: Option<[u8; 16]> = key;
287
309
  let mut buf: Vec<u8> = vec![0u8; len];
288
310
  let fragments: Vec<process::FragmentStat> =
289
311
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
290
- check_strict(&fragments, key, strict)?;
312
+ wipe_key(&mut key);
313
+ check_strict(&fragments, guarded)?;
291
314
  write_atomic(&p, &buf)?;
292
315
  Ok(())
293
316
  }).await.map_err(join_err)??;
@@ -295,16 +318,24 @@ fn aproc<'py>(
295
318
  }
296
319
  Output::Return => {
297
320
  // allocate the result under a brief GIL attach, then build off-GIL
298
- // straight into its buffer — no intermediate copy
321
+ // straight into its buffer — no intermediate copy. The PyBytes
322
+ // owner moves INTO the build task: a cancelled future drops its
323
+ // own references but the buffer stays referenced for the whole
324
+ // write (dropping it early would free the object under the writer)
299
325
  let (base, result): (usize, Py<PyBytes>) = Python::attach(|py| -> PyResult<(usize, Py<PyBytes>)> {
300
326
  let b: Bound<'_, PyBytes> = PyBytes::new_with(py, len, |_buf: &mut [u8]| Ok(()))?;
301
327
  Ok((b.as_bytes().as_ptr() as usize, b.unbind()))
302
328
  })?;
303
- let fragments: Vec<process::FragmentStat> = tokio::task::spawn_blocking(move || -> PyResult<Vec<process::FragmentStat>> {
304
- let buf: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, len) };
305
- Ok(process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?)
306
- }).await.map_err(join_err)??;
307
- check_strict(&fragments, key, strict)?;
329
+ let (fragments, result): (Vec<process::FragmentStat>, Py<PyBytes>) =
330
+ tokio::task::spawn_blocking(move || -> PyResult<(Vec<process::FragmentStat>, Py<PyBytes>)> {
331
+ let mut key: Option<[u8; 16]> = key;
332
+ let buf: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, len) };
333
+ let fragments: Vec<process::FragmentStat> =
334
+ process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?;
335
+ wipe_key(&mut key);
336
+ Ok((fragments, result))
337
+ }).await.map_err(join_err)??;
338
+ check_strict(&fragments, guarded)?;
308
339
  Ok(Some(result))
309
340
  }
310
341
  }
@@ -182,11 +182,6 @@ def build_sample_file():
182
182
  moof3 = make_moof(3, [make_tfhd(sizes[0]), make_trun(sizes, 0, with_sizes=False),
183
183
  make_senc(ivs)])
184
184
 
185
- # trun data_offset: first byte of sample data relative to moof start
186
- def set_offset(moof, off):
187
- i = moof.find(b"trun") # position of the type string
188
- return moof[:i + 12] + i32(off) + moof[i + 16:]
189
-
190
185
  moof1 = set_offset(moof1, len(moof1) + 8)
191
186
  moof2 = set_offset(moof2, len(moof2) + 8)
192
187
  moof3 = set_offset(moof3, len(moof3) + 8)
@@ -601,6 +596,23 @@ def test_aproc_cancel_no_tmp_litter(sp, src_file, tmp_path):
601
596
  assert list(tmp_path.glob("*.tmp")) == []
602
597
 
603
598
 
599
+ def test_aproc_cancel_return(sp, sample):
600
+ # cancelling bytes-return aprocs mid-flight must be memory-safe — the
601
+ # result owner moves into the build task, so a dropped future can never
602
+ # free the output buffer under the writer's feet (use-after-free regression)
603
+ data, _ = sample
604
+
605
+ async def main():
606
+ for _ in range(8):
607
+ tasks = [asyncio.create_task(sp.aproc(input=data, key=KEY_HEX)) for _ in range(16)]
608
+ await asyncio.sleep(0.001)
609
+ for t in tasks:
610
+ t.cancel()
611
+ await asyncio.gather(*tasks, return_exceptions=True)
612
+
613
+ asyncio.run(main())
614
+
615
+
604
616
  # ---- metadata ---------------------------------------------------------------
605
617
 
606
618
  def test_udta_first(sp, tagged):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes