decryptune 1.1.7__tar.gz → 1.1.8__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 (26) hide show
  1. {decryptune-1.1.7 → decryptune-1.1.8}/Cargo.lock +1 -1
  2. {decryptune-1.1.7 → decryptune-1.1.8}/Cargo.toml +1 -1
  3. {decryptune-1.1.7 → decryptune-1.1.8}/PKG-INFO +1 -1
  4. {decryptune-1.1.7 → decryptune-1.1.8}/python/decryptune/__init__.py +2 -2
  5. {decryptune-1.1.7 → decryptune-1.1.8}/src/defrag.rs +30 -14
  6. {decryptune-1.1.7 → decryptune-1.1.8}/src/lib.rs +4 -4
  7. {decryptune-1.1.7 → decryptune-1.1.8}/src/process.rs +1 -1
  8. {decryptune-1.1.7 → decryptune-1.1.8}/tests/test_decryptune.py +105 -3
  9. {decryptune-1.1.7 → decryptune-1.1.8}/.gitattributes +0 -0
  10. {decryptune-1.1.7 → decryptune-1.1.8}/.github/workflows/build.yml +0 -0
  11. {decryptune-1.1.7 → decryptune-1.1.8}/.gitignore +0 -0
  12. {decryptune-1.1.7 → decryptune-1.1.8}/LICENSE +0 -0
  13. {decryptune-1.1.7 → decryptune-1.1.8}/README.md +0 -0
  14. {decryptune-1.1.7 → decryptune-1.1.8}/pyproject.toml +0 -0
  15. {decryptune-1.1.7 → decryptune-1.1.8}/src/boxes.rs +0 -0
  16. {decryptune-1.1.7 → decryptune-1.1.8}/src/cover.rs +0 -0
  17. {decryptune-1.1.7 → decryptune-1.1.8}/src/error.rs +0 -0
  18. {decryptune-1.1.7 → decryptune-1.1.8}/src/input.rs +0 -0
  19. {decryptune-1.1.7 → decryptune-1.1.8}/src/jpeg/decode.rs +0 -0
  20. {decryptune-1.1.7 → decryptune-1.1.8}/src/jpeg/encode.rs +0 -0
  21. {decryptune-1.1.7 → decryptune-1.1.8}/src/jpeg/mod.rs +0 -0
  22. {decryptune-1.1.7 → decryptune-1.1.8}/src/jpeg/tests.rs +0 -0
  23. {decryptune-1.1.7 → decryptune-1.1.8}/src/meta.rs +0 -0
  24. {decryptune-1.1.7 → decryptune-1.1.8}/tests/fixtures/big.jpg +0 -0
  25. {decryptune-1.1.7 → decryptune-1.1.8}/tests/fixtures/odd420.jpg +0 -0
  26. {decryptune-1.1.7 → decryptune-1.1.8}/tests/fixtures/tiny.jpg +0 -0
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.7"
71
+ version = "1.1.8"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.7"
3
+ version = "1.1.8"
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.7
3
+ Version: 1.1.8
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Rust
@@ -39,7 +39,7 @@ except ImportError as _imp_err:
39
39
  raise ImportError(f"staged extension {_lib} failed to load: {_load_err}") from _load_err
40
40
  sys.modules[f"{__name__}.decryptune"] = _native # register like a real submodule import
41
41
 
42
- __version__ = "1.1.7"
42
+ __version__ = "1.1.8"
43
43
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
44
44
 
45
45
 
@@ -63,7 +63,7 @@ class DecrypTuneError(Exception):
63
63
  # all error messages are authored by the native core (error.rs) — this wrapper
64
64
  # relays [code] + message; anything outside the known code range (or without a
65
65
  # [N] prefix) is not a native error and propagates unchanged
66
- _NATIVE_CODES: frozenset[int] = frozenset(range(1, 15)) # 14 = CoverTooLarge is the last
66
+ _NATIVE_CODES: frozenset[int] = frozenset(range(1, 16)) # 15 = ClassicUnsupported is the last (error.rs)
67
67
 
68
68
 
69
69
  def _to_err(exc: Exception) -> DecrypTuneError | None:
@@ -8,7 +8,7 @@
8
8
  // checked against the 32-bit chunk-offset limit before anything is written.
9
9
 
10
10
  use crate::boxes::{header_len, parse, write_header, Box, MAX_BOXES};
11
- use crate::process::trex_defaults;
11
+ use crate::process::{trex_defaults, MAX_TREE_DEPTH};
12
12
  use crate::Err;
13
13
 
14
14
  // containers the moov rebuild recurses into (mvex is dropped outright)
