dissect.evidence 3.14.dev2__py3-none-any.whl → 3.14.dev4__py3-none-any.whl

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.
@@ -14,6 +14,9 @@ from dissect.evidence.exception import FileNotFoundError, NotADirectoryError, No
14
14
  if TYPE_CHECKING:
15
15
  from collections.abc import Iterator
16
16
  from pathlib import PurePath
17
+ from types import TracebackType
18
+
19
+ from typing_extensions import Self
17
20
 
18
21
  EntryType = c_ad1.EntryType
19
22
  MetaType = c_ad1.MetaType
@@ -53,8 +56,9 @@ class AD1:
53
56
  - https://al3ks1s.fr/posts/adventures-part-1/
54
57
  """
55
58
 
56
- def __init__(self, fh: BinaryIO | list[BinaryIO]):
57
- fhs = [fh] if not isinstance(fh, list) else fh
59
+ def __init__(self, fh: BinaryIO | list[BinaryIO] | Path | list[Path]):
60
+ fhs = find_files(fh) if isinstance(fh, Path) else [fh] if not isinstance(fh, list) else fh
61
+
58
62
  self.fh = fhs
59
63
  self.root = VirtualEntry(self, "/")
60
64
 
@@ -77,6 +81,14 @@ class AD1:
77
81
  else:
78
82
  self._open_ad1()
79
83
 
84
+ def __enter__(self) -> Self:
85
+ return self
86
+
87
+ def __exit__(
88
+ self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
89
+ ) -> None:
90
+ self.close()
91
+
80
92
  def is_adcrypt(self) -> bool:
81
93
  """Return whether the AD1 container is ADCRYPT encrypted."""
82
94
  return self.adcrypt is not None
@@ -91,7 +103,7 @@ class AD1:
91
103
  Implements a simple LRU cache to limit the number of open segments.
92
104
 
93
105
  Args:
94
- idx: Index or URI of the segment to open.
106
+ idx: Index of the segment to open.
95
107
  """
96
108
  # Poor mans LRU
97
109
  if idx in self._segments:
@@ -103,21 +115,20 @@ class AD1:
103
115
  oldest_idx = self._segment_lru.pop(0)
104
116
  oldest_segment = self._segments.pop(oldest_idx)
105
117
 
106
- # Don't close it if we received it as a file-like object
107
- if not hasattr(self.fh[oldest_idx], "read"):
118
+ # Only close file handles that we opened ourselves
119
+ if isinstance(self.fh[oldest_idx], Path):
108
120
  oldest_segment.fh.close()
109
121
 
110
122
  del oldest_segment
111
123
 
112
124
  fh = self.fh[idx]
113
- if not hasattr(fh, "read"):
114
- fh = fh.open("rb") if isinstance(fh, Path) else Path(fh).open("rb") # noqa: SIM115
125
+ if isinstance(fh, Path):
126
+ fh = fh.open("rb")
115
127
 
116
128
  if self.is_adcrypt() and not self.is_locked():
117
129
  fh = self.adcrypt.wrap(fh, idx)
118
130
 
119
131
  segment = SegmentFile(fh)
120
-
121
132
  self._segments[idx] = segment
122
133
  self._segment_lru.append(idx)
123
134
 
@@ -210,6 +221,15 @@ class AD1:
210
221
  """Shortcut for ``AD1.entry(path).open()``."""
211
222
  return self.entry(path).open()
212
223
 
224
+ def close(self) -> None:
225
+ """Close all segment file handles that we opened ourselves and clear the segment cache."""
226
+ for idx, segment in self._segments.items():
227
+ if isinstance(self.fh[idx], Path):
228
+ segment.fh.close()
229
+
230
+ self._segments = {}
231
+ self._segment_lru = []
232
+
213
233
 
214
234
  def _hallicinate_root_entries(ad1: AD1) -> None:
215
235
  # We need to create some fake entries for all parts leading up to `logical_image.name`
@@ -38,3 +38,6 @@ class ADCryptStream(AlignedStream):
38
38
  )
39
39
  cipher = AES.new(self.key, AES.MODE_CTR, counter=ctr)
40
40
  return cipher.decrypt(buf)
41
+
42
+ def close(self) -> None:
43
+ self.fh.close()
@@ -3,8 +3,6 @@ from __future__ import annotations
3
3
  from dissect.evidence.ewf.c_ewf import c_ewf
4
4
  from dissect.evidence.ewf.ewf import (
5
5
  EWF,
6
- EWFError,
7
- EWFStream,
8
6
  HeaderSection,
9
7
  SectionDescriptor,
10
8
  Segment,
@@ -12,10 +10,10 @@ from dissect.evidence.ewf.ewf import (
12
10
  VolumeSection,
13
11
  find_files,
14
12
  )
13
+ from dissect.evidence.ewf.stream import EWFStream
15
14
 
16
15
  __all__ = [
17
16
  "EWF",
18
- "EWFError",
19
17
  "EWFStream",
20
18
  "HeaderSection",
21
19
  "SectionDescriptor",
@@ -25,65 +25,95 @@ enum CompressionLevel : uint8 {
25
25
  };
26
26
 
27
27
  typedef struct {
28
- char signature[8];
29
- uint8 fields_start;
30
- uint16 segment_number;
31
- uint16 fields_end;
32
- } EWFHeader;
28
+ char signature[8];
29
+ uint8 fields_start;
30
+ uint16 segment_number;
31
+ uint16 fields_end;
32
+ } SegmentHeader;
33
33
 
34
34
  typedef struct {
35
- char type[16];
36
- uint64 next;
37
- uint64 size;
38
- uint8 pad[40];
39
- uint32 checksum;
40
- } EWFSectionDescriptor;
35
+ char type[16];
36
+ uint64 next;
37
+ uint64 size;
38
+ uint8 pad[40];
39
+ uint32 checksum;
40
+ } SectionDescriptor;
41
41
 
42
42
  typedef struct {
43
- uint32 reserved_1;
44
- uint32 chunk_count;
45
- uint32 sector_count;
46
- uint32 sector_size;
47
- uint32 total_sector_count;
48
- uint8 reserved[20];
49
- uint8 pad[45];
50
- char signature[5];
51
- uint32 checksum;
52
- } EWFVolumeSectionSpec;
43
+ uint32 reserved_1;
44
+ uint32 number_of_chunks;
45
+ uint32 sectors_per_chunk;
46
+ uint32 bytes_per_sector;
47
+ uint32 number_of_sectors;
48
+ uint8 reserved[20];
49
+ uint8 pad[45];
50
+ char signature[5];
51
+ uint32 checksum;
52
+ } VolumeSectionSmart;
53
53
 
