team-ljyzipelo

공개

암호 ZIP 해제와 AES 생성을 구현함

작성자
시로사키 하나
작성 시각
커밋
604583e358e1b7d39c6b557ea1000cb37d0a579a
부모
0f925a2
이 시점의 파일 보기

변경된 파일 17개

+1,023-41
수정experiments/rust-archive-worker/Cargo.lock+80-0
@@ -2,6 +2,18 @@
22# It is not intended for manual editing.
33version = 4
44
5추가: [[package]]
6추가: name = "aes"
7추가: version = "0.8.4"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
10추가: dependencies = [
11추가: "cfg-if",
12추가: "cipher",
13추가: "cpufeatures",
14추가: "zeroize",
15추가: ]
16추가:
517[[package]]
618name = "block-buffer"
719version = "0.10.4"
@@ -17,6 +29,16 @@ version = "1.0.5"
1729source = "registry+https://github.com/rust-lang/crates.io-index"
1830checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
1931
32추가: [[package]]
33추가: name = "cipher"
34추가: version = "0.4.4"
35추가: source = "registry+https://github.com/rust-lang/crates.io-index"
36추가: checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
37추가: dependencies = [
38추가: "crypto-common",
39추가: "inout",
40추가: ]
41추가:
2042[[package]]
2143name = "cpufeatures"
2244version = "0.2.17"
@@ -44,6 +66,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
4466dependencies = [
4567 "block-buffer",
4668 "crypto-common",
69추가: "subtle",
4770]
4871
4972[[package]]
@@ -56,12 +79,51 @@ dependencies = [
5679 "version_check",
5780]
5881
82추가: [[package]]
83추가: name = "hmac"
84추가: version = "0.12.1"
85추가: source = "registry+https://github.com/rust-lang/crates.io-index"
86추가: checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
87추가: dependencies = [
88추가: "digest",
89추가: ]
90추가:
91추가: [[package]]
92추가: name = "inout"
93추가: version = "0.1.4"
94추가: source = "registry+https://github.com/rust-lang/crates.io-index"
95추가: checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
96추가: dependencies = [
97추가: "generic-array",
98추가: ]
99추가:
59100[[package]]
60101name = "libc"
61102version = "0.2.191"
62103source = "registry+https://github.com/rust-lang/crates.io-index"
63104checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
64105
106추가: [[package]]
107추가: name = "pbkdf2"
108추가: version = "0.12.2"
109추가: source = "registry+https://github.com/rust-lang/crates.io-index"
110추가: checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
111추가: dependencies = [
112추가: "digest",
113추가: "hmac",
114추가: ]
115추가:
116추가: [[package]]
117추가: name = "sha1"
118추가: version = "0.10.7"
119추가: source = "registry+https://github.com/rust-lang/crates.io-index"
120추가: checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
121추가: dependencies = [
122추가: "cfg-if",
123추가: "cpufeatures",
124추가: "digest",
125추가: ]
126추가:
65127[[package]]
66128name = "sha2"
67129version = "0.10.9"
@@ -73,6 +135,12 @@ dependencies = [
73135 "digest",
74136]
75137
138추가: [[package]]
139추가: name = "subtle"
140추가: version = "2.6.1"
141추가: source = "registry+https://github.com/rust-lang/crates.io-index"
142추가: checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
143추가:
76144[[package]]
77145name = "typenum"
78146version = "1.20.1"
@@ -85,11 +153,23 @@ version = "0.9.5"
85153source = "registry+https://github.com/rust-lang/crates.io-index"
86154checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
87155
156추가: [[package]]
157추가: name = "zeroize"
158추가: version = "1.9.1"
159추가: source = "registry+https://github.com/rust-lang/crates.io-index"
160추가: checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
161추가:
88162[[package]]
89163name = "zipelo-archive-worker"
90164version = "0.1.0"
91165dependencies = [
166추가: "aes",
167추가: "hmac",
168추가: "pbkdf2",
169추가: "sha1",
92170 "sha2",
171추가: "subtle",
172추가: "zeroize",
93173 "zlib-rs",
94174]
95175
수정experiments/rust-archive-worker/Cargo.toml+6-0
@@ -7,6 +7,12 @@ publish = false
77autotests = false
88
99[dependencies]
10추가: aes = { version = "=0.8.4", features = ["zeroize"] }
11추가: hmac = "=0.12.1"
12추가: pbkdf2 = { version = "=0.12.2", default-features = false, features = ["hmac"] }
13추가: sha1 = "=0.10.7"
14추가: subtle = "=2.6.1"
15추가: zeroize = "=1.9.1"
1016sha2 = "=0.10.9"
1117zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] }
1218
수정experiments/rust-archive-worker/README.md+15-3
@@ -1,6 +1,6 @@
11# Rust archive worker
22
3삭제: 별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱 연결과 OS sandbox를 제공하는 단계는 아닙니다. 암호 기능은 capability=false이며 암호 ZIP 해제 및 AES 생성 요청은 UnsupportedFeature로 종료합니다.
3추가: 별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱 연결과 OS sandbox를 제공하는 단계는 아닙니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다.
44
55- ZIP32 Store/Deflate 목록, 해제, 생성, 기본 TAR/USTAR, GZ, TAR.GZ 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. ZIP64, 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
66- 입력은 최대 64 MiB, 해독/생성 출력은 최대 128 MiB, 항목은 최대 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 입력과 검증 완료 payload를 메모리에 보관해 모든 선택 출력의 CRC, 크기와 경로를 쓰기 전에 검사합니다. checkpoint마다 취소와 300초 한도를 확인합니다.
@@ -11,15 +11,25 @@
1111- 파일 sync/close는 게시 전에 확인합니다. 게시 후 부모 sync와 임시 파일 정리 실패는 게시 사실과 따로 보고합니다. Windows의 디렉터리 내구성은 Unconfirmed입니다. hard link의 결과가 불명확하면 CommitUncertain/Uncertain이며 자동 재시도나 rollback은 없습니다.
1212- 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 실파일 close/sync/link 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다.
1313
14추가: ## 암호 ZIP
15추가:
16추가: - AES는 [WinZip AE-1/AE-2 명세](https://www.winzip.com/en/support/aes-encryption/)의 method 99, 0x9901 추가 필드, PBKDF2-HMAC-SHA1 1000회, 16바이트 salt, AES-256 CTR와 HMAC-SHA1-80 형식을 사용합니다. 새 파일은 CRC를 노출하지 않는 AE-2입니다. AE-1은 인증과 CRC를 모두 검증합니다. AES-128/192와 PKWARE Strong Encryption은 미지원입니다.
17추가: - AES 인증값을 상수 시간 비교로 확인한 뒤 복호화/압축 해제합니다. 모든 파일의 인증, CRC, 크기와 경로 검증이 끝나기 전에는 출력하지 않습니다. ZIP 파일명과 목록 메타데이터는 암호화되거나 인증되지 않으며, 목록 성공은 파일 내용 인증 성공을 의미하지 않습니다.
18추가: - [ZipCrypto](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)는 기존 파일 해제만 지원합니다. 보안성이 약하며 암호학적 인증이 없습니다. 12바이트 헤더 검사 후 압축 스트림, 크기와 CRC를 확인합니다. 새 암호 ZIP은 AES-256만 생성합니다.
19추가: - 목록은 암호 없이 표시합니다. 해제 시 한 번 입력한 암호를 ZIP 전체에 적용하며 WrongPassword일 때 새 challenge_id로 최대 3회 요청합니다. 항목마다 다른 암호인 ZIP은 지원하지 않습니다. 헤더 확인값이 우연히 일치한 잘못된 암호는 Integrity로 끝날 수 있습니다. 인증 실패 후에는 다시 요청하거나 쓰지 않습니다.
20추가: - 생성은 PasswordPurpose::Encrypt로 한 번 요청하며 빈 암호는 거부합니다. 암호는 최대 1024 UTF-8 바이트입니다. 대기 중 Cancel도 처리하고, 답변 없이 입력 EOF가 오면 Protocol로 종료합니다. 기존 300초 작업 제한에 암호 입력 대기 시간도 포함됩니다.
21추가: - salt는 Linux /dev/urandom 또는 Windows BCryptGenRandom에서 얻으며 실패 시 생성을 중단합니다. 암호, 파생 키와 임시 복호화 버퍼는 zeroize로 정리하고 AES 키 일정의 zeroize 기능을 켭니다. HMAC 내부 상태, OS 메모리 복사본과 전체 평문 메모리의 완전 소거를 보장하지 않습니다.
22추가: - Python hashlib/hmac과 OpenSSL로 만든 AES 표본 4개, Info-ZIP으로 만든 ZipCrypto 표본 2개를 tests/ 아래에 보관합니다. 생성한 AES ZIP도 Linux에서 독립 Python/OpenSSL 검증기로 확인합니다. OpenSSL/Info-ZIP은 시험 도구이며 제품 의존성이 아닙니다.
23추가:
1424## 공유 codec
1525
16삭제: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 의존성 없는 LE codec입니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 2 원문입니다.
26추가: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 2 원문입니다.
1727
1828헤더는 ZAW1, version u16=1, kind u16, body length u32, reserved u32=0, job ID u64, sequence u64의 32바이트입니다. 양방향 sequence는 각각 0부터 시작합니다. body는 최대 1 MiB이며 한 방향당 최대 1,000,000프레임입니다. 잘린 프레임, 알 수 없는 tag, 잔여 payload, 잘못된 ID/sequence를 거부합니다.
1929
2030- kind: Start=1, Password=2, Cancel=3, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107입니다.
2131- body 필드는 `protocol.rs` 선언 순서입니다. enum은 선언 순서의 u8 tag이며 NativePath/SourceObject만 Unix=1, Windows=2입니다. bool/Option은 0 또는 1입니다. String/Vec는 u32 길이 뒤 원소를 저장하며 String은 UTF-8 바이트 길이입니다. `[u8; N]`은 길이 없이 N바이트입니다. action variant의 필드는 선언 순서를 사용합니다. Start는 action 뒤 limits(input u64, output u64, entries u32)입니다.
22삭제: - Password의 비밀 값은 Debug에 노출되지 않습니다. 이 버전은 PasswordRequired를 보내지 않으므로 들어온 Password는 Protocol 오류입니다. 비밀 값은 로그나 파일에 저장하지 않습니다.
32추가: - Password의 비밀 값은 Debug에 노출되지 않습니다. 암호 작업은 PasswordRequired의 challenge_id와 일치하는 Password를 한 번 받습니다. 오래된 ID, 중복 또는 요청 전 암호는 Protocol 오류입니다. 비밀 값은 로그나 파일에 저장하지 않습니다.
2333- CancelAck.request_sequence는 요청 헤더 sequence입니다. Requested, AlreadyRequested, TooLate, Finished는 최종 결과와 별개입니다. 종료와 경합한 요청은 읽히지 않아 응답이 없을 수 있습니다. Terminal은 마지막 프레임이며 Failed/Cancelled도 정상 전달 뒤 프로세스 exit=0입니다. 앱은 Terminal과 stdout/stderr EOF, child wait를 모두 확인해야 합니다.
2434
2535## 검증과 의존성
@@ -27,3 +37,5 @@
2737시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다.
2838
2939직접 의존성은 기존 zlib-rs=0.6.8와 허용된 RustCrypto sha2=0.10.9입니다. 2026-11-11에 확인한 [zlib-rs RUSTSEC-2024-0401](https://rustsec.org/advisories/RUSTSEC-2024-0401.html)은 >=0.4.0, [sha2 RUSTSEC-2021-0100](https://rustsec.org/advisories/RUSTSEC-2021-0100.html)은 >=0.9.8을 수정 버전으로 명시합니다. 선택 버전은 이 수정 범위에 들어갑니다. 이는 전체 전이 의존성의 취약점 부재나 완전한 보안 감사를 의미하지 않습니다.
40추가:
41추가: 암호 구현에 RustCrypto aes=0.8.4(zeroize 기능), hmac=0.12.1, pbkdf2=0.12.2, sha1=0.10.7, zeroize=1.9.1과 상수 시간 비교용 subtle=2.6.1을 추가했습니다. SHA-1은 ZIP 호환용 HMAC/KDF에만 사용합니다. 고정 버전과 전이 의존성은 Cargo.lock에 있습니다. 로컬 RustSec DB(1645308, 2026-10-23)의 해당 패키지 기록과 공개 RustSec 검색을 확인했지만 cargo-audit 명령이 없어 최신 DB 전체 자동 감사는 수행하지 못했습니다. 이 확인은 취약점 부재나 전체 보안 감사의 증거가 아닙니다.
수정experiments/rust-archive-worker/src/archive.rs+122-16
@@ -314,10 +314,45 @@ fn tar(
314314 validate_members(&members)?;
315315 Ok(members)
316316}
317추가: #[derive(Clone, Copy, PartialEq, Eq)]
318추가: struct AesExtra {
319추가: version: u16,
320추가: method: u16,
321추가: }
322추가: fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> {
323추가: let mut at = 0;
324추가: let mut found = None;
325추가: while at < extra.len() {
326추가: let tag = u16at(extra, at)?;
327추가: let len = u16at(extra, at + 2)? as usize;
328추가: let value = part(extra, at + 4, len)?;
329추가: if tag == 1 {
330추가: return Err(ErrorCode::UnsupportedFeature);
331추가: }
332추가: if tag == 0x9901 {
333추가: if found.is_some() || len < 7 {
334추가: return Err(ErrorCode::Integrity);
335추가: }
336추가: let version = u16at(value, 0)?;
337추가: let method = u16at(value, 5)?;
338추가: if !matches!(version, 1 | 2)
339추가: || &value[2..4] != b"AE"
340추가: || value[4] != 3
341추가: || !matches!(method, 0 | 8)
342추가: {
343추가: return Err(ErrorCode::UnsupportedFeature);
344추가: }
345추가: found = Some(AesExtra { version, method });
346추가: }
347추가: at += 4 + len;
348추가: }
349추가: Ok(found)
350추가: }
317351fn zip(
318352 input: &[u8],
319353 limits: Limits,
320354 decode: bool,
355추가: password: Option<&[u8]>,
321356 check: &mut impl FnMut() -> Result<()>,
322357) -> Result<Vec<Member>> {
323358 if input.len() < 22 {
@@ -363,7 +398,7 @@ fn zip(
363398 }
364399 let flags = u16at(h, 8)?;
365400 let method = u16at(h, 10)?;
366삭제: if flags & !0x080f != 0 || !matches!(method, 0 | 8) || u16at(h, 34)? != 0 {
401추가: if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) || u16at(h, 34)? != 0 {
367402 return Err(ErrorCode::UnsupportedFeature);
368403 }
369404 let crc = u32at(h, 16)?;
@@ -379,6 +414,14 @@ fn zip(
379414 let name_len = u16at(h, 28)? as usize;
380415 let extra_len = u16at(h, 30)? as usize;
381416 let comment_len = u16at(h, 32)? as usize;
417추가: let extra = aes_extra(part(input, at + 46 + name_len, extra_len)?)?;
418추가: let encrypted = flags & 1 != 0;
419추가: if (method == 99) != extra.is_some() || (method == 99 && !encrypted) {
420추가: return Err(ErrorCode::Integrity);
421추가: }
422추가: if extra.is_some_and(|e| e.version == 2) && crc != 0 {
423추가: return Err(ErrorCode::Integrity);
424추가: }
382425 let raw = part(input, at + 46, name_len)?;
383426 if flags & 0x0800 == 0 && !raw.is_ascii() {
384427 return Err(ErrorCode::UnsupportedFeature);
@@ -406,7 +449,10 @@ fn zip(
406449 }
407450 let ln = u16at(lh, 26)? as usize;
408451 let le = u16at(lh, 28)? as usize;
409삭제: if part(input, local + 30, ln)? != raw {
452추가: if aes_extra(part(input, local + 30 + ln, le)?)? != extra
453추가: || u16at(lh, 10)? != u16at(h, 12)?
454추가: || part(input, local + 30, ln)? != raw
455추가: {
410456 return Err(ErrorCode::Integrity);
411457 }
412458 if flags & 8 == 0
@@ -437,21 +483,43 @@ fn zip(
437483 return Err(ErrorCode::Integrity);
438484 }
439485 spans.push((local, stop));
440삭제: let encrypted = flags & 1 != 0;
441삭제: let data = if decode && !encrypted {
442삭제: let bytes = if method == 0 {
443삭제: if compressed != size {
486추가: if encrypted && compressed < if extra.is_some() { 28 } else { 12 } {
487추가: return Err(ErrorCode::Integrity);
488추가: }
489추가: let data = if decode {
490추가: let decrypted;
491추가: let packed = if encrypted {
492추가: let password = password.ok_or(ErrorCode::WrongPassword)?;
493추가: decrypted = if extra.is_some() {
494추가: crate::crypto::aes_decrypt(packed, password, check)?
495추가: } else {
496추가: let verifier = if flags & 8 != 0 {
497추가: (u16at(h, 12)? >> 8) as u8
498추가: } else {
499추가: (crc >> 24) as u8
500추가: };
501추가: crate::crypto::zipcrypto_decrypt(packed, password, verifier, check)?
502추가: };
503추가: decrypted.as_slice()
504추가: } else {
505추가: packed
506추가: };
507추가: let actual_method = extra.map_or(method, |e| e.method);
508추가: let bytes = if actual_method == 0 {
509추가: if packed.len() != size {
444510 return Err(ErrorCode::Integrity);
445511 }
446512 packed.to_vec()
447513 } else {
448514 let (out, used) = inflate(packed, false, size as u64, check)?;
449삭제: if used != compressed {
515추가: if used != packed.len() {
450516 return Err(ErrorCode::Integrity);
451517 }
452518 out
453519 };
454삭제: if bytes.len() != size || crc32(0, &bytes) != crc {
520추가: if bytes.len() != size
521추가: || (extra.is_none_or(|e| e.version == 1) && crc32(0, &bytes) != crc)
522추가: {
455523 return Err(ErrorCode::Integrity);
456524 }
457525 bytes
@@ -498,6 +566,15 @@ pub fn parse(
498566 limits: Limits,
499567 decode: bool,
500568 check: &mut impl FnMut() -> Result<()>,
569추가: ) -> Result<Catalog> {
570추가: parse_with_password(input, limits, decode, None, check)
571추가: }
572추가: pub fn parse_with_password(
573추가: input: &[u8],
574추가: limits: Limits,
575추가: decode: bool,
576추가: password: Option<&[u8]>,
577추가: check: &mut impl FnMut() -> Result<()>,
501578) -> Result<Catalog> {
502579 if !limits.valid() || input.len() as u64 > limits.input {
503580 return Err(ErrorCode::Limit);
@@ -505,7 +582,7 @@ pub fn parse(
505582 if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") {
506583 return Ok(Catalog {
507584 format: Format::Zip,
508삭제: members: zip(input, limits, decode, check)?,
585추가: members: zip(input, limits, decode, password, check)?,
509586 });
510587 }
511588 if input.starts_with(&[31, 139]) {
@@ -575,6 +652,15 @@ pub fn create_zip(
575652 method: Method,
576653 limits: Limits,
577654 check: &mut impl FnMut() -> Result<()>,
655추가: ) -> Result<Vec<u8>> {
656추가: create_zip_with_password(members, method, limits, None, check)
657추가: }
658추가: pub fn create_zip_with_password(
659추가: members: &[Member],
660추가: method: Method,
661추가: limits: Limits,
662추가: password: Option<&[u8]>,
663추가: check: &mut impl FnMut() -> Result<()>,
578664) -> Result<Vec<u8>> {
579665 if members.len() > limits.entries as usize || members.len() >= 65535 {
580666 return Err(ErrorCode::Limit);
@@ -593,7 +679,11 @@ pub fn create_zip(
593679 return Err(ErrorCode::UnsupportedFeature);
594680 }
595681 let name = m.entry.name.as_bytes();
596삭제: let crc = crc32(0, &m.data);
682추가: let crc = if password.is_some() {
683추가: 0
684추가: } else {
685추가: crc32(0, &m.data)
686추가: };
597687 let offset = out.len() as u32;
598688 let packed = match method {
599689 Method::Store => m.data.clone(),
@@ -603,9 +693,23 @@ pub fn create_zip(
603693 Method::Store => 0,
604694 Method::Deflate => 8,
605695 };
696추가: let mut extra = Vec::new();
697추가: let flags = if password.is_some() { 0x0801 } else { 0x0800 };
698추가: let version = if password.is_some() { 51 } else { 20 };
699추가: let (method, packed) = if let Some(password) = password {
700추가: put16(&mut extra, 0x9901);
701추가: put16(&mut extra, 7);
702추가: put16(&mut extra, 2);
703추가: extra.extend(b"AE");
704추가: extra.push(3);
705추가: put16(&mut extra, method);
706추가: (99, crate::crypto::aes_encrypt(&packed, password, check)?)
707추가: } else {
708추가: (method, packed)
709추가: };
606710 out.extend(b"PK\x03\x04");
607삭제: put16(&mut out, 20);
608삭제: put16(&mut out, 0x0800);
711추가: put16(&mut out, version);
712추가: put16(&mut out, flags);
609713 put16(&mut out, method);
610714 put16(&mut out, 0);
611715 put16(&mut out, 33);
@@ -613,13 +717,14 @@ pub fn create_zip(
613717 put32(&mut out, packed.len() as u32);
614718 put32(&mut out, m.data.len() as u32);
615719 put16(&mut out, name.len() as u16);
616삭제: put16(&mut out, 0);
720추가: put16(&mut out, extra.len() as u16);
617721 out.extend(name);
722추가: out.extend(&extra);
618723 bounded_append(&mut out, &packed, limits.output)?;
619724 cd.extend(b"PK\x01\x02");
620725 put16(&mut cd, 0x0314);
621삭제: put16(&mut cd, 20);
622삭제: put16(&mut cd, 0x0800);
726추가: put16(&mut cd, version);
727추가: put16(&mut cd, flags);
623728 put16(&mut cd, method);
624729 put16(&mut cd, 0);
625730 put16(&mut cd, 33);
@@ -627,13 +732,14 @@ pub fn create_zip(
627732 put32(&mut cd, packed.len() as u32);
628733 put32(&mut cd, m.data.len() as u32);
629734 put16(&mut cd, name.len() as u16);
630삭제: put16(&mut cd, 0);
735추가: put16(&mut cd, extra.len() as u16);
631736 put16(&mut cd, 0);
632737 put16(&mut cd, 0);
633738 put16(&mut cd, 0);
634739 put32(&mut cd, 0o100600 << 16);
635740 put32(&mut cd, offset);
636741 cd.extend(name);
742추가: cd.extend(&extra);
637743 }
638744 let offset = out.len();
639745 bounded_append(&mut out, &cd, limits.output)?;
추가experiments/rust-archive-worker/src/crypto.rs+174-0
@@ -0,0 +1,174 @@
1추가: use crate::protocol::ErrorCode;
2추가: use aes::{
3추가: Aes256,
4추가: cipher::{BlockEncrypt, KeyInit},
5추가: };
6추가: use hmac::{Hmac, Mac};
7추가: use sha1::Sha1;
8추가: use subtle::ConstantTimeEq;
9추가: use zeroize::{Zeroize, Zeroizing};
10추가:
11추가: type Result<T> = std::result::Result<T, ErrorCode>;
12추가: type Sha1Mac = Hmac<Sha1>;
13추가:
14추가: fn keys(password: &[u8], salt: &[u8]) -> Zeroizing<[u8; 66]> {
15추가: let mut result = Zeroizing::new([0; 66]);
16추가: pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, 1000, result.as_mut());
17추가: result
18추가: }
19추가: fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl FnMut() -> Result<()>) -> Result<()> {
20추가: let cipher = Aes256::new_from_slice(key).map_err(|_| ErrorCode::Internal)?;
21추가: for (index, chunk) in bytes.chunks_mut(16).enumerate() {
22추가: if index % 4096 == 0 {
23추가: check()?;
24추가: }
25추가: // WinZip은 1부터 시작하는 리틀엔디언 카운터를 사용함.
26추가: let mut block = ((index as u128) + 1).to_le_bytes().into();
27추가: cipher.encrypt_block(&mut block);
28추가: for (byte, mask) in chunk.iter_mut().zip(block.iter()) {
29추가: *byte ^= mask;
30추가: }
31추가: block.as_mut_slice().zeroize();
32추가: }
33추가: Ok(())
34추가: }
35추가: fn authenticate(
36추가: key: &[u8],
37추가: bytes: &[u8],
38추가: check: &mut impl FnMut() -> Result<()>,
39추가: ) -> Result<Sha1Mac> {
40추가: let mut mac = <Sha1Mac as Mac>::new_from_slice(key).map_err(|_| ErrorCode::Internal)?;
41추가: for chunk in bytes.chunks(65536) {
42추가: check()?;
43추가: mac.update(chunk);
44추가: }
45추가: Ok(mac)
46추가: }
47추가: pub(crate) fn aes_decrypt(
48추가: packed: &[u8],
49추가: password: &[u8],
50추가: check: &mut impl FnMut() -> Result<()>,
51추가: ) -> Result<Zeroizing<Vec<u8>>> {
52추가: if packed.len() < 28 {
53추가: return Err(ErrorCode::Integrity);
54추가: }
55추가: check()?;
56추가: let key = keys(password, &packed[..16]);
57추가: if !bool::from(key[64..].ct_eq(&packed[16..18])) {
58추가: return Err(ErrorCode::WrongPassword);
59추가: }
60추가: let end = packed.len() - 10;
61추가: // 인증이 성공하기 전에는 복호화나 압축 해제를 시작하지 않음.
62추가: authenticate(&key[32..64], &packed[18..end], check)?
63추가: .verify_truncated_left(&packed[end..])
64추가: .map_err(|_| ErrorCode::Integrity)?;
65추가: let mut bytes = Zeroizing::new(packed[18..end].to_vec());
66추가: ctr(&mut bytes, &key[..32], check)?;
67추가: Ok(bytes)
68추가: }
69추가: pub(crate) fn aes_encrypt(
70추가: packed: &[u8],
71추가: password: &[u8],
72추가: check: &mut impl FnMut() -> Result<()>,
73추가: ) -> Result<Vec<u8>> {
74추가: check()?;
75추가: let mut salt = [0; 16];
76추가: random(&mut salt)?;
77추가: let key = keys(password, &salt);
78추가: let mut bytes = packed.to_vec();
79추가: ctr(&mut bytes, &key[..32], check)?;
80추가: let mac = authenticate(&key[32..64], &bytes, check)?
81추가: .finalize()
82추가: .into_bytes();
83추가: let mut result = Vec::with_capacity(bytes.len() + 28);
84추가: result.extend(salt);
85추가: result.extend(&key[64..]);
86추가: result.extend(bytes);
87추가: result.extend(&mac[..10]);
88추가: Ok(result)
89추가: }
90추가: fn random(bytes: &mut [u8]) -> Result<()> {
91추가: #[cfg(target_os = "linux")]
92추가: {
93추가: use std::io::Read;
94추가: std::fs::File::open("/dev/urandom")
95추가: .and_then(|mut file| file.read_exact(bytes))
96추가: .map_err(|_| ErrorCode::Io)
97추가: }
98추가: #[cfg(windows)]
99추가: {
100추가: #[link(name = "bcrypt")]
101추가: unsafe extern "system" {
102추가: fn BCryptGenRandom(
103추가: algorithm: *mut core::ffi::c_void,
104추가: buffer: *mut u8,
105추가: length: u32,
106추가: flags: u32,
107추가: ) -> i32;
108추가: }
109추가: let len = u32::try_from(bytes.len()).map_err(|_| ErrorCode::Limit)?;
110추가: if unsafe { BCryptGenRandom(std::ptr::null_mut(), bytes.as_mut_ptr(), len, 2) } >= 0 {
111추가: Ok(())
112추가: } else {
113추가: Err(ErrorCode::Io)
114추가: }
115추가: }
116추가: #[cfg(not(any(target_os = "linux", windows)))]
117추가: {
118추가: let _ = bytes;
119추가: Err(ErrorCode::UnsupportedFeature)
120추가: }
121추가: }
122추가: const CRC_TABLE: [u32; 256] = {
123추가: let mut table = [0; 256];
124추가: let mut i = 0;
125추가: while i < 256 {
126추가: let mut crc = i as u32;
127추가: let mut bit = 0;
128추가: while bit < 8 {
129추가: crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1));
130추가: bit += 1;
131추가: }
132추가: table[i] = crc;
133추가: i += 1;
134추가: }
135추가: table
136추가: };
137추가: pub(crate) fn zipcrypto_decrypt(
138추가: packed: &[u8],
139추가: password: &[u8],
140추가: verifier: u8,
141추가: check: &mut impl FnMut() -> Result<()>,
142추가: ) -> Result<Zeroizing<Vec<u8>>> {
143추가: if packed.len() < 12 {
144추가: return Err(ErrorCode::Integrity);
145추가: }
146추가: let mut key = Zeroizing::new([0x12345678u32, 0x23456789, 0x34567890]);
147추가: fn update(key: &mut [u32; 3], byte: u8) {
148추가: key[0] = (key[0] >> 8) ^ CRC_TABLE[((key[0] as u8) ^ byte) as usize];
149추가: key[1] = key[1]
150추가: .wrapping_add(key[0] & 255)
151추가: .wrapping_mul(134775813)
152추가: .wrapping_add(1);
153추가: key[2] = (key[2] >> 8) ^ CRC_TABLE[((key[2] as u8) ^ ((key[1] >> 24) as u8)) as usize];
154추가: }
155추가: for &byte in password {
156추가: update(&mut key, byte);
157추가: }
158추가: let mut out = Zeroizing::new(Vec::with_capacity(packed.len() - 12));
159추가: for (index, &byte) in packed.iter().enumerate() {
160추가: if index % 65536 == 0 {
161추가: check()?;
162추가: }
163추가: let temp = key[2] | 2;
164추가: let plain = byte ^ ((temp.wrapping_mul(temp ^ 1) >> 8) as u8);
165추가: update(&mut key, plain);
166추가: if index == 11 && plain != verifier {
167추가: return Err(ErrorCode::WrongPassword);
168추가: }
169추가: if index >= 12 {
170추가: out.push(plain);
171추가: }
172추가: }
173추가: Ok(out)
174추가: }
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -1,4 +1,5 @@
11pub mod archive;
2추가: mod crypto;
23pub mod filesystem;
34pub mod protocol;
45pub mod runtime;
수정experiments/rust-archive-worker/src/protocol.rs+1-1
@@ -264,7 +264,7 @@ impl std::fmt::Debug for Secret {
264264}
265265impl Drop for Secret {
266266 fn drop(&mut self) {
267삭제: self.0.fill(0);
267추가: zeroize::Zeroize::zeroize(&mut self.0);
268268 }
269269}
270270#[derive(Debug)]
수정experiments/rust-archive-worker/src/runtime.rs+117-16
@@ -7,7 +7,7 @@ use crate::{
77use std::{
88 collections::BTreeSet,
99 io::{Read, Write},
10삭제: sync::{Arc, Mutex},
10추가: sync::{Arc, Condvar, Mutex},
1111 time::{Duration, Instant},
1212};
1313
@@ -17,13 +17,57 @@ struct State<W> {
1717 cancelled: bool,
1818 phase: u8,
1919 fault: Option<ErrorCode>,
20추가: challenge: Option<u64>,
21추가: password: Option<Secret>,
22추가: input_closed: bool,
2023}
2124struct Job<W> {
2225 state: Arc<Mutex<State<W>>>,
26추가: wake: Arc<Condvar>,
27추가: next_challenge: u64,
2328 started: Instant,
2429 terminal: Terminal,
2530}
2631impl<W: Write> Job<W> {
32추가: fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> {
33추가: self.check()?;
34추가: self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?;
35추가: let id = self.next_challenge;
36추가: let state_ref = Arc::clone(&self.state);
37추가: let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?;
38추가: state.challenge = Some(id);
39추가: state
40추가: .writer
41추가: .send(&Message::PasswordRequired {
42추가: challenge_id: id,
43추가: attempt,
44추가: purpose,
45추가: })
46추가: .map_err(|_| ErrorCode::Io)?;
47추가: loop {
48추가: if let Some(error) = state.fault {
49추가: return Err(error);
50추가: }
51추가: if state.cancelled {
52추가: return Err(ErrorCode::None);
53추가: }
54추가: if let Some(secret) = state.password.take() {
55추가: return Ok(secret);
56추가: }
57추가: if state.input_closed {
58추가: return Err(ErrorCode::Protocol);
59추가: }
60추가: if self.started.elapsed() > Duration::from_secs(300) {
61추가: return Err(ErrorCode::Limit);
62추가: }
63추가: state = self
64추가: .wake
65추가: .wait_timeout(state, Duration::from_millis(50))
66추가: .map_err(|_| ErrorCode::Internal)?
67추가: .0;
68추가: }
69추가: }
70추가:
2771 fn event(&mut self, event: Message) -> Result<()> {
2872 let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
2973 state.writer.send(&event).map_err(|_| {
@@ -136,7 +180,7 @@ impl<W: Write> Job<W> {
136180 }
137181 self.event(Message::Accepted {
138182 action: start.action.kind(),
139삭제: encryption: false,
183추가: encryption: true,
140184 })?;
141185 self.check()?;
142186 match start.action {
@@ -172,7 +216,7 @@ impl<W: Write> Job<W> {
172216 0,
173217 )?;
174218 let mut catalog =
175삭제: archive::parse(&snapshot.bytes, start.limits, extract, &mut || self.check())?;
219추가: archive::parse(&snapshot.bytes, start.limits, false, &mut || self.check())?;
176220 let list_id = ListId {
177221 catalog_version: 1,
178222 format: catalog.format,
@@ -218,9 +262,6 @@ impl<W: Write> Job<W> {
218262 Some(set)
219263 }
220264 };
221삭제: if catalog.members.iter().any(|m| m.entry.encrypted) {
222삭제: return Err(ErrorCode::UnsupportedFeature);
223삭제: }
224265 if catalog
225266 .members
226267 .iter()
@@ -228,6 +269,28 @@ impl<W: Write> Job<W> {
228269 {
229270 return Err(ErrorCode::UnsafePath);
230271 }
272추가: let encrypted = catalog.members.iter().any(|m| m.entry.encrypted);
273추가: for attempt in 1..=3 {
274추가: let secret = if encrypted {
275추가: Some(self.password(PasswordPurpose::Decrypt, attempt)?)
276추가: } else {
277추가: None
278추가: };
279추가: match archive::parse_with_password(
280추가: &snapshot.bytes,
281추가: start.limits,
282추가: true,
283추가: secret.as_ref().map(|s| s.0.as_slice()),
284추가: &mut || self.check(),
285추가: ) {
286추가: Ok(decoded) => {
287추가: catalog = decoded;
288추가: break;
289추가: }
290추가: Err(ErrorCode::WrongPassword) if attempt < 3 => continue,
291추가: Err(error) => return Err(error),
292추가: }
293추가: }
231294 if catalog.format == Format::Gzip {
232295 let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?;
233296 let checked = archive::valid_name(&name, false)
@@ -299,9 +362,6 @@ impl<W: Write> Job<W> {
299362 method,
300363 encryption,
301364 } => {
302삭제: if encryption != Encryption::None {
303삭제: return Err(ErrorCode::UnsupportedFeature);
304삭제: }
305365 if sources.len() > start.limits.entries as usize {
306366 return Err(ErrorCode::Limit);
307367 }
@@ -328,8 +388,22 @@ impl<W: Write> Job<W> {
328388 data: snapshot.bytes,
329389 });
330390 }
331삭제: let bytes =
332삭제: archive::create_zip(&members, method, start.limits, &mut || self.check())?;
391추가: let secret = if encryption == Encryption::Aes256 {
392추가: let secret = self.password(PasswordPurpose::Encrypt, 1)?;
393추가: if secret.0.is_empty() {
394추가: return Err(ErrorCode::InvalidRequest);
395추가: }
396추가: Some(secret)
397추가: } else {
398추가: None
399추가: };
400추가: let bytes = archive::create_zip_with_password(
401추가: &members,
402추가: method,
403추가: start.limits,
404추가: secret.as_ref().map(|s| s.0.as_slice()),
405추가: &mut || self.check(),
406추가: )?;
333407 let output = output_file.to_path()?;
334408 let leaf = output
335409 .file_name()
@@ -365,18 +439,23 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
365439 cancelled: false,
366440 phase: 0,
367441 fault: None,
442추가: challenge: None,
443추가: password: None,
444추가: input_closed: false,
368445 }));
446추가: let wake = Arc::new(Condvar::new());
447추가: let control_wake = Arc::clone(&wake);
369448 let control = Arc::clone(&state);
370449 std::thread::spawn(move || {
371450 loop {
372451 let command = reader.read();
373452 let Ok(Some((_, sequence, message))) = command else {
374삭제: if command.is_err() {
375삭제: if let Ok(mut state) = control.lock() {
376삭제: if state.phase < 2 {
377삭제: state.fault = Some(ErrorCode::Protocol);
378삭제: }
453추가: if let Ok(mut state) = control.lock() {
454추가: state.input_closed = true;
455추가: if command.is_err() && state.phase < 2 {
456추가: state.fault = Some(ErrorCode::Protocol);
379457 }
458추가: control_wake.notify_all();
380459 }
381460 break;
382461 };
@@ -387,6 +466,23 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
387466 break;
388467 }
389468 match message {
469추가: Message::Password {
470추가: challenge_id,
471추가: secret,
472추가: } => {
473추가: if state.phase != 0
474추가: || state.challenge != Some(challenge_id)
475추가: || state.password.is_some()
476추가: {
477추가: state.fault = Some(ErrorCode::Protocol);
478추가: } else {
479추가: state.challenge = None;
480추가: if !state.cancelled {
481추가: state.password = Some(secret);
482추가: }
483추가: }
484추가: control_wake.notify_all();
485추가: }
390486 Message::Cancel => {
391487 let status = match state.phase {
392488 2 => CancelStatus::Finished,
@@ -397,6 +493,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
397493 CancelStatus::Requested
398494 }
399495 };
496추가: control_wake.notify_all();
400497 if state
401498 .writer
402499 .send(&Message::CancelAck {
@@ -418,6 +515,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
418515 });
419516 let mut context = Job {
420517 state: Arc::clone(&state),
518추가: wake,
519추가: next_challenge: 0,
421520 started: Instant::now(),
422521 terminal: Terminal {
423522 outcome: Outcome::Completed,
@@ -443,6 +542,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
443542 .lock()
444543 .map_err(|_| std::io::Error::other("worker state poisoned"))?;
445544 state.phase = 2;
545추가: state.challenge = None;
546추가: state.password = None;
446547 if let Some(error) = state.fault.or(error) {
447548 context.terminal.error = error;
448549 context.terminal.outcome = if error == ErrorCode::None {
수정experiments/rust-archive-worker/src/wire.rs+2-1
@@ -495,7 +495,7 @@ impl<R: Read> Reader<R> {
495495 }
496496 self.job = Some(job);
497497 self.sequence += 1;
498삭제: let mut b = vec![0; len];
498추가: let mut b = zeroize::Zeroizing::new(vec![0; len]);
499499 self.input.read_exact(&mut b)?;
500500 let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?;
501501 self.terminal = matches!(message, Message::Terminal(_));
@@ -522,6 +522,7 @@ impl<W: Write> Writer<W> {
522522 return Err(invalid());
523523 }
524524 let (kind, b) = m.encode()?;
525추가: let b = zeroize::Zeroizing::new(b);
525526 let mut h = Vec::with_capacity(32);
526527 h.extend(b"ZAW1");
527528 h.extend(1u16.to_le_bytes());
추가tests/rust-archive-worker/encryption_fixtures.py+104-0
@@ -0,0 +1,104 @@
1추가: """공개 시험 암호로 독립 AES 표본 생성과 검증을 수행함."""
2추가:
3추가: import argparse
4추가: import hashlib
5추가: import hmac
6추가: import io
7추가: from pathlib import Path
8추가: import struct
9추가: import subprocess
10추가: import tempfile
11추가: import zipfile
12추가: import zlib
13추가:
14추가: ROOT = Path(__file__).resolve().parent
15추가: PASSWORD = b"fixture-password"
16추가: PAYLOAD = b"Zipelo encrypted interoperability\n" * 8
17추가:
18추가:
19추가: def crypt(data, key):
20추가: counters = b"".join(i.to_bytes(16, "little") for i in range(1, (len(data) + 15) // 16 + 1))
21추가: if not counters:
22추가: return b""
23추가: mask = subprocess.run(["openssl", "enc", "-aes-256-ecb", "-nopad", "-K", key.hex()],
24추가: input=counters, check=True, stdout=subprocess.PIPE).stdout
25추가: return bytes(a ^ b for a, b in zip(data, mask))
26추가:
27추가:
28추가: def aes_zip(version, method):
29추가: data = PAYLOAD
30추가: packed = data if method == 0 else zlib.compress(data, wbits=-15)
31추가: salt = bytes(range(16))
32추가: keys = hashlib.pbkdf2_hmac("sha1", PASSWORD, salt, 1000, 66)
33추가: cipher = crypt(packed, keys[:32])
34추가: encrypted = salt + keys[64:] + cipher + hmac.digest(keys[32:64], cipher, "sha1")[:10]
35추가: name = b"payload.bin"
36추가: crc = zlib.crc32(data) if version == 1 else 0
37추가: extra = struct.pack("<HHH2sBH", 0x9901, 7, version, b"AE", 3, method)
38추가: local = struct.pack("<IHHHHHIIIHH", 0x04034B50, 51, 0x801, 99, 0, 33,
39추가: crc, len(encrypted), len(data), len(name), len(extra)) + name + extra + encrypted
40추가: central = struct.pack("<IHHHHHHIIIHHHHHII", 0x02014B50, 0x333, 51, 0x801, 99, 0, 33,
41추가: crc, len(encrypted), len(data), len(name), len(extra), 0, 0, 0,
42추가: 0o100600 << 16, 0) + name + extra
43추가: return local + central + struct.pack("<IHHHHIIH", 0x06054B50, 0, 0, 1, 1,
44추가: len(central), len(local), 0)
45추가:
46추가:
47추가: def verify(path):
48추가: raw = Path(path).read_bytes()
49추가: with zipfile.ZipFile(io.BytesIO(raw)) as archive:
50추가: assert archive.infolist()
51추가: for info in archive.infolist():
52추가: assert info.compress_type == 99 and info.flag_bits & 1
53추가: fields = struct.unpack_from("<HHHHHIIIHH", raw, info.header_offset + 4)
54추가: name_len, extra_len = fields[-2:]
55추가: extra_at = info.header_offset + 30 + name_len
56추가: assert raw[extra_at:extra_at + extra_len] == info.extra
57추가: tag, length, version, vendor, strength, method = struct.unpack("<HHH2sBH", info.extra)
58추가: assert (tag, length, vendor, strength) == (0x9901, 7, b"AE", 3)
59추가: assert version in (1, 2)
60추가: start = extra_at + extra_len
61추가: encrypted = raw[start:start + info.compress_size]
62추가: keys = hashlib.pbkdf2_hmac("sha1", PASSWORD, encrypted[:16], 1000, 66)
63추가: assert hmac.compare_digest(keys[64:], encrypted[16:18])
64추가: cipher = encrypted[18:-10]
65추가: assert hmac.compare_digest(hmac.digest(keys[32:64], cipher, "sha1")[:10], encrypted[-10:])
66추가: packed = crypt(cipher, keys[:32])
67추가: data = packed if method == 0 else zlib.decompress(packed, wbits=-15)
68추가: assert len(data) == info.file_size
69추가: assert info.CRC == (0 if version == 2 else zlib.crc32(data))
70추가: assert data == PAYLOAD
71추가:
72추가:
73추가: def generate():
74추가: directory = ROOT / "fixtures"
75추가: for version in (1, 2):
76추가: for method, name in ((0, "store"), (8, "deflate")):
77추가: path = directory / f"aes{version}-{name}.zip"
78추가: path.write_bytes(aes_zip(version, method))
79추가: verify(path)
80추가: runs = ROOT / "runs"
81추가: runs.mkdir(exist_ok=True)
82추가: with tempfile.TemporaryDirectory(dir=runs) as scratch:
83추가: source = Path(scratch) / "payload.bin"
84추가: source.write_bytes(PAYLOAD)
85추가: for level, name in (("-0", "store"), ("-9", "deflate")):
86추가: result = subprocess.run(["zip", "-q", "-X", "-P", PASSWORD.decode(), level, "-", source.name],
87추가: cwd=scratch, check=True, stdout=subprocess.PIPE).stdout
88추가: with zipfile.ZipFile(io.BytesIO(result)) as archive:
89추가: assert archive.read("payload.bin", pwd=PASSWORD) == PAYLOAD
90추가: assert archive.infolist()[0].flag_bits & 8
91추가: (directory / f"zipcrypto-{name}.zip").write_bytes(result)
92추가:
93추가:
94추가: if __name__ == "__main__":
95추가: parser = argparse.ArgumentParser(description=__doc__)
96추가: parser.add_argument("--generate", action="store_true")
97추가: parser.add_argument("--verify", type=Path)
98추가: args = parser.parse_args()
99추가: if args.generate:
100추가: generate()
101추가: elif args.verify:
102추가: verify(args.verify)
103추가: else:
104추가: parser.error("--generate 또는 --verify가 필요함")
추가tests/rust-archive-worker/fixtures/aes1-deflate.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/aes1-store.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/aes2-deflate.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/aes2-store.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/zipcrypto-deflate.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/zipcrypto-store.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
수정tests/rust-archive-worker/main.rs+401-4
@@ -413,7 +413,7 @@ fn create_store_and_deflate_zip() {
413413 }
414414}
415415#[test]
416삭제: fn encrypted_creation_is_explicitly_unsupported() {
416추가: fn encryption_password_eof_is_protocol_failure() {
417417 let s = Scratch::new();
418418 let e = execute(Start {
419419 action: Action::CreateZip {
@@ -424,7 +424,7 @@ fn encrypted_creation_is_explicitly_unsupported() {
424424 },
425425 limits: Limits::default(),
426426 });
427삭제: assert_eq!(terminal(&e).error, ErrorCode::UnsupportedFeature);
427추가: assert_eq!(terminal(&e).error, ErrorCode::Protocol);
428428 assert!(!s.0.join("result.zip").exists());
429429}
430430#[test]
@@ -598,14 +598,14 @@ fn cancel_ack_and_terminal_are_distinct() {
598598}
599599
600600#[test]
601삭제: fn encrypted_zip_rejects_without_outputs() {
601추가: fn encrypted_zip_password_eof_preserves_outputs() {
602602 let mut bytes = include_bytes!("fixtures/store.zip").to_vec();
603603 bytes[6] |= 1;
604604 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
605605 bytes[central + 8] |= 1;
606606 let s = Scratch::new();
607607 let e = extract(&s, &bytes, None, Selection::All, None, Limits::default());
608삭제: assert_eq!(terminal(&e).error, ErrorCode::UnsupportedFeature);
608추가: assert_eq!(terminal(&e).error, ErrorCode::Protocol);
609609 assert_eq!(terminal(&e).publication, Publication::None);
610610 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
611611}
@@ -801,3 +801,400 @@ fn zero_payload_gzip_is_not_tar() {
801801 assert_eq!(list_id.format, Format::Gzip);
802802 }
803803}
804추가:
805추가: const ENCRYPTED_PAYLOAD: &[u8] = b"Zipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\n";
806추가: const TEST_PASSWORD: &[u8] = b"fixture-password";
807추가: const AES_ZIP: &[u8] = include_bytes!("fixtures/aes2-deflate.zip");
808추가: fn interactive(
809추가: start: Start,
810추가: mut respond: impl FnMut(u64, u32, PasswordPurpose) -> Vec<Message>,
811추가: ) -> Vec<Message> {
812추가: use std::{io::Read, sync::mpsc, time::Duration};
813추가: let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
814추가: .stdin(Stdio::piped())
815추가: .stdout(Stdio::piped())
816추가: .stderr(Stdio::piped())
817추가: .spawn()
818추가: .unwrap();
819추가: let mut writer = Some(Writer::new(child.stdin.take().unwrap(), 17));
820추가: writer
821추가: .as_mut()
822추가: .unwrap()
823추가: .send(&Message::Start(start))
824추가: .unwrap();
825추가: let output = child.stdout.take().unwrap();
826추가: let mut errors = child.stderr.take().unwrap();
827추가: let error_thread = std::thread::spawn(move || {
828추가: let mut bytes = Vec::new();
829추가: errors.read_to_end(&mut bytes).unwrap();
830추가: bytes
831추가: });
832추가: let (sender, receiver) = mpsc::channel();
833추가: let reader_thread = std::thread::spawn(move || {
834추가: let mut reader = Reader::new(output);
835추가: loop {
836추가: let event = reader.read().map(|v| {
837추가: v.map(|(job, _, message)| {
838추가: assert_eq!(job, 17);
839추가: message
840추가: })
841추가: });
842추가: let done = !matches!(event, Ok(Some(_)));
843추가: if sender.send(event).is_err() || done {
844추가: break;
845추가: }
846추가: }
847추가: });
848추가: let mut events = Vec::new();
849추가: loop {
850추가: let event = match receiver.recv_timeout(Duration::from_secs(10)) {
851추가: Ok(event) => event.unwrap(),
852추가: Err(error) => {
853추가: child.kill().unwrap();
854추가: child.wait().unwrap();
855추가: panic!("worker timeout: {error}");
856추가: }
857추가: };
858추가: let Some(event) = event else {
859추가: break;
860추가: };
861추가: if let Message::PasswordRequired {
862추가: challenge_id,
863추가: attempt,
864추가: purpose,
865추가: } = &event
866추가: {
867추가: let commands = respond(*challenge_id, *attempt, *purpose);
868추가: if commands.is_empty() {
869추가: writer = None;
870추가: } else {
871추가: for command in commands {
872추가: writer.as_mut().unwrap().send(&command).unwrap();
873추가: }
874추가: }
875추가: }
876추가: if matches!(event, Message::Terminal(_)) {
877추가: writer = None;
878추가: }
879추가: events.push(event);
880추가: }
881추가: assert!(child.wait().unwrap().success());
882추가: reader_thread.join().unwrap();
883추가: assert!(error_thread.join().unwrap().is_empty());
884추가: assert!(matches!(events.last(), Some(Message::Terminal(_))));
885추가: events
886추가: }
887추가: fn password_reply(id: u64, password: &[u8]) -> Vec<Message> {
888추가: vec![Message::Password {
889추가: challenge_id: id,
890추가: secret: Secret(password.to_vec()),
891추가: }]
892추가: }
893추가: fn encrypted_start(s: &Scratch, bytes: &[u8]) -> Start {
894추가: fs::write(s.0.join("input"), bytes).unwrap();
895추가: fs::create_dir(s.0.join("output")).unwrap();
896추가: #[cfg(unix)]
897추가: {
898추가: use std::os::unix::fs::PermissionsExt;
899추가: fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
900추가: }
901추가: Start {
902추가: action: Action::Extract {
903추가: archive: s.path("input"),
904추가: destination: s.path("output"),
905추가: selection: Selection::All,
906추가: list_id: None,
907추가: gzip_output_name: None,
908추가: },
909추가: limits: Limits::default(),
910추가: }
911추가: }
912추가: fn no_encrypted_output(s: &Scratch, events: &[Message], error: ErrorCode) {
913추가: assert_eq!(terminal(events).error, error, "{events:?}");
914추가: assert_eq!(terminal(events).publication, Publication::None);
915추가: assert_eq!(terminal(events).created_count, 0);
916추가: assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
917추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
918추가: }
919추가: #[test]
920추가: fn independent_encrypted_fixtures_list_and_extract() {
921추가: for bytes in [
922추가: include_bytes!("fixtures/aes1-store.zip").as_slice(),
923추가: include_bytes!("fixtures/aes1-deflate.zip").as_slice(),
924추가: include_bytes!("fixtures/aes2-store.zip").as_slice(),
925추가: AES_ZIP,
926추가: include_bytes!("fixtures/zipcrypto-store.zip").as_slice(),
927추가: include_bytes!("fixtures/zipcrypto-deflate.zip").as_slice(),
928추가: ] {
929추가: let s = Scratch::new();
930추가: let start = encrypted_start(&s, bytes);
931추가: let listing = execute(Start {
932추가: action: Action::List {
933추가: archive: s.path("input"),
934추가: },
935추가: limits: Limits::default(),
936추가: });
937추가: assert_eq!(
938추가: terminal(&listing).outcome,
939추가: Outcome::Completed,
940추가: "{listing:?}"
941추가: );
942추가: assert!(listing.iter().any(|e| matches!(
943추가: e,
944추가: Message::Entry(Entry {
945추가: encrypted: true,
946추가: ..
947추가: })
948추가: )));
949추가: assert!(
950추가: !listing
951추가: .iter()
952추가: .any(|e| matches!(e, Message::PasswordRequired { .. }))
953추가: );
954추가: let events = interactive(start, |id, attempt, purpose| {
955추가: assert_eq!(purpose, PasswordPurpose::Decrypt);
956추가: assert_eq!(attempt, 1);
957추가: password_reply(id, TEST_PASSWORD)
958추가: });
959추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
960추가: assert_eq!(
961추가: fs::read(s.0.join("output/payload.bin")).unwrap(),
962추가: ENCRYPTED_PAYLOAD
963추가: );
964추가: }
965추가: }
966추가: #[test]
967추가: fn aes_creation_uses_password_flow_and_independent_verification() {
968추가: for method in [Method::Store, Method::Deflate] {
969추가: let s = Scratch::new();
970추가: fs::write(s.0.join("source"), ENCRYPTED_PAYLOAD).unwrap();
971추가: let events = interactive(
972추가: Start {
973추가: action: Action::CreateZip {
974추가: sources: vec![Source {
975추가: path: s.path("source"),
976추가: archive_name: "payload.bin".into(),
977추가: }],
978추가: output_file: s.path("encrypted.zip"),
979추가: method,
980추가: encryption: Encryption::Aes256,
981추가: },
982추가: limits: Limits::default(),
983추가: },
984추가: |id, attempt, purpose| {
985추가: assert_eq!(purpose, PasswordPurpose::Encrypt);
986추가: assert_eq!(attempt, 1);
987추가: password_reply(id, TEST_PASSWORD)
988추가: },
989추가: );
990추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
991추가: assert!(events.iter().any(|e| matches!(
992추가: e,
993추가: Message::Accepted {
994추가: encryption: true,
995추가: ..
996추가: }
997추가: )));
998추가: #[cfg(target_os = "linux")]
999추가: {
1000추가: let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1001추가: .join("../../tests/rust-archive-worker/encryption_fixtures.py");
1002추가: assert!(
1003추가: Command::new("python3")
1004추가: .arg(helper)
1005추가: .arg("--verify")
1006추가: .arg(s.0.join("encrypted.zip"))
1007추가: .status()
1008추가: .unwrap()
1009추가: .success()
1010추가: );
1011추가: }
1012추가: let bytes = fs::read(s.0.join("encrypted.zip")).unwrap();
1013추가: let start = encrypted_start(&s, &bytes);
1014추가: let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1015추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1016추가: assert_eq!(
1017추가: fs::read(s.0.join("output/payload.bin")).unwrap(),
1018추가: ENCRYPTED_PAYLOAD
1019추가: );
1020추가: }
1021추가: }
1022추가: #[test]
1023추가: fn wrong_password_retries_with_new_challenge_then_succeeds() {
1024추가: let s = Scratch::new();
1025추가: let start = encrypted_start(&s, AES_ZIP);
1026추가: let mut previous = 0;
1027추가: let events = interactive(start, |id, attempt, _| {
1028추가: assert!(id > previous);
1029추가: previous = id;
1030추가: password_reply(
1031추가: id,
1032추가: if attempt == 1 {
1033추가: b"wrong"
1034추가: } else {
1035추가: TEST_PASSWORD
1036추가: },
1037추가: )
1038추가: });
1039추가: assert_eq!(terminal(&events).outcome, Outcome::Completed);
1040추가: assert_eq!(previous, 2);
1041추가: }
1042추가: #[test]
1043추가: fn wrong_password_attempts_are_bounded_without_writes() {
1044추가: let s = Scratch::new();
1045추가: let start = encrypted_start(&s, AES_ZIP);
1046추가: let mut attempts = 0;
1047추가: let events = interactive(start, |id, attempt, _| {
1048추가: attempts = attempt;
1049추가: password_reply(id, b"wrong")
1050추가: });
1051추가: assert_eq!(attempts, 3);
1052추가: no_encrypted_output(&s, &events, ErrorCode::WrongPassword);
1053추가: }
1054추가: #[test]
1055추가: fn cancellation_while_waiting_for_password_is_acknowledged() {
1056추가: let s = Scratch::new();
1057추가: let start = encrypted_start(&s, AES_ZIP);
1058추가: let events = interactive(start, |_, _, _| vec![Message::Cancel]);
1059추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
1060추가: assert!(events.iter().any(|e| matches!(
1061추가: e,
1062추가: Message::CancelAck {
1063추가: status: CancelStatus::Requested,
1064추가: ..
1065추가: }
1066추가: )));
1067추가: no_encrypted_output(&s, &events, ErrorCode::None);
1068추가: }
1069추가: #[test]
1070추가: fn stale_and_mismatched_password_challenges_fail_without_writes() {
1071추가: for stale in [false, true] {
1072추가: let s = Scratch::new();
1073추가: let start = encrypted_start(&s, AES_ZIP);
1074추가: let events = interactive(start, |id, attempt, _| {
1075추가: if stale && attempt == 1 {
1076추가: password_reply(id, b"wrong")
1077추가: } else {
1078추가: password_reply(if stale { id - 1 } else { id + 1 }, TEST_PASSWORD)
1079추가: }
1080추가: });
1081추가: no_encrypted_output(&s, &events, ErrorCode::Protocol);
1082추가: }
1083추가: }
1084추가: #[test]
1085추가: fn password_input_eof_fails_without_writes() {
1086추가: let s = Scratch::new();
1087추가: let start = encrypted_start(&s, AES_ZIP);
1088추가: let events = interactive(start, |_, _, _| vec![]);
1089추가: no_encrypted_output(&s, &events, ErrorCode::Protocol);
1090추가: }
1091추가: #[test]
1092추가: fn aes_authentication_failure_never_publishes_plaintext() {
1093추가: for tamper_tag in [false, true] {
1094추가: let mut bytes = AES_ZIP.to_vec();
1095추가: let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
1096추가: if tamper_tag {
1097추가: bytes[central - 1] ^= 1;
1098추가: } else {
1099추가: bytes[30 + b"payload.bin".len() + 11 + 18] ^= 1;
1100추가: }
1101추가: let s = Scratch::new();
1102추가: let start = encrypted_start(&s, &bytes);
1103추가: let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1104추가: no_encrypted_output(&s, &events, ErrorCode::Integrity);
1105추가: }
1106추가: }
1107추가: #[test]
1108추가: fn aes1_crc_and_extra_consistency_are_checked() {
1109추가: let original = include_bytes!("fixtures/aes1-store.zip");
1110추가: for corrupt_extra in [false, true] {
1111추가: let mut bytes = original.to_vec();
1112추가: let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
1113추가: if corrupt_extra {
1114추가: bytes[30 + b"payload.bin".len() + 4] = 2;
1115추가: } else {
1116추가: bytes[14] ^= 1;
1117추가: bytes[central + 16] ^= 1;
1118추가: }
1119추가: let s = Scratch::new();
1120추가: let start = encrypted_start(&s, &bytes);
1121추가: let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1122추가: no_encrypted_output(&s, &events, ErrorCode::Integrity);
1123추가: }
1124추가: }
1125추가: #[test]
1126추가: fn empty_aes_members_and_random_salts_round_trip() {
1127추가: let members = vec![archive::Member {
1128추가: entry: Entry {
1129추가: entry_id: 0,
1130추가: name: "empty".into(),
1131추가: kind: EntryKind::File,
1132추가: size: 0,
1133추가: compressed_size: 0,
1134추가: encrypted: false,
1135추가: },
1136추가: data: vec![],
1137추가: }];
1138추가: let a = archive::create_zip_with_password(
1139추가: &members,
1140추가: Method::Store,
1141추가: Limits::default(),
1142추가: Some(TEST_PASSWORD),
1143추가: &mut || Ok(()),
1144추가: )
1145추가: .unwrap();
1146추가: let b = archive::create_zip_with_password(
1147추가: &members,
1148추가: Method::Store,
1149추가: Limits::default(),
1150추가: Some(TEST_PASSWORD),
1151추가: &mut || Ok(()),
1152추가: )
1153추가: .unwrap();
1154추가: assert_ne!(a, b);
1155추가: let decoded = archive::parse_with_password(
1156추가: &a,
1157추가: Limits::default(),
1158추가: true,
1159추가: Some(TEST_PASSWORD),
1160추가: &mut || Ok(()),
1161추가: )
1162추가: .unwrap();
1163추가: assert!(decoded.members[0].data.is_empty());
1164추가: }
1165추가:
1166추가: #[test]
1167추가: fn password_racing_after_cancel_does_not_override_cancellation() {
1168추가: let s = Scratch::new();
1169추가: let start = encrypted_start(&s, AES_ZIP);
1170추가: let events = interactive(start, |id, _, _| {
1171추가: vec![
1172추가: Message::Cancel,
1173추가: Message::Password {
1174추가: challenge_id: id,
1175추가: secret: Secret(TEST_PASSWORD.to_vec()),
1176추가: },
1177추가: ]
1178추가: });
1179추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
1180추가: no_encrypted_output(&s, &events, ErrorCode::None);
1181추가: }
1182추가: #[test]
1183추가: fn empty_encryption_password_never_creates_zip() {
1184추가: let s = Scratch::new();
1185추가: let events = interactive(
1186추가: Start {
1187추가: action: Action::CreateZip {
1188추가: sources: vec![],
1189추가: output_file: s.path("empty.zip"),
1190추가: method: Method::Store,
1191추가: encryption: Encryption::Aes256,
1192추가: },
1193추가: limits: Limits::default(),
1194추가: },
1195추가: |id, _, _| password_reply(id, b""),
1196추가: );
1197추가: assert_eq!(terminal(&events).error, ErrorCode::InvalidRequest);
1198추가: assert_eq!(terminal(&events).publication, Publication::None);
1199추가: assert!(!s.0.join("empty.zip").exists());
1200추가: }