@@ -133,8 +133,11 @@ fn make_tables(chunks: &[ChunkRun], offsets: &[u32], durations: &[u32], sizes: &
133
133
  }
134
134
 
135
135
  // recursive moov rebuild — the only structural change is that mvex vanishes
136
- // and the sample tables inside stbl are appended fresh
137
- fn rebuild(data: &[u8], start: usize, end: usize, tables: &Tables, movie_duration: u64, media_duration: u64) -> Result<Vec<u8>, Err> {
136
+ // and the sample tables inside stbl are appended fresh. Hostile container
137
+ // nesting is depth-capped like the decrypt path's rebuild_container: without
138
+ // the cap, nested boxes recurse to a stack overflow (uncatchable)
139
+ fn rebuild(data: &[u8], start: usize, end: usize, tables: &Tables, movie_duration: u64, media_duration: u64, depth: usize) -> Result<Vec<u8>, Err> {
140
+ if depth > MAX_TREE_DEPTH { return Err(Err::ClassicUnsupported); }
138
141
  let children: Vec<Box> = parse(data, start, end);
139
142
  if children.len() >= MAX_BOXES { return Err(Err::ClassicUnsupported); }
140
143
  let mut out: Vec<u8> = Vec::new();
@@ -162,7 +165,7 @@ fn rebuild(data: &[u8], start: usize, end: usize, tables: &Tables, movie_duratio
162
165
  out.extend_from_slice(&body);
163
166
  }
164
167
  b"stbl" => {
165
- let mut inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration)?;
168
+ let mut inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration, depth + 1)?;
166
169
  // the Tables fields hold box BODIES — wrap each in its header
167
170
  write_header(&mut inner, b"stts", tables.stts.len());
168
171
  inner.extend_from_slice(&tables.stts);
@@ -176,7 +179,7 @@ fn rebuild(data: &[u8], start: usize, end: usize, tables: &Tables, movie_duratio
176
179
  out.extend_from_slice(&inner);
177
180
  }
178
181
  typ if CONTAINERS.iter().any(|c| c == &typ) => {
179
- let inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration)?;
182
+ let inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration, depth + 1)?;
180
183
  write_header(&mut out, typ, inner.len());
181
184
  out.extend_from_slice(&inner);
182
185
  }
@@ -186,13 +189,16 @@ fn rebuild(data: &[u8], start: usize, end: usize, tables: &Tables, movie_duratio
186
189
  Ok(out)
187
190
  }
188
191
 