54
54
  typedef struct {
55
55
  MediaType media_type;
56
56
  uint8 reserved_1[3];
57
- uint32 chunk_count;
58
- uint32 sector_count;
59
- uint32 sector_size;
60
- uint64 total_sector_count;
61
- uint32 num_cylinders;
62
- uint32 num_heads;
63
- uint32 num_sectors;
57
+ uint32 number_of_chunks;
58
+ uint32 sectors_per_chunk;
59
+ uint32 bytes_per_sector;
60
+ uint64 number_of_sectors;
61
+ uint32 chs_cylinders;
62
+ uint32 chs_heads;
63
+ uint32 chs_sectors;
64
64
  uint8 media_flags;
65
65
  uint8 unknown_1[3];
66
- uint32 palm_start_sector;
66
+ uint32 palm_volume_start_sector;
67
67
  uint32 unknown_2;
68
- uint32 smart_start_sector;
68
+ uint32 smart_logs_start_sector;
69
69
  CompressionLevel compression_level;
70
70
  uint8 unknown_3[3];
71
71
  uint32 error_granularity;
72
72
  uint32 unknown_4;
73
- uint8 uuid[16];
73
+ uint8 set_identifier[16];
74
74
  uint8 pad[963];
75
75
  char signature[5];
76
76
  uint32 checksum;
77
- } EWFVolumeSection;
77
+ } VolumeSection;
78
+
79
+ typedef struct {
80
+ MediaType media_type;
81
+ uint8 unknown1[3];
82
+ uint32 number_of_chunks;
83
+ uint32 sectors_per_chunk;
84
+ uint32 bytes_per_sector;
85
+ uint64 number_of_sectors;
86
+ uint32 chs_cylinders;
87
+ uint32 chs_heads;
88
+ uint32 chs_sectors;
89
+ MediaFlags media_flags;
90
+ uint8 unknown2[3];
91
+ uint32 palm_volume_start_sector;
92
+ uint32 unknown3;
93
+ uint32 smart_logs_start_sector;
94
+ CompressionLevel compression_level;
95
+ uint8 unknown4[3];
96
+ uint32 error_granularity;
97
+ uint32 unknown5;
98
+ uint8 set_identifier[16];
99
+ char pad[963];
100
+ char signature[5];
101
+ uint32 checksum;
102
+ } DataSection;
103
+
104
+ typedef struct {
105
+ uint32 number_of_entries;
106
+ uint32 _;
107
+ uint64 base_offset;
108
+ uint32 _;
109
+ uint32 checksum;
110
+ } TableSection;
78
111
 
