team-ljyzipelo

공개
346줄9.5 KB
1//! Linux 이름 정책을 적용하는 메모리 전용 USTAR 후보임.
2//! 완료 전 payload를 노출하지 않으며 파일시스템과 worker를 사용하지 않음.
3
4use std::{fmt, time::Duration};
5
6use sha2::{Digest, Sha256};
7use subtle::ConstantTimeEq;
8
9mod budget;
10mod header;
11
12use budget::Budget;
13
14pub const MAX_BYTES: u64 = 16 * 1024 * 1024;
15pub const MAX_ENTRIES: usize = 1024;
16pub const MAX_PROCESSED: u64 = 128 * 1024 * 1024;
17pub const MAX_METADATA: u64 = 1024 * 1024;
18pub const MAX_DURATION: Duration = Duration::from_secs(300);
19pub const CHUNK: usize = 65_536;
20const BLOCK: usize = 512;
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum NamePolicy {
24 Linux,
25 Windows,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum Kind {
30 File,
31 Directory,
32}
33
34#[derive(Debug, PartialEq, Eq)]
35pub struct Entry {
36 pub id: String,
37 pub name: String,
38 pub kind: Kind,
39 pub size: u64,
40}
41
42#[derive(Clone, Copy, Debug)]
43pub struct Limits {
44 pub input: u64,
45 pub entries: usize,
46 pub processed: u64,
47 pub output: u64,
48 pub metadata: u64,
49 pub duration: Duration,
50}
51
52impl Default for Limits {
53 fn default() -> Self {
54 Self {
55 input: MAX_BYTES,
56 entries: MAX_ENTRIES,
57 processed: MAX_PROCESSED,
58 output: MAX_BYTES,
59 metadata: MAX_METADATA,
60 duration: MAX_DURATION,
61 }
62 }
63}
64
65#[derive(Debug)]
66pub struct Request {
67 pub input: Box<[u8]>,
68 pub policy: NamePolicy,
69 pub limits: Limits,
70}
71
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73pub struct Usage {
74 pub entries: usize,
75 pub processed: u64,
76 pub output: u64,
77}
78
79#[derive(Debug, PartialEq, Eq)]
80pub struct SelectedFile {
81 pub id: String,
82 pub bytes: Vec<u8>,
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum ContentVerification {
87 Unavailable,
88}
89
90#[derive(Debug)]
91pub struct Completed {
92 pub entries: Vec<Entry>,
93 pub files: Vec<SelectedFile>,
94 pub usage: Usage,
95 pub input_sha256: [u8; 32],
96 pub content_verification: ContentVerification,
97}
98
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub enum Failure {
101 InvalidRequest,
102 Unsupported,
103 Integrity,
104 UnsafePath,
105 Conflict,
106 Budget,
107 Cancelled,
108 Allocation,
109}
110
111#[derive(Debug, PartialEq, Eq)]
112pub enum Error<E> {
113 Reader(Failure),
114 Selection(E),
115}
116
117impl<E> From<Failure> for Error<E> {
118 fn from(value: Failure) -> Self {
119 Self::Reader(value)
120 }
121}
122
123impl<E: fmt::Display> fmt::Display for Error<E> {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 match self {
126 Self::Reader(value) => write!(f, "{value:?}"),
127 Self::Selection(value) => write!(f, "selection: {value}"),
128 }
129 }
130}
131
132impl<E: std::error::Error + 'static> std::error::Error for Error<E> {
133 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
134 match self {
135 Self::Selection(value) => Some(value),
136 Self::Reader(_) => None,
137 }
138 }
139}
140
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub enum Stop {
143 Cancelled,
144 Deadline,
145}
146
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub enum Checkpoint {
149 Start,
150 Read { pass: u8, offset: usize },
151 Entry { pass: u8, index: usize },
152 BeforeSelection,
153 AfterSelection,
154 SelectionId { index: usize },
155 Finish,
156}
157
158/// 선택 콜백은 1차 검증 목록만 받음. 실패 시 누적 파일 결과를 전부 폐기함.
159/// 콜백 자체의 할당, 실행 시간과 panic은 호출자가 관리함.
160pub fn read<E, S, C>(request: Request, select: S, checkpoint: C) -> Result<Completed, Error<E>>
161where
162 S: FnOnce(&[Entry]) -> Result<Vec<String>, E>,
163 C: FnMut(Checkpoint) -> Result<(), Stop>,
164{
165 let mut budget = Budget::new(request.limits, checkpoint)?;
166 budget.check(Checkpoint::Start)?;
167 if request.policy != NamePolicy::Linux {
168 return Err(Failure::Unsupported.into());
169 }
170 if request.input.len() as u64 > budget.limits.input {
171 return Err(Failure::Budget.into());
172 }
173 if request.input.len() < 2 * BLOCK || request.input.len() % BLOCK != 0 {
174 return Err(Failure::Integrity.into());
175 }
176 let mut entries = Vec::new();
177 let mut files = Vec::new();
178 let first = scan(&request.input, &mut entries, None, &mut files, &mut budget)?;
179 budget.check(Checkpoint::BeforeSelection)?;
180 let requested = select(&entries).map_err(Error::Selection)?;
181 budget.check(Checkpoint::AfterSelection)?;
182 if requested.len() > entries.len() {
183 return Err(Failure::Unsupported.into());
184 }
185 let mut selected = Vec::new();
186 selected
187 .try_reserve_exact(entries.len())
188 .map_err(|_| Failure::Allocation)?;
189 selected.resize(entries.len(), false);
190 for (index, id) in requested.iter().enumerate() {
191 budget.check(Checkpoint::SelectionId { index })?;
192 let position = entries
193 .iter()
194 .position(|entry| entry.id == *id)
195 .ok_or(Failure::Unsupported)?;
196 if selected[position] {
197 return Err(Failure::Unsupported.into());
198 }
199 selected[position] = true;
200 }
201 if !requested.is_empty() {
202 let second = scan(
203 &request.input,
204 &mut entries,
205 Some(&selected),
206 &mut files,
207 &mut budget,
208 )?;
209 if !bool::from(first[..].ct_eq(&second[..])) {
210 return Err(Failure::Integrity.into());
211 }
212 }
213 budget.check(Checkpoint::Finish)?;
214 Ok(Completed {
215 entries,
216 files,
217 usage: budget.usage,
218 input_sha256: first,
219 content_verification: ContentVerification::Unavailable,
220 })
221}
222
223fn scan<C>(
224 input: &[u8],
225 entries: &mut Vec<Entry>,
226 selected: Option<&[bool]>,
227 files: &mut Vec<SelectedFile>,
228 budget: &mut Budget<C>,
229) -> Result<[u8; 32], Failure>
230where
231 C: FnMut(Checkpoint) -> Result<(), Stop>,
232{
233 let pass = if selected.is_some() { 2 } else { 1 };
234 let mut hash = Sha256::new();
235 let mut offset = 0;
236 let mut metadata = 0;
237 let mut index = 0;
238 loop {
239 let block = take(input, &mut offset, BLOCK, pass, &mut hash, budget)?;
240 if header::zero(block) {
241 let end = take(input, &mut offset, BLOCK, pass, &mut hash, budget)?;
242 if !header::zero(end) {
243 return Err(Failure::Integrity);
244 }
245 while offset < input.len() {
246 let count = CHUNK.min(input.len() - offset);
247 let trailing = take(input, &mut offset, count, pass, &mut hash, budget)?;
248 if !header::zero(trailing) {
249 return Err(Failure::Integrity);
250 }
251 }
252 break;
253 }
254 budget.check(Checkpoint::Entry { pass, index })?;
255 if selected.is_none() {
256 budget.entry()?;
257 }
258 if budget.limits.metadata - metadata < BLOCK as u64 {
259 return Err(Failure::Budget);
260 }
261 metadata += BLOCK as u64;
262 let entry = header::parse(block, index)?;
263 if selected.is_some() && entries.get(index) != Some(&entry) {
264 return Err(Failure::Integrity);
265 }
266 header::unique(&entry, &entries[..index])?;
267 let remaining = (input.len() - offset) as u64;
268 let padding = (BLOCK as u64 - entry.size % BLOCK as u64) % BLOCK as u64;
269 if entry.size > remaining || padding > remaining - entry.size {
270 return Err(Failure::Integrity);
271 }
272 let emit = selected.is_some_and(|ids| ids[index]) && entry.kind == Kind::File;
273 let mut bytes = Vec::new();
274 if emit {
275 budget.output(entry.size)?;
276 bytes
277 .try_reserve_exact(entry.size as usize)
278 .map_err(|_| Failure::Allocation)?;
279 }
280 let mut body = entry.size as usize;
281 while body > 0 {
282 let count = CHUNK.min(body);
283 let chunk = take(input, &mut offset, count, pass, &mut hash, budget)?;
284 if emit {
285 bytes.extend_from_slice(chunk);
286 }
287 budget.check(Checkpoint::Read { pass, offset })?;
288 body -= count;
289 }
290 if padding > 0 {
291 let chunk = take(
292 input,
293 &mut offset,
294 padding as usize,
295 pass,
296 &mut hash,
297 budget,
298 )?;
299 if !header::zero(chunk) {
300 return Err(Failure::Integrity);
301 }
302 }
303 if emit {
304 files.try_reserve(1).map_err(|_| Failure::Allocation)?;
305 files.push(SelectedFile {
306 id: header::copy(&entry.id)?,
307 bytes,
308 });
309 }
310 if selected.is_none() {
311 entries.try_reserve(1).map_err(|_| Failure::Allocation)?;
312 entries.push(entry);
313 }
314 index += 1;
315 }
316 budget.check(Checkpoint::Read { pass, offset })?;
317 if selected.is_some() && entries.len() != index {
318 return Err(Failure::Integrity);
319 }
320 Ok(hash.finalize().into())
321}
322
323fn take<'a, C>(
324 input: &'a [u8],
325 offset: &mut usize,
326 count: usize,
327 pass: u8,
328 hash: &mut Sha256,
329 budget: &mut Budget<C>,
330) -> Result<&'a [u8], Failure>
331where
332 C: FnMut(Checkpoint) -> Result<(), Stop>,
333{
334 budget.check(Checkpoint::Read {
335 pass,
336 offset: *offset,
337 })?;
338 if count > input.len() - *offset {
339 return Err(Failure::Integrity);
340 }
341 budget.processed(count as u64)?;
342 let bytes = &input[*offset..*offset + count];
343 hash.update(bytes);
344 *offset += count;
345 Ok(bytes)
346}