189
- /// Rewrite fragmented MP4 bytes as a classic MP4. A file without moof boxes
190
- /// is already classic and returns unchanged.
191
- pub(crate) fn defragment(data: &[u8]) -> Result<Vec<u8>, Err> {
192
+ /// Rewrite fragmented MP4 bytes as a classic MP4. `None` means the input has
193
+ /// no moof boxes — already classic — and no rewrite buffer is needed.
194
+ pub(crate) fn defragment(data: &[u8]) -> Result<Option<Vec<u8>>, Err> {
192
195
  let top: Vec<Box> = parse(data, 0, data.len());
193
196
  if top.is_empty() || top.len() >= MAX_BOXES { return Err(Err::ClassicUnsupported); }
194
- if !top.iter().any(|b| b.is(b"moof")) { return Ok(data.to_vec()); }
197
+ if !top.iter().any(|b| b.is(b"moof")) { return Ok(None); }
195
198
  let moov: &Box = top.iter().find(|b| b.is(b"moov")).ok_or(Err::ClassicUnsupported)?;
199
+ if top.iter().filter(|b| b.is(b"moov")).count() != 1 {
200
+ return Err(Err::ClassicUnsupported); // duplicate moovs would corrupt the offset math
201
+ }
196
202
  let children: Vec<Box> = parse(data, moov.content_start, moov.end);
197
203
  if children.len() >= MAX_BOXES || children.iter().filter(|b| b.is(b"trak")).count() != 1 {
198
204
  return Err(Err::ClassicUnsupported);
@@ -215,13 +221,15 @@ pub(crate) fn defragment(data: &[u8]) -> Result<Vec<u8>, Err> {
215
221
  let mut chunks: Vec<ChunkRun> = Vec::new();
216
222
  for moof in top.iter().filter(|b| b.is(b"moof")) {
217
223
  let moof_children: Vec<Box> = parse(data, moof.content_start, moof.end);
224
+ // a trun without data_offset continues the PREVIOUS run's data, chaining
225
+ // across trafs of the same moof — so `next` lives at the moof level
226
+ let mut next: Option<usize> = None;
218
227
  for traf in &moof_children {
219
228
  if !traf.is(b"traf") { continue; }
220
229
  let subs: Vec<Box> = parse(data, traf.content_start, traf.end);
221
230
  let mut base: usize = moof.start;
222
231
  let mut dur: u32 = trex.map(|(d, _)| d).unwrap_or(0);
223
232
  let mut size: u32 = trex.map(|(_, s)| s).unwrap_or(0);
224
- let mut next: Option<usize> = None;
225
233
  for sub in &subs {
226
234
  match &sub.typ {
227
235
  b"tfhd" => {
@@ -284,19 +292,27 @@ pub(crate) fn defragment(data: &[u8]) -> Result<Vec<u8>, Err> {
284
292
  if sizes.is_empty() { return Err(Err::ClassicUnsupported); }
285
293
  let media_duration: u64 = durations.iter().map(|d| u64::from(*d)).sum();
286
294
  if media_duration == 0 { return Err(Err::ClassicUnsupported); }
287
- let movie_duration: u64 = media_duration * u64::from(movie_ts) / u64::from(media_ts);
295
+ // hostile timescales/durations can overflow the u64 product — the u128
296
+ // intermediate keeps it exact (the result itself always fits: it is at
297
+ // most media_duration, which came out of a u64 sum)
298
+ let movie_duration: u64 =
299
+ ((media_duration as u128 * u128::from(movie_ts)) / u128::from(media_ts)) as u64;
288
300
 
289
301
  // moov's size does not depend on the offset VALUES — size it with dummy
290
302
  // offsets first, then place the data and rebuild with the real ones
291
303
  let zeros: Vec<u32> = vec![0u32; chunks.len()];
292
304
  let dummy: Tables = make_tables(&chunks, &zeros, &durations, &sizes);
293
- let placeholder: Vec<u8> = rebuild(data, moov.content_start, moov.end, &dummy, movie_duration, media_duration)?;
305
+ let placeholder: Vec<u8> = rebuild(data, moov.content_start, moov.end, &dummy, movie_duration, media_duration, 0)?;
294
306
  let others_len: usize = top.iter()
295
307
  .filter(|b| !matches!(&b.typ, b"moof" | b"mdat" | b"sidx" | b"moov"))
296
308
  .map(|b| b.end - b.start)
297
309
  .sum();
298
310
  let data_start: usize = others_len + header_len(placeholder.len()) + placeholder.len() + 8; // moov box + mdat header
299
311
  let total_audio: usize = chunks.iter().map(|c| c.len).sum();
312
+ // legit sample bytes are a subset of the input (disjoint runs), so the
313
+ // total can never exceed it — overlapping runs are malformed, and the cap
314
+ // also bounds the output allocation against hostile amplification
315
+ if total_audio > data.len() { return Err(Err::ClassicUnsupported); }
300
316
  if data_start + total_audio > u32::MAX as usize {
301
317
  return Err(Err::ClassicUnsupported); // stco holds u32 offsets only (audio never gets there)
302
318
  }
@@ -307,7 +323,7 @@ pub(crate) fn defragment(data: &[u8]) -> Result<Vec<u8>, Err> {
307
323
  pos += c.len;
308
324
  }
309
325
  let tables: Tables = make_tables(&chunks, &offsets, &durations, &sizes);
310
- let new_moov: Vec<u8> = rebuild(data, moov.content_start, moov.end, &tables, movie_duration, media_duration)?;
326
+ let new_moov: Vec<u8> = rebuild(data, moov.content_start, moov.end, &tables, movie_duration, media_duration, 0)?;
311
327
  if new_moov.len() != placeholder.len() { return Err(Err::ClassicUnsupported); } // cannot happen — table sizes are value-independent
312
328
 
313
329
  // unknown top-level boxes (free, top-level meta…) are kept verbatim;
@@ -327,5 +343,5 @@ pub(crate) fn defragment(data: &[u8]) -> Result<Vec<u8>, Err> {
327
343
  for c in &chunks {
328
344
  out.extend_from_slice(&data[c.offset..c.offset + c.len]);
329
345
  }
330
- Ok(out)
346
+ Ok(Some(out))
331
347
  }
@@ -278,7 +278,7 @@ fn proc<'py>(
278
278
  wipe_key(&mut key);
279
279
  check_strict(&fragments, guarded)?;
280
280
  if classic {
281
- buf = defrag::defragment(&buf)?;
281
+ buf = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
282
282
  }
283
283
  write_atomic(&p, &buf)?;
284
284
  Ok(())
@@ -295,7 +295,7 @@ fn proc<'py>(
295
295
  let fragments: Vec<process::FragmentStat> =
296
296
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
297
297
  wipe_key(&mut key);
298
- let classic_buf: Vec<u8> = defrag::defragment(&buf)?;
298
+ let classic_buf: Vec<u8> = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
299
299
  Ok((classic_buf, fragments))
300
300
  },
301
301
  )?;
@@ -367,7 +367,7 @@ fn aproc<'py>(
367
367
  wipe_key(&mut key);
368
368
  check_strict(&fragments, guarded)?;
369
369
  if classic {
370
- buf = defrag::defragment(&buf)?;
370
+ buf = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
371
371
  }
372
372
  write_atomic(&p, &buf)?;
373
373
  Ok(())
@@ -384,7 +384,7 @@ fn aproc<'py>(
384
384
  let fragments: Vec<process::FragmentStat> =
385
385
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
386
386
  wipe_key(&mut key);
387
- let classic_buf: Vec<u8> = defrag::defragment(&buf)?;
387
+ let classic_buf: Vec<u8> = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
388
388
  Ok((classic_buf, fragments))
389
389
  },
390
390
  ).await.map_err(join_err)??;
@@ -10,7 +10,7 @@ use crate::Err;
10
10
  type Aes128Ctr = ctr::Ctr128BE<Aes128>;
11
11
 
12
12
  const CONTAINERS: &[&[u8; 4]] = &[b"moov", b"trak", b"mdia", b"minf", b"stbl"];
13
- const MAX_TREE_DEPTH: usize = 16;
13
+ pub(crate) const MAX_TREE_DEPTH: usize = 16;
14
14
  // chi2 thresholds calibrated on real AAC tracks (structured ~3800..14000 at
15
15
  // 16KB, ~950+ at 4KB; noise is df-bound at ~210..340 for any size above ~1KB,
16
16
  // so 500 splits clean from corrupt with margin on both sides down to 4KB)
@@ -58,9 +58,11 @@ def make_senc(ivs):
58
58
  return full_box(b"senc", 0, 0, body)
59
59
 
60
60
 
61
- def make_trun(sizes, data_offset, with_sizes=True, durations=None):
62
- flags = 0x1 | (0x200 if with_sizes else 0) | (0x100 if durations else 0)
63
- body = u32(len(sizes)) + i32(data_offset)
61
+ def make_trun(sizes, data_offset, with_sizes=True, durations=None, with_offset=True):
62
+ flags = (0x1 if with_offset else 0) | (0x200 if with_sizes else 0) | (0x100 if durations else 0)
63
+ body = u32(len(sizes))
64
+ if with_offset:
65
+ body += i32(data_offset)
64
66
  for i in range(len(sizes)):
65
67
  if durations:
66
68
  body += u32(durations[i])
@@ -437,6 +439,106 @@ def test_classic_aproc_parity(sp):
437
439
  assert out == sp.proc(input=data, key=KEY_HEX, classic=True)
438
440
 
439
441
 
442
+ def test_classic_moov_first(sp):
443
+ """The real-file layout: moov FIRST, then the fragments (moov-at-end was
444
+ the only shape the earlier tests covered — a typo in the fragment walk
445
+ silently produced empty sample tables there and only broke moov-first
446
+ files, i.e. every real track)."""
447
+ data, plain = build_classic_source()
448
+ ftyp = find(data, b"ftyp")[0]
449
+ moov = find(data, b"moov")[0]
450
+ moofs, mdats = find(data, b"moof"), find(data, b"mdat")
451
+ reordered = (data[ftyp[1]:ftyp[1] + ftyp[2]] + data[moov[1]:moov[1] + moov[2]] +
452
+ b"".join(data[m[1]:m[1] + m[2]] + data[d[1]:d[1] + d[2]] for m, d in zip(moofs, mdats)))
453
+ out = sp.proc(input=reordered, key=KEY_HEX, strict=True, classic=True)
454
+ mdat = find(out, b"mdat")[0]
455
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == b"".join(plain) * 2
456
+ moov2 = find(out, b"moov")[0]
457
+ stco = find_deep(out, moov2[1], moov2[1] + moov2[2], b"stco")
458
+ assert stco is not None
459
+ (count,) = struct.unpack_from(">I", out, stco[0] + 12)
460
+ assert count == 2
461
+
462
+
463
+ def test_error_classic_unsupported(sp):
464
+ """A fragmented layout the rewrite cannot express raises coded error 15 —
465
+ wrapped as DecrypTuneError like every other native code (the [N] relay
466
+ range must cover it)."""
467
+ size = 20000
468
+ moof = make_moof(1, [make_tfhd(), make_trun([size] * 2, 0)])
469
+ data = (box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") +
470
+ set_offset(moof, 99999999) + box(b"mdat", bytes(size * 2)) + make_moov()) # data outside the file
471
+ try:
472
+ sp.proc(input=data, classic=True)
473
+ raise AssertionError("classic rewrite accepted impossible offsets")
474
+ except DecrypTuneError as e:
475
+ assert e.code == 15, e
476
+
477
+
478
+ def test_classic_chained_trafs(sp):
479
+ """A trun without data_offset continues the previous run's data, chaining
480
+ across trafs of the same moof (ISO 14496-12) — the second traf here relies
481
+ on it. Without the moof-level chain this layout was refused with error 15."""
482
+ size, dur = 20000, 1024
483
+ blob = bytes([(0x33 + i) & 0xFF for i in range(size * 4)]) # 4 samples × 20000
484
+ traf1 = box(b"traf", make_tfhd(default_duration=dur) +
485
+ make_trun([size] * 2, 0, durations=[dur] * 2)) # offset patched below
486
+ traf2 = box(b"traf", make_tfhd(default_duration=dur) +
487
+ make_trun([size] * 2, 0, durations=[dur] * 2, with_offset=False))
488
+ moof = box(b"moof", full_box(b"mfhd", 0, 0, u32(1)) + traf1 + traf2)
489
+ moof = set_offset(moof, len(moof) + 8) # traf1's run starts at the mdat content
490
+ data = (box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") +
491
+ moof + box(b"mdat", blob) + make_moov())
492
+ out = sp.proc(input=data, classic=True)
493
+ mdat = find(out, b"mdat")[0]
494
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == blob # both trafs' samples, in order
495
+ moov = find(out, b"moov")[0]
496
+ stco = find_deep(out, moov[1], moov[1] + moov[2], b"stco")
497
+ (count,) = struct.unpack_from(">I", out, stco[0] + 12)
498
+ assert count == 2
499
+ assert struct.unpack_from(">II", out, stco[0] + 16) == (mdat[1] + 8, mdat[1] + 8 + 40000)
500
+
501
+
502
+ def test_classic_deep_nesting_rejected(sp):
503
+ """Deeply nested containers would recurse the rewrite to a stack overflow
504
+ (uncatchable SIGSEGV) — the depth guard refuses them exactly like the
505
+ decrypt path's rebuild_container. The nest is built in O(n): each level
506
+ prepends an 8-byte trak header, so level k is k concatenated headers."""
507
+ moov = make_moov()
508
+ trak_pos = 8 + 108 # moov header + the 108-byte mvhd
509
+ (trak_size,) = struct.unpack_from(">I", moov, trak_pos)
510
+ n = 100_000
511
+ nested = b"".join(u32(8 * k) + b"trak" for k in range(n, 0, -1))
512
+ moov = (moov[:trak_pos] + u32(trak_size + len(nested)) + moov[trak_pos + 4:trak_pos + 8] +
513
+ nested + moov[trak_pos + 8:])
514
+ (moov_size,) = struct.unpack_from(">I", moov, 0)
515
+ moov = u32(moov_size + len(nested)) + moov[4:]
516
+ data = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") + make_moof(1, [make_tfhd(), make_trun([2048] * 2, 0)]) + box(b"mdat", bytes(4096)) + moov
517
+ try:
518
+ sp.proc(input=data, classic=True)
519
+ raise AssertionError("deep nesting accepted")
520
+ except DecrypTuneError as e:
521
+ assert e.code == 15, e
522
+
523
+
524
+ def test_classic_overlapping_chunks_rejected(sp):
525
+ """Hostile truns can all reference the same byte range — the summed output
526
+ used to inflate toward the 32-bit cap and force a huge allocation. Legit
527
+ sample bytes never exceed the input, so overlap is rejected."""
528
+ moofs = []
529
+ for seq in range(500):
530
+ m = make_moof(seq + 1, [make_tfhd(default_size=4096, default_duration=1024),
531
+ make_trun([4096] * 64, 0, with_sizes=False)])
532
+ moofs.append(set_offset(m, 100)) # every fragment claims the same bytes
533
+ ftyp = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom")
534
+ data = ftyp + b"".join(moofs) + make_moov()
535
+ try:
536
+ sp.proc(input=data, classic=True)
537
+ raise AssertionError("overlapping chunks accepted")
538
+ except DecrypTuneError as e:
539
+ assert e.code == 15, e
540
+
541
+
440
542
  # ---- fixtures ---------------------------------------------------------------
441
543
 
442
544
  @pytest.fixture(scope="session")
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