79
112
  typedef struct {
80
- uint32 num_entries;
81
- uint32 _;
82
- uint64 base_offset;
83
- uint32 _;
84
- uint32 checksum;
85
- uint32 entries[num_entries];
86
- } EWFTableSection;
113
+ char md5[16];
114
+ char unknown1[16];
115
+ uint32 checksum;
116
+ } HashSection;
87
117
  """
88
118
 
89
119
  c_ewf = cstruct().load(ewf_def)
@@ -22,7 +22,7 @@ class _c_ewf(__cs__.cstruct):
22
22
  Good = ...
23
23
  Best = ...
24
24
 
25
- class EWFHeader(__cs__.Structure):
25
+ class SegmentHeader(__cs__.Structure):
26
26
  signature: __cs__.CharArray
27
27
  fields_start: _c_ewf.uint8
28
28
  segment_number: _c_ewf.uint16
@@ -38,7 +38,7 @@ class _c_ewf(__cs__.cstruct):
38
38
  @overload
39
39
  def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO, /): ...
40
40
 
41
- class EWFSectionDescriptor(__cs__.Structure):
41
+ class SectionDescriptor(__cs__.Structure):
42
42
  type: __cs__.CharArray
43
43
  next: _c_ewf.uint64
44
44
  size: _c_ewf.uint64
@@ -56,12 +56,12 @@ class _c_ewf(__cs__.cstruct):
56
56
  @overload
57
57
  def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO, /): ...
58
58
 
59
- class EWFVolumeSectionSpec(__cs__.Structure):
59
+ class VolumeSectionSmart(__cs__.Structure):
60
60
  reserved_1: _c_ewf.uint32
61
- chunk_count: _c_ewf.uint32
62
- sector_count: _c_ewf.uint32
63
- sector_size: _c_ewf.uint32
64
- total_sector_count: _c_ewf.uint32
61
+ number_of_chunks: _c_ewf.uint32
62
+ sectors_per_chunk: _c_ewf.uint32
63
+ bytes_per_sector: _c_ewf.uint32
64
+ number_of_sectors: _c_ewf.uint32
65
65
  reserved: __cs__.Array[_c_ewf.uint8]
66
66
  pad: __cs__.Array[_c_ewf.uint8]
67
67
  signature: __cs__.CharArray
@@ -70,10 +70,10 @@ class _c_ewf(__cs__.cstruct):
70
70
  def __init__(
71
71
  self,
72
72
  reserved_1: _c_ewf.uint32 | None = ...,
73
- chunk_count: _c_ewf.uint32 | None = ...,
74
- sector_count: _c_ewf.uint32 | None = ...,
75
- sector_size: _c_ewf.uint32 | None = ...,
76
- total_sector_count: _c_ewf.uint32 | None = ...,
73
+ number_of_chunks: _c_ewf.uint32 | None = ...,
74
+ sectors_per_chunk: _c_ewf.uint32 | None = ...,
75
+ bytes_per_sector: _c_ewf.uint32 | None = ...,
76
+ number_of_sectors: _c_ewf.uint32 | None = ...,
77
77
  reserved: __cs__.Array[_c_ewf.uint8] | None = ...,
78
78
  pad: __cs__.Array[_c_ewf.uint8] | None = ...,
79
79
  signature: __cs__.CharArray | None = ...,
@@ -82,26 +82,26 @@ class _c_ewf(__cs__.cstruct):
82
82
  @overload
83
83
  def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO, /): ...
84
84
 
85
- class EWFVolumeSection(__cs__.Structure):
85
+ class VolumeSection(__cs__.Structure):
86
86
  media_type: _c_ewf.MediaType
87
87
  reserved_1: __cs__.Array[_c_ewf.uint8]
88
- chunk_count: _c_ewf.uint32
89
- sector_count: _c_ewf.uint32
90
- sector_size: _c_ewf.uint32
91
- total_sector_count: _c_ewf.uint64
92
- num_cylinders: _c_ewf.uint32
93
- num_heads: _c_ewf.uint32
94
- num_sectors: _c_ewf.uint32
88
+ number_of_chunks: _c_ewf.uint32
89
+ sectors_per_chunk: _c_ewf.uint32
90
+ bytes_per_sector: _c_ewf.uint32
91
+ number_of_sectors: _c_ewf.uint64
92
+ chs_cylinders: _c_ewf.uint32
93
+ chs_heads: _c_ewf.uint32
94
+ chs_sectors: _c_ewf.uint32
95
95
  media_flags: _c_ewf.uint8
96
96
  unknown_1: __cs__.Array[_c_ewf.uint8]
97
- palm_start_sector: _c_ewf.uint32
97
+ palm_volume_start_sector: _c_ewf.uint32
98
98
  unknown_2: _c_ewf.uint32
99
- smart_start_sector: _c_ewf.uint32
99
+ smart_logs_start_sector: _c_ewf.uint32
100
100
  compression_level: _c_ewf.CompressionLevel
101
101
  unknown_3: __cs__.Array[_c_ewf.uint8]
102
102
  error_granularity: _c_ewf.uint32
103
103
  unknown_4: _c_ewf.uint32
104
- uuid: __cs__.Array[_c_ewf.uint8]
104
+ set_identifier: __cs__.Array[_c_ewf.uint8]
105
105
  pad: __cs__.Array[_c_ewf.uint8]
106
106
  signature: __cs__.CharArray
107
107
  checksum: _c_ewf.uint32
@@ -110,23 +110,23 @@ class _c_ewf(__cs__.cstruct):
110
110
  self,
111
111
  media_type: _c_ewf.MediaType | None = ...,
112
112
  reserved_1: __cs__.Array[_c_ewf.uint8] | None = ...,
113
- chunk_count: _c_ewf.uint32 | None = ...,
114
- sector_count: _c_ewf.uint32 | None = ...,
115
- sector_size: _c_ewf.uint32 | None = ...,
116
- total_sector_count: _c_ewf.uint64 | None = ...,
117
- num_cylinders: _c_ewf.uint32 | None = ...,
118
- num_heads: _c_ewf.uint32 | None = ...,
119
- num_sectors: _c_ewf.uint32 | None = ...,
113
+ number_of_chunks: _c_ewf.uint32 | None = ...,
114
+ sectors_per_chunk: _c_ewf.uint32 | None = ...,
115
+ bytes_per_sector: _c_ewf.uint32 | None = ...,
116
+ number_of_sectors: _c_ewf.uint64 | None = ...,
117
+ chs_cylinders: _c_ewf.uint32 | None = ...,
118
+ chs_heads: _c_ewf.uint32 | None = ...,
119
+ chs_sectors: _c_ewf.uint32 | None = ...,
120
120
  media_flags: _c_ewf.uint8 | None = ...,
121
121
  unknown_1: __cs__.Array[_c_ewf.uint8] | None = ...,
122
- palm_start_sector: _c_ewf.uint32 | None = ...,
122
+ palm_volume_start_sector: _c_ewf.uint32 | None = ...,
123
123
  unknown_2: _c_ewf.uint32 | None = ...,
124
- smart_start_sector: _c_ewf.uint32 | None = ...,
124
+ smart_logs_start_sector: _c_ewf.uint32 | None = ...,
125
125
  compression_level: _c_ewf.CompressionLevel | None = ...,
126
126
  unknown_3: __cs__.Array[_c_ewf.uint8] | None = ...,
127
127
  error_granularity: _c_ewf.uint32 | None = ...,
128
128
  unknown_4: _c_ewf.uint32 | None = ...,
129
- uuid: __cs__.Array[_c_ewf.uint8] | None = ...,
129
+ set_identifier: __cs__.Array[_c_ewf.uint8] | None = ...,
130
130
  pad: __cs__.Array[_c_ewf.uint8] | None = ...,
131
131
  signature: __cs__.CharArray | None = ...,
132
132
  checksum: _c_ewf.uint32 | None = ...,
@@ -134,20 +134,84 @@ class _c_ewf(__cs__.cstruct):
134
134
  @overload
135
135
  def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO, /): ...
136
136
 
137
- class EWFTableSection(__cs__.Structure):
138
- num_entries: _c_ewf.uint32
137
+ class DataSection(__cs__.Structure):
138
+ media_type: _c_ewf.MediaType
139
+ unknown1: __cs__.Array[_c_ewf.uint8]
140
+ number_of_chunks: _c_ewf.uint32
141
+ sectors_per_chunk: _c_ewf.uint32
142
+ bytes_per_sector: _c_ewf.uint32
143
+ number_of_sectors: _c_ewf.uint64
144
+ chs_cylinders: _c_ewf.uint32
145
+ chs_heads: _c_ewf.uint32
146
+ chs_sectors: _c_ewf.uint32
147
+ media_flags: _c_ewf.MediaFlags
148
+ unknown2: __cs__.Array[_c_ewf.uint8]
149
+ palm_volume_start_sector: _c_ewf.uint32
150
+ unknown3: _c_ewf.uint32
151
+ smart_logs_start_sector: _c_ewf.uint32
152
+ compression_level: _c_ewf.CompressionLevel
153
+ unknown4: __cs__.Array[_c_ewf.uint8]
154
+ error_granularity: _c_ewf.uint32
155
+ unknown5: _c_ewf.uint32
156
+ set_identifier: __cs__.Array[_c_ewf.uint8]
157
+ pad: __cs__.CharArray
158
+ signature: __cs__.CharArray
159
+ checksum: _c_ewf.uint32
160
+ @overload
161
+ def __init__(
162
+ self,
163
+ media_type: _c_ewf.MediaType | None = ...,
164
+ unknown1: __cs__.Array[_c_ewf.uint8] | None = ...,
165
+ number_of_chunks: _c_ewf.uint32 | None = ...,
166
+ sectors_per_chunk: _c_ewf.uint32 | None = ...,
167
+ bytes_per_sector: _c_ewf.uint32 | None = ...,
168
+ number_of_sectors: _c_ewf.uint64 | None = ...,
169
+ chs_cylinders: _c_ewf.uint32 | None = ...,
170
+ chs_heads: _c_ewf.uint32 | None = ...,
171
+ chs_sectors: _c_ewf.uint32 | None = ...,
172
+ media_flags: _c_ewf.MediaFlags | None = ...,
173
+ unknown2: __cs__.Array[_c_ewf.uint8] | None = ...,
174
+ palm_volume_start_sector: _c_ewf.uint32 | None = ...,
175
+ unknown3: _c_ewf.uint32 | None = ...,
176
+ smart_logs_start_sector: _c_ewf.uint32 | None = ...,
177
+ compression_level: _c_ewf.CompressionLevel | None = ...,
178
+ unknown4: __cs__.Array[_c_ewf.uint8] | None = ...,
179
+ error_granularity: _c_ewf.uint32 | None = ...,
180
+ unknown5: _c_ewf.uint32 | None = ...,
181
+ set_identifier: __cs__.Array[_c_ewf.uint8] | None = ...,
182
+ pad: __cs__.CharArray | None = ...,
183
+ signature: __cs__.CharArray | None = ...,
184
+ checksum: _c_ewf.uint32 | None = ...,
185
+ ): ...
186
+ @overload
187
+ def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO, /): ...
188
+
189
+ class TableSection(__cs__.Structure):
190
+ number_of_entries: _c_ewf.uint32
139
191
  _: _c_ewf.uint32
140
192
  base_offset: _c_ewf.uint64
141
193
  checksum: _c_ewf.uint32
142
- entries: __cs__.Array[_c_ewf.uint32]
143
194
  @overload
144
195
  def __init__(
145
196
  self,
146
- num_entries: _c_ewf.uint32 | None = ...,
197
+ number_of_entries: _c_ewf.uint32 | None = ...,
147
198
  _: _c_ewf.uint32 | None = ...,
148
199
  base_offset: _c_ewf.uint64 | None = ...,
149
200
  checksum: _c_ewf.uint32 | None = ...,
150
- entries: __cs__.Array[_c_ewf.uint32] | None = ...,
201
+ ): ...
202
+ @overload
203
+ def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO, /): ...
204
+
205
+ class HashSection(__cs__.Structure):
206
+ md5: __cs__.CharArray
207
+ unknown1: __cs__.CharArray
208
+ checksum: _c_ewf.uint32
209
+ @overload
210
+ def __init__(
211
+ self,
212
+ md5: __cs__.CharArray | None = ...,
213
+ unknown1: __cs__.CharArray | None = ...,
214
+ checksum: _c_ewf.uint32 | None = ...,
151
215
  ): ...
152
216
  @overload
153
217
  def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO, /): ...
@@ -1,21 +1,20 @@
1
1
  from __future__ import annotations
2
2
 
3
- import logging
4
- import os
3
+ import codecs
5
4
  import zlib
6
5
  from bisect import bisect_right
7
- from functools import lru_cache
6
+ from functools import cached_property, lru_cache
8
7
  from pathlib import Path
9
- from typing import BinaryIO
10
-
11
- from dissect.util.stream import AlignedStream
8
+ from typing import TYPE_CHECKING, BinaryIO
12
9
 
10
+ from dissect.evidence.adcrypt.adcrypt import ADCrypt, is_adcrypt
13
11
  from dissect.evidence.ewf import c_ewf
14
- from dissect.evidence.exception import EWFError
12
+ from dissect.evidence.ewf.stream import EWFStream
15
13
 
16
- log = logging.getLogger(__name__)
17
- log.setLevel(os.getenv("DISSECT_LOG_EWF", "CRITICAL"))
14
+ if TYPE_CHECKING:
15
+ from types import TracebackType
18
16
 
17
+ from typing_extensions import Self
19
18
 
20
19
  MAX_OPEN_SEGMENTS = 128
21
20
 
@@ -29,7 +28,7 @@ def find_files(path: str | Path) -> list[Path]:
29
28
  ext = path.suffix
30
29
 
31
30
  if ext[1].upper() not in "ELS":
32
- raise EWFError(f"Invalid EWF file: {path}")
31
+ raise ValueError(f"Invalid EWF file: {path}")
33
32
 
34
33
  ewfglob = f"[{ext[1]}-{'Z' if ext[1].isupper() else 'z'}]" if len(ext) == 4 else f"{ext[1]}[x-z]"
35
34
 
@@ -37,52 +36,66 @@ def find_files(path: str | Path) -> list[Path]:
37
36
 
38
37
 
39
38
  class EWF:
40
- """Expert Witness Disk Image Format."""
39
+ """Expert Witness Disk Image Format.
40
+
41
+ Args:
42
+ fh: A file handle, list of file handles, path or list of paths to the EWF segment files.
43
+ If a path is provided, all related segment files will be automatically discovered.
44
+ """
41
45
 
42
46
  def __init__(self, fh: BinaryIO | list[BinaryIO] | Path | list[Path]):
43
- fhs = [fh] if not isinstance(fh, list) else fh
47
+ fhs = find_files(fh) if isinstance(fh, Path) else [fh] if not isinstance(fh, list) else fh
44
48
 
45
49
  self.fh = fhs
46
- self.header: HeaderSection = None
47
- self.volume: VolumeSection = None
48
- self._segments: dict[str, Segment] = {}
49
- self._segment_offsets = []
50
- self._segment_lru = []
50
+ self.header: HeaderSection | None = None
51
+ self.volume: VolumeSection | None = None
51
52
 
52
- segment_offset = 0
53
+ self.chunk_size = 0
54
+ self.size = 0
53
55
 
54
- for i in range(len(fhs)):
55
- try:
56
- segment = self.segment(i)
57
- except Exception:
58
- log.exception("Failed to parse as EWF file: %s", fh)
59
- continue
56
+ self._segments: dict[int, Segment] = {}
57
+ self._segment_lru: list[int] = []
60
58
 
61
- if segment.header and not self.header:
62
- self.header = segment.header
59
+ self._chunk_lookup: list[int] = []
60
+ self._chunk_map: list[tuple[int, int]] = []
63
61
 
64
- if segment.volume and not self.volume:
65
- self.volume = segment.volume
62
+ if not self.fh:
63
+ raise ValueError("No segment files provided for EWF container")
64
+
65
+ self.adcrypt = None
66
66
 
67
- if segment_offset != 0:
68
- self._segment_offsets.append(segment_offset)
67
+ first_segment = self.segment(0)
68
+ if is_adcrypt(first_segment.fh):
69
+ self.adcrypt = ADCrypt(first_segment.fh)
70
+ else:
71
+ self._open_ewf()
69
72
 
70
- segment.offset = segment_offset * self.volume.sector_size
71
- segment.sector_offset = segment_offset
72
- segment_offset += segment.sector_count
73
+ self.read_chunk = lru_cache(128)(self.read_chunk)
73
74
 
74
- if not self.header or not self.volume:
75
- raise EWFError(f"Failed to load EWF: {fh}")
75
+ def __enter__(self) -> Self:
76
+ return self
76
77
 
77
- self.chunk_size = self.volume.sector_count * self.volume.sector_size
78
+ def __exit__(
79
+ self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
80
+ ) -> None:
81
+ self.close()
78
82
 
79
- max_size = self.volume.chunk_count * self.volume.sector_count * self.volume.sector_size
80
- last_table = self.segment(len(self.fh) - 1).tables[-1]
81
- last_chunk_size = len(last_table.read_chunk(last_table.num_entries - 1))
83
+ def is_adcrypt(self) -> bool:
84
+ """Return whether the EWF container is ADCRYPT encrypted."""
85
+ return self.adcrypt is not None
82
86
 
83
- self.size = max_size - (self.chunk_size - last_chunk_size)
87
+ def is_locked(self) -> bool:
88
+ """Return whether the ADCRYPT container is locked."""
89
+ return self.is_adcrypt() and self.adcrypt.is_locked()
84
90
 
85
91
  def segment(self, idx: int) -> Segment:
92
+ """Open a segment by index.
93
+
94
+ Implements a simple LRU cache to limit the number of open segments.
95
+
96
+ Args:
97
+ idx: Index of the segment to open.
98
+ """
86
99
  # Poor mans LRU
87
100
  if idx in self._segments:
88
101
  self._segment_lru.remove(idx)
@@ -93,274 +106,375 @@ class EWF:
93
106
  oldest_idx = self._segment_lru.pop(0)
94
107
  oldest_segment = self._segments.pop(oldest_idx)
95
108
 
96
- # Don't close it if we received it as a file-like object
97
- if not hasattr(self.fh[oldest_idx], "read"):
109
+ # Only close file handles that we opened ourselves
110
+ if isinstance(self.fh[oldest_idx], Path):
98
111
  oldest_segment.fh.close()
99
112
 
100
113
  del oldest_segment
101
114
 
102
115
  fh = self.fh[idx]
103
- if not hasattr(fh, "read"):
104
- fh = fh.open("rb") if isinstance(fh, Path) else Path(fh).open("rb") # noqa: SIM115
105
-
106
- segment = Segment(self, fh)
107
- if self.volume and 0 < idx <= len(self._segment_offsets):
108
- # We already have a known segment offset for this segment, so set it back
109
- segment_offset = self._segment_offsets[idx - 1]
110
- segment.offset = segment_offset * self.volume.sector_size
111
- segment.sector_offset = segment_offset
112
- else:
113
- # Otherwise we're in the initialization loop (or we're idx == 0)
114
- segment.offset = 0
115
- segment.sector_offset = 0
116
+ if isinstance(fh, Path):
117
+ fh = fh.open("rb")
116
118
 
119
+ if self.is_adcrypt() and not self.is_locked():
120
+ fh = self.adcrypt.wrap(fh, idx)
121
+
122
+ segment = Segment(fh)
117
123
  self._segments[idx] = segment
118
124
  self._segment_lru.append(idx)
119
125
 
120
126
  return segment
121
127
 
122
- def open(self) -> BinaryIO:
123
- return EWFStream(self)
128
+ def unlock(self, *, passphrase: str | bytes | None = None, private_key: Path | bytes | None = None) -> None:
129
+ """Unlock the ADCRYPT container with a given passphrase or private key.
124
130
 
131
+ Args:
132
+ passphrase: The passphrase to unlock the container.
133
+ private_key: The private key to unlock the container.
125
134
 
126
- class EWFStream(AlignedStream):
127
- def __init__(self, ewf: EWF):
128
- self.ewf = ewf
129
- self.sector_size = self.ewf.volume.sector_size
130
- super().__init__(ewf.size)
135
+ Raises:
136
+ RuntimeError: If required dependencies are missing.
137
+ ValueError: If unlocking failed.
138
+ """
139
+ self.adcrypt.unlock(passphrase=passphrase, private_key=private_key)
131
140
 
132
- def _read(self, offset: int, length: int) -> bytes:
133
- result = []
141
+ # Reset LRU
142
+ self._segments = {}
143
+ self._segment_lru = []
134
144
 
135
- sector_offset = offset // self.sector_size
136
- sector_count = (length + self.sector_size - 1) // self.sector_size
145
+ # Open the EWF
146
+ self._open_ewf()
137
147
 
138
- segment_idx = bisect_right(self.ewf._segment_offsets, sector_offset)
148
+ def _open_ewf(self) -> None:
149
+ """Open the EWF container and initialize the volume and chunk information."""
150
+ self.volume = None
139
151
 
140
- while sector_count > 0:
141
- if segment_idx > len(self.ewf._segment_offsets):
142
- raise EWFError(f"Missing EWF file for segment index: {segment_idx}")
152
+ chunk = 0
153
+ for i in range(len(self.fh)):
154
+ segment = self.segment(i)
155
+ if segment.header.signature not in (b"EVF\x09\x0d\x0a\xff\x00", b"LVF\x09\x0d\x0a\xff\x00"):
156
+ raise ValueError(f"Invalid EWF signature in segment {i}, got {segment.header.signature!r}")
143
157
 
144
- segment = self.ewf.segment(segment_idx)
158
+ if segment.number != i + 1:
159
+ raise ValueError(f"Invalid EWF segment number in segment {i}, got {segment.number}, expected {i + 1}")
145
160
 
146
- segment_remaining_sectors = segment.sector_count - (sector_offset - segment.sector_offset)
147
- segment_sectors = min(segment_remaining_sectors, sector_count)
161
+ if not self.volume and segment.volume:
162
+ self.volume = segment.volume
163
+ self.chunk_size = self.volume.sectors_per_chunk * self.volume.sector_size
164
+ elif not self.volume and not segment.volume:
165
+ raise ValueError("Missing expected volume section in first segment")
148
166
 
149
- result.append(segment.read_sectors(sector_offset, segment_sectors))
150
- sector_offset += segment_sectors
151
- sector_count -= segment_sectors
167
+ for j, table in enumerate(segment.tables):
168
+ chunk += table.number_of_entries
169
+ self._chunk_lookup.append(chunk)
170
+ self._chunk_map.append((i, j))
152
171
 
153
- segment_idx += 1
172
+ max_size = self.volume.number_of_chunks * self.chunk_size
173
+ last_chunk = self.read_chunk(self.volume.number_of_chunks - 1)
154
174
 
155
- return b"".join(result)
175
+ self.size = max_size - (self.chunk_size - len(last_chunk))
156
176
 
177
+ def read_chunk(self, chunk: int) -> bytes:
178
+ """Read a chunk of data from the EWF container.
157
179
 
158
- class Segment:
159
- def __init__(self, ewf: EWF, fh: BinaryIO):
160
- self.ewf = ewf
161
- self.fh = fh
180
+ Args:
181
+ chunk: The chunk index to read.
182
+ """
183
+ lookup_idx = bisect_right(self._chunk_lookup, chunk)
184
+ if lookup_idx >= len(self._chunk_map):
185
+ raise IndexError(f"Chunk {chunk} out of range")
162
186
 
163
- fh.seek(0)
164
- self.ewfheader = c_ewf.EWFHeader(fh)
165
- self.header = ewf.header
166
- self.volume = ewf.volume
187
+ segment_idx, table_idx = self._chunk_map[lookup_idx]
167
188
 
168
- if self.ewfheader.signature not in (b"EVF\x09\x0d\x0a\xff\x00", b"LVF\x09\x0d\x0a\xff\x00"):
169
- raise EWFError(f"Invalid signature, got {self.ewfheader.signature!r}")
189
+ segment = self.segment(segment_idx)
190
+ table = segment.tables[table_idx]
170
191
 
171
- self.sections: list[SectionDescriptor] = []
172
- self.tables: list[TableSection] = []
173
- self.table_offsets = []
192
+ chunk_offset = 0 if lookup_idx == 0 else self._chunk_lookup[lookup_idx - 1]
193
+ relative_chunk = chunk - chunk_offset
174
194
 
175
- offset = 0
176
- sector_offset = 0
195
+ entry = table.entries[relative_chunk]
196
+ offset_of_chunk = table.base_offset + (entry & 0x7FFFFFFF)
197
+ compressed = entry >> 31 == 1
177
198
 
178
- while True:
179
- section = SectionDescriptor(fh)
180
- self.sections.append(section)
199
+ # We don't know the chunk size, so try to determine it using the offset of the next chunk
200
+ # When it's the last chunk in the table though, this becomes trickier
201
+ # We have to check if the chunk data is preceding the table, or if it's contained within the table section
202
+ if relative_chunk == table.number_of_entries - 1:
203
+ # The chunk data is stored before the table section (probably in a sectors section)
204
+ if offset_of_chunk < table.descriptor.offset:
205
+ end_of_chunk = table.descriptor.offset
181
206
 
182
- if section.type in (b"header", b"header2") and not self.header:
183
- self.header = HeaderSection(self, section)
207
+ # The chunk data is stored within the table section
208
+ elif offset_of_chunk < table.descriptor.offset + table.descriptor.raw_size:
209
+ end_of_chunk = table.descriptor.offset + table.descriptor.raw_size
184
210
 
185
- if section.type in (b"disk", b"volume") and not self.volume:
186
- self.volume = VolumeSection(self, section)
211
+ else:
212
+ raise ValueError("Unknown size of last chunk")
213
+ else:
214
+ end_of_chunk = table.base_offset + (table.entries[relative_chunk + 1] & 0x7FFFFFFF)
187
215
 
188
- if section.type == b"table":
189
- table = TableSection(self, section)
216
+ size_of_chunk = end_of_chunk - offset_of_chunk
190
217
 
191
- if sector_offset != 0:
192
- self.table_offsets.append(sector_offset)
218
+ # Uncompressed chunks have a 4 byte checksum at the end
219
+ if not compressed:
220
+ size_of_chunk -= 4
193
221
 
194
- table.offset = sector_offset * self.volume.sector_size
195
- table.sector_offset = sector_offset
196
- sector_offset += table.sector_count
222
+ segment.fh.seek(offset_of_chunk)
223
+ buf = segment.fh.read(size_of_chunk)
224
+ if compressed:
225
+ buf = zlib.decompress(buf)
197
226
 
198
- self.tables.append(table)
227
+ return buf
199
228
 
200
- if section.next == offset or section.type == b"done":
201
- break
229
+ def open(self) -> BinaryIO:
230
+ """Open a stream to read the EWF container contents."""
231
+ if self.is_locked():
232
+ raise ValueError("EWF container is locked by ADCRYPT")
233
+
234
+ return EWFStream(self)
235
+
236
+ def close(self) -> None:
237
+ """Close all segment file handles that we opened ourselves and clear the segment cache."""
238
+ for idx, segment in self._segments.items():
239
+ if isinstance(self.fh[idx], Path):
240
+ segment.fh.close()
202
241
 
203
- offset = section.next
204
- fh.seek(offset)
242
+ self._segments = {}
243
+ self._segment_lru = []
244
+
245
+
246
+ class Segment:
247
+ """EWF segment."""
248
+
249
+ def __init__(self, fh: BinaryIO):
250
+ self.fh = fh
251
+
252
+ self.fh.seek(0)
253
+ self.header = c_ewf.SegmentHeader(fh)
254
+ self.number = self.header.segment_number
255
+
256
+ @cached_property
257
+ def sections(self) -> list[Section]:
258
+ """Return all sections in this segment."""
259
+ result = []
205
260
 
206
- self.chunk_count = sum([t.num_entries for t in self.tables])
207
- self.sector_count = self.chunk_count * self.volume.sector_count
208
- self.size = self.chunk_count * self.volume.sector_count * self.volume.sector_size
209
- self.sector_offset = None # Set later
210
- self.offset = None # Set later
261
+ offset = len(c_ewf.SegmentHeader)
262
+ while True:
263
+ self.fh.seek(offset)
264
+ section = Section.from_fh(self.fh)
265
+ result.append(section)
211
266
 
212
- def read_sectors(self, sector: int, count: int) -> bytes:
213
- log.debug("Segment::read_sectors(0x%x, 0x%x)", sector, count)
214
- segment_sector = sector - self.sector_offset
215
- r = []
267
+ if section.descriptor.next == offset or section.descriptor.type == b"done":
268
+ break
216
269
 
217
- table_idx = bisect_right(self.table_offsets, segment_sector)
218
- while count > 0:
219
- table = self.tables[table_idx]
270
+ offset = section.descriptor.next
220
271
 
221
- table_remaining_sectors = table.sector_count - (segment_sector - table.sector_offset)
222
- table_sectors = min(table_remaining_sectors, count)
272
+ return result
223
273
 
224
- r.append(table.read_sectors(segment_sector, table_sectors))
225
- segment_sector += table_sectors
226
- count -= table_sectors
274
+ @cached_property
275
+ def headers(self) -> list[HeaderSection]:
276
+ """Return all header sections in this segment."""
277
+ return [section for section in self.sections if isinstance(section, HeaderSection)]
227
278
 
228
- table_idx += 1
279
+ @cached_property
280
+ def tables(self) -> list[TableSection]:
281
+ """Return all table sections in this segment."""
282
+ return [section for section in self.sections if type(section) is TableSection] # Ignore Table2Section
229
283
 
230
- return b"".join(r)
284
+ @cached_property
285
+ def volume(self) -> VolumeSection | None:
286
+ """Return the volume section in this segment, if present."""
287
+ for section in self.sections:
288
+ if isinstance(section, VolumeSection):
289
+ return section
290
+ return None
231
291
 
232
292
 
233
- class HeaderSection:
234
- def __init__(self, segment: Segment, section: SectionDescriptor):
235
- self.segment = segment
236
- self.section = section
293
+ class SectionDescriptor:
294
+ """EWF section descriptor."""
237
295
 
238
- fh = segment.fh
239
- fh.seek(section.data_offset)
240
- self.data = zlib.decompress(fh.read(section.size))
296
+ def __init__(self, fh: BinaryIO):
297
+ self.fh = fh
241
298
 
242
- if self.data[0] in (b"\xff", b"\xfe"):
243
- self.data = self.data.decode("utf16")
299
+ self.offset = fh.tell()
300
+ self.descriptor = c_ewf.SectionDescriptor(fh)
244
301
 
245
302
  def __repr__(self) -> str:
246
- return f"<HeaderSection categories={int(self.data[0])}>"
303
+ return (
304
+ f"<SectionDescriptor "
305
+ f"type={self.type!r} size={self.size:#x} offset={self.offset:#x} checksum={self.checksum:#x}>"
306
+ )
247
307
 
308
+ @property
309
+ def type(self) -> str:
310
+ """The type of the section."""
311
+ return self.descriptor.type.rstrip(b"\x00").decode()
248
312
 
249
- class VolumeSection:
250
- def __init__(self, segment: Segment, section: SectionDescriptor):
251
- self.segment = segment
252
- self.section = section
313
+ @property
314
+ def next(self) -> int:
315
+ """The offset of the next section."""
316
+ return self.descriptor.next
253
317
 
254
- fh = segment.fh
255
- fh.seek(section.data_offset)
256
- data = c_ewf.EWFVolumeSection(fh) if section.size == 1052 else c_ewf.EWFVolumeSectionSpec(fh)
318
+ @property
319
+ def raw_size(self) -> int:
320
+ """The raw size of the section, including the descriptor."""
321
+ return self.descriptor.size
257
322
 
258
- self.volume = data
259
- self.chunk_count = data.chunk_count
260
- self.sector_count = data.sector_count
261
- self.sector_size = data.sector_size
323
+ @property
324
+ def size(self) -> int:
325
+ """The size of the section data."""
326
+ return (self.descriptor.size - len(c_ewf.SectionDescriptor)) if self.descriptor.size else 0
262
327
 
328
+ @property
329
+ def data(self) -> bytes:
330
+ """The raw data of the section."""
331
+ self.fh.seek(self.offset + len(c_ewf.SectionDescriptor))
332
+ return self.fh.read(self.size)
263
333
 
264
- class TableSection:
265
- def __init__(self, segment: Segment, section: SectionDescriptor):
266
- self.segment = segment
267
- self.section = section
334
+ @property
335
+ def checksum(self) -> int:
336
+ """The checksum of the section data."""
337
+ return self.descriptor.checksum
268
338
 
269
- fh = segment.fh
270
- fh.seek(section.data_offset)
271
339
 
272
- self.header = c_ewf.EWFTableSection(fh)
273
- self.num_entries = self.header.num_entries
274
- self.base_offset = self.header.base_offset
275
- self.entries = self.header.entries
340
+ class Section:
341
+ """EWF section."""
276
342
 
277
- self.sector_count = self.num_entries * self.segment.volume.sector_count
278
- self.size = self.sector_count * self.segment.volume.sector_size
279
- self.sector_offset = None # Set later
280
- self.offset = None # Set later
343
+ def __init__(self, descriptor: SectionDescriptor):
344
+ self.descriptor = descriptor
281
345
 
282
- self.read_chunk = lru_cache(1024)(self.read_chunk)
346
+ def __repr__(self) -> str:
347
+ return f"<{self.__class__.__name__} type={self.descriptor.type!r} size={self.descriptor.size:#x}>"
283
348
 
284
- def read_chunk(self, chunk: int) -> bytes:
285
- log.debug("TableSection::read_chunk(0x%x)", chunk)
349
+ @classmethod
350
+ def from_fh(
351
+ cls, fh: BinaryIO
352
+ ) -> Section | HeaderSection | VolumeSection | DataSection | TableSection | Table2Section | HashSection:
353
+ """Open a section from a file-like object."""
354
+ descriptor = SectionDescriptor(fh)
286
355
 
287
- chunk_entry = self.entries[chunk]
288
- chunk_offset = self.base_offset + (chunk_entry & 0x7FFFFFFF)
289
- compressed = chunk_entry >> 31 == 1
356
+ if descriptor.type in ("header", "header2"):
357
+ return HeaderSection(descriptor)
290
358
 
291
- # EWF sucks
292
- # We don't know the chunk size, so try to determine it using the offset of the next chunk
293
- # When it's the last chunk in the table though, this becomes trickier.
294
- # We have to check if the chunk data is preceding the table, or if it's contained within the table section
295
- # Then we can calculate the chunk size using these offsets
296
- if chunk + 1 == self.num_entries:
297
- # The chunk data is stored before the table section
298
- if chunk_offset < self.section.offset:
299
- chunk_size = self.section.offset - chunk_offset
300
- # The chunk data is stored within the table section
301
- elif chunk_offset < self.section.offset + self.section.size:
302
- chunk_size = self.section.offset + self.section.size - chunk_offset
303
- else:
304
- raise EWFError("Unknown size of last chunk")
305
- else:
306
- chunk_size = self.base_offset + (self.entries[chunk + 1] & 0x7FFFFFFF) - chunk_offset
359
+ if descriptor.type in ("disk", "volume"):
360
+ return VolumeSection(descriptor)
307
361
 
308
- # Non compressed chunks have a 4 byte checksum
309
- if not compressed:
310
- chunk_size -= 4
362
+ if descriptor.type == "data":
363
+ return DataSection(descriptor)
311
364
 
312
- self.segment.fh.seek(chunk_offset)
313
- buf = self.segment.fh.read(chunk_size)
365
+ if descriptor.type == "table":
366
+ return TableSection(descriptor)
314
367
 
315
- if compressed:
316
- buf = zlib.decompress(buf)
368
+ if descriptor.type == "table2":
369
+ return Table2Section(descriptor)
317
370
 
318
- return buf
371
+ if descriptor.type == "hash":
372
+ return HashSection(descriptor)
319
373
 
320
- def read_sectors(self, sector: int, count: int) -> bytes:
321
- log.debug("TableSection::read_sectors(0x%x, 0x%x)", sector, count)
322
- result = []
374
+ return Section(descriptor)
323
375
 
324
- chunk_sector_count = self.segment.volume.sector_count
325
- sector_size = self.segment.volume.sector_size
376
+ @property
377
+ def type(self) -> str:
378
+ """The type of the section."""
379
+ return self.descriptor.type
326
380
 
327
- table_sector = sector - self.sector_offset
328
- table_chunk = table_sector // chunk_sector_count
381
+ @cached_property
382
+ def data(self) -> bytes:
383
+ """The raw data of the section."""
384
+ return self.descriptor.data
329
385
 
330
- while count > 0:
331
- table_sector_offset = table_sector % chunk_sector_count
332
- chunk_remaining_sectors = chunk_sector_count - table_sector_offset
333
- table_sectors = min(chunk_remaining_sectors, count)
334
386
 
335
- chunk_pos = table_sector_offset * sector_size
336
- chunk_end = chunk_pos + (table_sectors * sector_size)
387
+ class HeaderSection(Section):
388
+ """EWF header section."""
337
389
 
338
- buf = self.read_chunk(table_chunk)
339
- if chunk_pos != 0 or table_sectors != chunk_sector_count:
340
- buf = buf[chunk_pos:chunk_end]
341
- result.append(buf)
390
+ @cached_property
391
+ def data(self) -> str:
392
+ """The header data."""
393
+ data = zlib.decompress(self.descriptor.data)
394
+ return data.decode("utf16") if data[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE) else data.decode()
342
395
 
343
- count -= table_sectors
344
- table_sector += table_sectors
345
- table_chunk += 1
346
396
 
347
- return b"".join(result)
397
+ class VolumeSection(Section):
398
+ """EWF volume section."""
348
399
 
400
+ @cached_property
401
+ def data(self) -> c_ewf.VolumeSection | c_ewf.VolumeSectionSmart:
402
+ """The volume data."""
403
+ return (c_ewf.VolumeSection if self.descriptor.size == len(c_ewf.VolumeSection) else c_ewf.VolumeSectionSmart)(
404
+ self.descriptor.data
405
+ )
349
406
 
350
- class SectionDescriptor:
351
- def __init__(self, fh: BinaryIO):
352
- self.fh = fh
407
+ @property
408
+ def number_of_chunks(self) -> int:
409
+ """The number of chunks in the volume."""
410
+ return self.data.number_of_chunks
411
+
412
+ @property
413
+ def sectors_per_chunk(self) -> int:
414
+ """The number of sectors per chunk."""
415
+ return self.data.sectors_per_chunk
416
+
417
+ @property
418
+ def sector_size(self) -> int:
419
+ """The size of a sector in bytes."""
420
+ return self.data.bytes_per_sector
353
421
 
354
- self.offset = fh.tell()
355
- descriptor = c_ewf.EWFSectionDescriptor(fh)
356
- self.type = descriptor.type.rstrip(b"\x00")
357
- self.next = descriptor.next
358
- self.size = descriptor.size - len(c_ewf.EWFSectionDescriptor)
359
- self.checksum = descriptor.checksum
360
- self.data_offset = fh.tell()
422
+
423
+ class DataSection(Section):
424
+ """EWF data section."""
425
+
426
+ @cached_property
427
+ def data(self) -> c_ewf.DataSection:
428
+ """The data section."""
429
+ return c_ewf.DataSection(self.descriptor.data)
430
+
431
+
432
+ class TableSection(Section):
433
+ """EWF table section."""
361
434
 
362
435
  def __repr__(self) -> str:
363
436
  return (
364
- f"<SectionDescriptor "
365
- f"type={self.type} size={self.size:#x} offset={self.offset:#x} checksum={self.checksum:#x}>"
437
+ f"<{self.__class__.__name__} "
438
+ f"type={self.descriptor.type!r} size={self.descriptor.size:#x} "
439
+ f"number_of_entries={self.number_of_entries} base_offset={self.base_offset:#x}>"
366
440
  )
441
+
442
+ @cached_property
443
+ def data(self) -> c_ewf.TableSection:
444
+ """The table section."""
445
+ self.descriptor.fh.seek(self.descriptor.offset + len(c_ewf.SectionDescriptor))
446
+ return c_ewf.TableSection(self.descriptor.fh)
447
+
448
+ @cached_property
449
+ def entries(self) -> list[int]:
450
+ """The table entries."""
451
+ self.descriptor.fh.seek(self.descriptor.offset + len(c_ewf.SectionDescriptor) + len(c_ewf.TableSection))
452
+ return c_ewf.uint32[self.number_of_entries](self.descriptor.fh)
453
+
454
+ @property
455
+ def number_of_entries(self) -> int:
456
+ """The number of entries in the table."""
457
+ return self.data.number_of_entries
458
+
459
+ @property
460
+ def base_offset(self) -> int:
461
+ """The base offset of the table."""
462
+ return self.data.base_offset
463
+
464
+
465
+ class Table2Section(TableSection):
466
+ """EWF table2 section."""
467
+
468
+
469
+ class HashSection(Section):
470
+ """EWF hash section."""
471
+
472
+ @cached_property
473
+ def data(self) -> c_ewf.HashSection:
474
+ """The hash section."""
475
+ return c_ewf.HashSection(self.descriptor.data)
476
+
477
+ @property
478
+ def md5(self) -> str:
479
+ """The MD5 hash of the section."""
480
+ return self.data.md5.hex()
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from dissect.util.stream import AlignedStream
6
+
7
+ if TYPE_CHECKING:
8
+ from dissect.evidence.ewf.ewf import EWF
9
+
10
+
11
+ class EWFStream(AlignedStream):
12
+ """Provide a stitched stream over all EWF segments."""
13
+
14
+ def __init__(self, ewf: EWF):
15
+ self.ewf = ewf
16
+ super().__init__(ewf.size, ewf.chunk_size)
17
+
18
+ def _read(self, offset: int, length: int) -> bytes:
19
+ result = []
20
+
21
+ chunk, offset_in_chunk = divmod(offset, self.ewf.chunk_size)
22
+
23
+ while length > 0:
24
+ buf = self.ewf.read_chunk(chunk)
25
+ read_size = min(length, self.ewf.chunk_size - offset_in_chunk)
26
+ result.append(buf[offset_in_chunk : offset_in_chunk + read_size])
27
+
28
+ offset_in_chunk = 0
29
+ offset += read_size
30
+ length -= read_size
31
+ chunk += 1
32
+
33
+ return b"".join(result)
@@ -21,10 +21,6 @@ class NotASymlinkError(Error):
21
21
  pass
22
22
 
23
23
 
24
- class EWFError(Error):
25
- """Related to EWF (Expert Witness disk image Format)."""
26
-
27
-
28
24
  class InvalidSnapshot(Error):
29
25
  """Related to ASDF (Acquire Snapshot Data Format)."""
30
26
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.evidence
3
- Version: 3.14.dev2
3
+ Version: 3.14.dev4
4
4
  Summary: A Dissect module implementing a parsers for various forensic evidence file containers, currently: AD1, ASDF and EWF
5
5
  Author-email: Dissect Team <dissect@fox-it.com>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -1,7 +1,7 @@
1
1
  dissect/evidence/__init__.py,sha256=HBsn_m9aTzUqV0niqY6DV1GwKhtL2WfMf3i1LJFyxO4,257
2
- dissect/evidence/exception.py,sha256=wWN1bkKu5dHezB3HM55Fs6rwIZ9ajUGo57iM48bguv4,656
2
+ dissect/evidence/exception.py,sha256=e--4r9hL1hWm0BeXaIqxsXcrjl60QAfYV3c2Q8caHss,570
3
3
  dissect/evidence/ad1/__init__.py,sha256=p31RFzymZqk4dp2h8Ov9uAOk-lUqbT2rQujrfOFScTc,557
4
- dissect/evidence/ad1/ad1.py,sha256=1E_-bb2ePXz1Za6exrExnMkFyIJTDuVpaps5LNkhWpU,14993
4
+ dissect/evidence/ad1/ad1.py,sha256=xP9MVcgAPDb78Np9sojDrUDdLFBQ2nC90nGsFx47nJY,15598
5
5
  dissect/evidence/ad1/c_ad1.py,sha256=3MWCTONFBj99M7ZZbzLMZM393uJqPqljMdvZZpeG78A,6421
6
6
  dissect/evidence/ad1/c_ad1.pyi,sha256=m4m5VK1fRe4N5LNE-Cb1Datd1yutC6fptvKeq7fWH1k,7299
7
7
  dissect/evidence/ad1/stream.py,sha256=clcugxOaTcgXS0C5M694pnmIRFgEI2Ip32iqkdBJ5hM,2539
@@ -9,16 +9,17 @@ dissect/evidence/adcrypt/__init__.py,sha256=6OZAzN5vI9EGAyDz4BNP2YO_Ev0dyCILDKNF
9
9
  dissect/evidence/adcrypt/adcrypt.py,sha256=u_YABDws6Q92tMK6K7Lmx7BcLyPfSqmlXgONOzZ2Be0,5400
10
10
  dissect/evidence/adcrypt/c_adcrypt.py,sha256=rE17LHpx1pSbsIxAupEwM8ZFY4U9BODAY8aCyRljZoM,1000
11
11
  dissect/evidence/adcrypt/c_adcrypt.pyi,sha256=-m3voe_rrLWCScds9tl9CRzoVbGn7GqhN9O7yUICtGA,2195
12
- dissect/evidence/adcrypt/stream.py,sha256=gwsim1mzSJnskzDL-y7FRLUt-MuNezGkT_Un950Gnfc,1144
12
+ dissect/evidence/adcrypt/stream.py,sha256=Zea3Jaj5WSqxmQV4CS41Wk6OOtMVIPy2shHCviakCa8,1198
13
13
  dissect/evidence/asdf/__init__.py,sha256=Q7gUKk6Z5nR_DHnSo2ZfuUIlDNmARk420lC7A0GPwkg,213
14
14
  dissect/evidence/asdf/asdf.py,sha256=5FvEQ0KsaCYvloNGbtqlQin1t52AvZFBpbgh8jbEkRY,22239
15
15
  dissect/evidence/asdf/c_asdf.py,sha256=rfP2dVcJLxSbkNHZdDnCOM5Hs-ZKD_QY5e3iyxBQWQU,1803
16
16
  dissect/evidence/asdf/c_asdf.pyi,sha256=_-uhzA7yuXtH-22ERL-vHxoUYMnXHAXqvq71Zvxi_LQ,3244
17
17
  dissect/evidence/asdf/stream.py,sha256=v4oN8CHJu54Og_X5ZPvcGUOCLY-B8ApvQFsZjUy3Mbc,2637
18
- dissect/evidence/ewf/__init__.py,sha256=SbU1qjVHgwddhxFVU-WujpfWRE4SxJT46Fhen8lahuY,460
19
- dissect/evidence/ewf/c_ewf.py,sha256=DIZcUq3DK0V1HAjLQ-m6pzYhnsdllUN36BuMu7KEqQk,2115
20
- dissect/evidence/ewf/c_ewf.pyi,sha256=hQPBSL0SyJpKWrO6bDHdXTBG1NY0wP85NV9aFw_b0Ls,5860
21
- dissect/evidence/ewf/ewf.py,sha256=UIOxxsq_Auty0c64x-KG6d_sL2d3khnFvG4uBHxJPfA,12588
18
+ dissect/evidence/ewf/__init__.py,sha256=0dm4OWL-ECqlY4AiB9k61i6ncE6xtOTPzO2EkwBwqxs,465
19
+ dissect/evidence/ewf/c_ewf.py,sha256=EzJM6m3XsfZPbBDLMwJktEM7ASzxdbTZvIUtK37mID4,3354
20
+ dissect/evidence/ewf/c_ewf.pyi,sha256=hMCFtkjKpVyO9-nYvg6lntZtXVJCrCKAYsDxiZdeOxY,8687
21
+ dissect/evidence/ewf/ewf.py,sha256=P5yHEARvGFuaswE1v2bDkQ8FayPc3UU_1mV_AGSyftA,15400
22
+ dissect/evidence/ewf/stream.py,sha256=7MbPIkiaTAeBmXCfdtLDrTjvAochQHaDJIQYlgE3bUM,907
22
23
  dissect/evidence/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
24
  dissect/evidence/tools/adcrypt.py,sha256=7D37eyPfvBOaIn3v1S-bUk-yOix6FZSi29CuO6F4dBg,2721
24
25
  dissect/evidence/tools/util.py,sha256=js2OsSkDl8F4T-HHClQ-PW_EboUKIXW5ClDgYSOk9Wo,900
@@ -27,10 +28,10 @@ dissect/evidence/tools/asdf/dd.py,sha256=GPsEqyGBefXkUCHxZUTHDi1j2Nw1w39h2Qr-RoG
27
28
  dissect/evidence/tools/asdf/meta.py,sha256=bMb9pI49MgjeKhVXYPqhw74Cn0Sq-25YMzXU3cYaZro,2568
28
29
  dissect/evidence/tools/asdf/repair.py,sha256=8iDzS7wmVfg35AKolMzOpbJVBx-CMPqOvxPAlBkKc9w,3071
29
30
  dissect/evidence/tools/asdf/verify.py,sha256=zvxRvHNFZv6bicDE7RcT-jWgDKdYbLKMNTpGOwUJmfU,4161
30
- dissect_evidence-3.14.dev2.dist-info/licenses/COPYRIGHT,sha256=yExUrJwFMdmpUCxPrUiBR1pPQ_pGrr6hf3p231U6VnQ,303
31
- dissect_evidence-3.14.dev2.dist-info/licenses/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
32
- dissect_evidence-3.14.dev2.dist-info/METADATA,sha256=eDMOzSVL8wA0Jm5VALiclbpINmgl4Rbif43kutXZ4Cw,3340
33
- dissect_evidence-3.14.dev2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
34
- dissect_evidence-3.14.dev2.dist-info/entry_points.txt,sha256=Wwci5PSqdS9koYEtx9lIsmPRfnKRJUG2UPAKpsJfGOI,268
35
- dissect_evidence-3.14.dev2.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
36
- dissect_evidence-3.14.dev2.dist-info/RECORD,,
31
+ dissect_evidence-3.14.dev4.dist-info/licenses/COPYRIGHT,sha256=yExUrJwFMdmpUCxPrUiBR1pPQ_pGrr6hf3p231U6VnQ,303
32
+ dissect_evidence-3.14.dev4.dist-info/licenses/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
33
+ dissect_evidence-3.14.dev4.dist-info/METADATA,sha256=UbQPOFO8zJyy-CO1uyUEDPBt7IKtluq_ZEB-8WGa5J0,3340
34
+ dissect_evidence-3.14.dev4.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
35
+ dissect_evidence-3.14.dev4.dist-info/entry_points.txt,sha256=Wwci5PSqdS9koYEtx9lIsmPRfnKRJUG2UPAKpsJfGOI,268
36
+ dissect_evidence-3.14.dev4.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
37
+ dissect_evidence-3.14.dev4.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (84.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5