암호 ZIP 해제와 AES 생성을 구현함
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
604583e358e1b7d39c6b557ea1000cb37d0a579a- 부모
- 0f925a2
변경된 파일 17개
+1,023-41| @@ -2,6 +2,18 @@ | ||
| 2 | 2 | # It is not intended for manual editing. |
| 3 | 3 | version = 4 |
| 4 | 4 | |
| 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 | 추가: | |
| 5 | 17 | [[package]] |
| 6 | 18 | name = "block-buffer" |
| 7 | 19 | version = "0.10.4" |
| @@ -17,6 +29,16 @@ version = "1.0.5" | ||
| 17 | 29 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 18 | 30 | checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" |
| 19 | 31 | |
| 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 | 추가: | |
| 20 | 42 | [[package]] |
| 21 | 43 | name = "cpufeatures" |
| 22 | 44 | version = "0.2.17" |
| @@ -44,6 +66,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" | ||
| 44 | 66 | dependencies = [ |
| 45 | 67 | "block-buffer", |
| 46 | 68 | "crypto-common", |
| 69 | 추가: "subtle", | |
| 47 | 70 | ] |
| 48 | 71 | |
| 49 | 72 | [[package]] |
| @@ -56,12 +79,51 @@ dependencies = [ | ||
| 56 | 79 | "version_check", |
| 57 | 80 | ] |
| 58 | 81 | |
| 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 | 추가: | |
| 59 | 100 | [[package]] |
| 60 | 101 | name = "libc" |
| 61 | 102 | version = "0.2.191" |
| 62 | 103 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 63 | 104 | checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" |
| 64 | 105 | |
| 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 | 추가: | |
| 65 | 127 | [[package]] |
| 66 | 128 | name = "sha2" |
| 67 | 129 | version = "0.10.9" |
| @@ -73,6 +135,12 @@ dependencies = [ | ||
| 73 | 135 | "digest", |
| 74 | 136 | ] |
| 75 | 137 | |
| 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 | 추가: | |
| 76 | 144 | [[package]] |
| 77 | 145 | name = "typenum" |
| 78 | 146 | version = "1.20.1" |
| @@ -85,11 +153,23 @@ version = "0.9.5" | ||
| 85 | 153 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 86 | 154 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" |
| 87 | 155 | |
| 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 | 추가: | |
| 88 | 162 | [[package]] |
| 89 | 163 | name = "zipelo-archive-worker" |
| 90 | 164 | version = "0.1.0" |
| 91 | 165 | dependencies = [ |
| 166 | 추가: "aes", | |
| 167 | 추가: "hmac", | |
| 168 | 추가: "pbkdf2", | |
| 169 | 추가: "sha1", | |
| 92 | 170 | "sha2", |
| 171 | 추가: "subtle", | |
| 172 | 추가: "zeroize", | |
| 93 | 173 | "zlib-rs", |
| 94 | 174 | ] |
| 95 | 175 |
| @@ -7,6 +7,12 @@ publish = false | ||
| 7 | 7 | autotests = false |
| 8 | 8 | |
| 9 | 9 | [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" | |
| 10 | 16 | sha2 = "=0.10.9" |
| 11 | 17 | zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] } |
| 12 | 18 |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # Rust archive worker |
| 2 | 2 | |
| 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 생성을 지원합니다. | |
| 4 | 4 | |
| 5 | 5 | - ZIP32 Store/Deflate 목록, 해제, 생성, 기본 TAR/USTAR, GZ, TAR.GZ 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. ZIP64, 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다. |
| 6 | 6 | - 입력은 최대 64 MiB, 해독/생성 출력은 최대 128 MiB, 항목은 최대 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 입력과 검증 완료 payload를 메모리에 보관해 모든 선택 출력의 CRC, 크기와 경로를 쓰기 전에 검사합니다. checkpoint마다 취소와 300초 한도를 확인합니다. |
| @@ -11,15 +11,25 @@ | ||
| 11 | 11 | - 파일 sync/close는 게시 전에 확인합니다. 게시 후 부모 sync와 임시 파일 정리 실패는 게시 사실과 따로 보고합니다. Windows의 디렉터리 내구성은 Unconfirmed입니다. hard link의 결과가 불명확하면 CommitUncertain/Uncertain이며 자동 재시도나 rollback은 없습니다. |
| 12 | 12 | - 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 실파일 close/sync/link 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다. |
| 13 | 13 | |
| 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 | 추가: | |
| 14 | 24 | ## 공유 codec |
| 15 | 25 | |
| 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 원문입니다. | |
| 17 | 27 | |
| 18 | 28 | 헤더는 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를 거부합니다. |
| 19 | 29 | |
| 20 | 30 | - kind: Start=1, Password=2, Cancel=3, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107입니다. |
| 21 | 31 | - 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 오류입니다. 비밀 값은 로그나 파일에 저장하지 않습니다. | |
| 23 | 33 | - CancelAck.request_sequence는 요청 헤더 sequence입니다. Requested, AlreadyRequested, TooLate, Finished는 최종 결과와 별개입니다. 종료와 경합한 요청은 읽히지 않아 응답이 없을 수 있습니다. Terminal은 마지막 프레임이며 Failed/Cancelled도 정상 전달 뒤 프로세스 exit=0입니다. 앱은 Terminal과 stdout/stderr EOF, child wait를 모두 확인해야 합니다. |
| 24 | 34 | |
| 25 | 35 | ## 검증과 의존성 |
| @@ -27,3 +37,5 @@ | ||
| 27 | 37 | 시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다. |
| 28 | 38 | |
| 29 | 39 | 직접 의존성은 기존 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 전체 자동 감사는 수행하지 못했습니다. 이 확인은 취약점 부재나 전체 보안 감사의 증거가 아닙니다. |
| @@ -314,10 +314,45 @@ fn tar( | ||
| 314 | 314 | validate_members(&members)?; |
| 315 | 315 | Ok(members) |
| 316 | 316 | } |
| 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 | 추가: } | |
| 317 | 351 | fn zip( |
| 318 | 352 | input: &[u8], |
| 319 | 353 | limits: Limits, |
| 320 | 354 | decode: bool, |
| 355 | 추가: password: Option<&[u8]>, | |
| 321 | 356 | check: &mut impl FnMut() -> Result<()>, |
| 322 | 357 | ) -> Result<Vec<Member>> { |
| 323 | 358 | if input.len() < 22 { |
| @@ -363,7 +398,7 @@ fn zip( | ||
| 363 | 398 | } |
| 364 | 399 | let flags = u16at(h, 8)?; |
| 365 | 400 | 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 { | |
| 367 | 402 | return Err(ErrorCode::UnsupportedFeature); |
| 368 | 403 | } |
| 369 | 404 | let crc = u32at(h, 16)?; |
| @@ -379,6 +414,14 @@ fn zip( | ||
| 379 | 414 | let name_len = u16at(h, 28)? as usize; |
| 380 | 415 | let extra_len = u16at(h, 30)? as usize; |
| 381 | 416 | 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 | 추가: } | |
| 382 | 425 | let raw = part(input, at + 46, name_len)?; |
| 383 | 426 | if flags & 0x0800 == 0 && !raw.is_ascii() { |
| 384 | 427 | return Err(ErrorCode::UnsupportedFeature); |
| @@ -406,7 +449,10 @@ fn zip( | ||
| 406 | 449 | } |
| 407 | 450 | let ln = u16at(lh, 26)? as usize; |
| 408 | 451 | 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 | 추가: { | |
| 410 | 456 | return Err(ErrorCode::Integrity); |
| 411 | 457 | } |
| 412 | 458 | if flags & 8 == 0 |
| @@ -437,21 +483,43 @@ fn zip( | ||
| 437 | 483 | return Err(ErrorCode::Integrity); |
| 438 | 484 | } |
| 439 | 485 | 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 { | |
| 444 | 510 | return Err(ErrorCode::Integrity); |
| 445 | 511 | } |
| 446 | 512 | packed.to_vec() |
| 447 | 513 | } else { |
| 448 | 514 | let (out, used) = inflate(packed, false, size as u64, check)?; |
| 449 | 삭제: if used != compressed { | |
| 515 | 추가: if used != packed.len() { | |
| 450 | 516 | return Err(ErrorCode::Integrity); |
| 451 | 517 | } |
| 452 | 518 | out |
| 453 | 519 | }; |
| 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 | 추가: { | |
| 455 | 523 | return Err(ErrorCode::Integrity); |
| 456 | 524 | } |
| 457 | 525 | bytes |
| @@ -498,6 +566,15 @@ pub fn parse( | ||
| 498 | 566 | limits: Limits, |
| 499 | 567 | decode: bool, |
| 500 | 568 | 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<()>, | |
| 501 | 578 | ) -> Result<Catalog> { |
| 502 | 579 | if !limits.valid() || input.len() as u64 > limits.input { |
| 503 | 580 | return Err(ErrorCode::Limit); |
| @@ -505,7 +582,7 @@ pub fn parse( | ||
| 505 | 582 | if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") { |
| 506 | 583 | return Ok(Catalog { |
| 507 | 584 | format: Format::Zip, |
| 508 | 삭제: members: zip(input, limits, decode, check)?, | |
| 585 | 추가: members: zip(input, limits, decode, password, check)?, | |
| 509 | 586 | }); |
| 510 | 587 | } |
| 511 | 588 | if input.starts_with(&[31, 139]) { |
| @@ -575,6 +652,15 @@ pub fn create_zip( | ||
| 575 | 652 | method: Method, |
| 576 | 653 | limits: Limits, |
| 577 | 654 | 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<()>, | |
| 578 | 664 | ) -> Result<Vec<u8>> { |
| 579 | 665 | if members.len() > limits.entries as usize || members.len() >= 65535 { |
| 580 | 666 | return Err(ErrorCode::Limit); |
| @@ -593,7 +679,11 @@ pub fn create_zip( | ||
| 593 | 679 | return Err(ErrorCode::UnsupportedFeature); |
| 594 | 680 | } |
| 595 | 681 | 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 | 추가: }; | |
| 597 | 687 | let offset = out.len() as u32; |
| 598 | 688 | let packed = match method { |
| 599 | 689 | Method::Store => m.data.clone(), |
| @@ -603,9 +693,23 @@ pub fn create_zip( | ||
| 603 | 693 | Method::Store => 0, |
| 604 | 694 | Method::Deflate => 8, |
| 605 | 695 | }; |
| 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 | 추가: }; | |
| 606 | 710 | 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); | |
| 609 | 713 | put16(&mut out, method); |
| 610 | 714 | put16(&mut out, 0); |
| 611 | 715 | put16(&mut out, 33); |
| @@ -613,13 +717,14 @@ pub fn create_zip( | ||
| 613 | 717 | put32(&mut out, packed.len() as u32); |
| 614 | 718 | put32(&mut out, m.data.len() as u32); |
| 615 | 719 | put16(&mut out, name.len() as u16); |
| 616 | 삭제: put16(&mut out, 0); | |
| 720 | 추가: put16(&mut out, extra.len() as u16); | |
| 617 | 721 | out.extend(name); |
| 722 | 추가: out.extend(&extra); | |
| 618 | 723 | bounded_append(&mut out, &packed, limits.output)?; |
| 619 | 724 | cd.extend(b"PK\x01\x02"); |
| 620 | 725 | put16(&mut cd, 0x0314); |
| 621 | 삭제: put16(&mut cd, 20); | |
| 622 | 삭제: put16(&mut cd, 0x0800); | |
| 726 | 추가: put16(&mut cd, version); | |
| 727 | 추가: put16(&mut cd, flags); | |
| 623 | 728 | put16(&mut cd, method); |
| 624 | 729 | put16(&mut cd, 0); |
| 625 | 730 | put16(&mut cd, 33); |
| @@ -627,13 +732,14 @@ pub fn create_zip( | ||
| 627 | 732 | put32(&mut cd, packed.len() as u32); |
| 628 | 733 | put32(&mut cd, m.data.len() as u32); |
| 629 | 734 | put16(&mut cd, name.len() as u16); |
| 630 | 삭제: put16(&mut cd, 0); | |
| 735 | 추가: put16(&mut cd, extra.len() as u16); | |
| 631 | 736 | put16(&mut cd, 0); |
| 632 | 737 | put16(&mut cd, 0); |
| 633 | 738 | put16(&mut cd, 0); |
| 634 | 739 | put32(&mut cd, 0o100600 << 16); |
| 635 | 740 | put32(&mut cd, offset); |
| 636 | 741 | cd.extend(name); |
| 742 | 추가: cd.extend(&extra); | |
| 637 | 743 | } |
| 638 | 744 | let offset = out.len(); |
| 639 | 745 | bounded_append(&mut out, &cd, limits.output)?; |
| @@ -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 | 추가: } |
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | pub mod archive; |
| 2 | 추가: mod crypto; | |
| 2 | 3 | pub mod filesystem; |
| 3 | 4 | pub mod protocol; |
| 4 | 5 | pub mod runtime; |
| @@ -264,7 +264,7 @@ impl std::fmt::Debug for Secret { | ||
| 264 | 264 | } |
| 265 | 265 | impl Drop for Secret { |
| 266 | 266 | fn drop(&mut self) { |
| 267 | 삭제: self.0.fill(0); | |
| 267 | 추가: zeroize::Zeroize::zeroize(&mut self.0); | |
| 268 | 268 | } |
| 269 | 269 | } |
| 270 | 270 | #[derive(Debug)] |
| @@ -7,7 +7,7 @@ use crate::{ | ||
| 7 | 7 | use std::{ |
| 8 | 8 | collections::BTreeSet, |
| 9 | 9 | io::{Read, Write}, |
| 10 | 삭제: sync::{Arc, Mutex}, | |
| 10 | 추가: sync::{Arc, Condvar, Mutex}, | |
| 11 | 11 | time::{Duration, Instant}, |
| 12 | 12 | }; |
| 13 | 13 | |
| @@ -17,13 +17,57 @@ struct State<W> { | ||
| 17 | 17 | cancelled: bool, |
| 18 | 18 | phase: u8, |
| 19 | 19 | fault: Option<ErrorCode>, |
| 20 | 추가: challenge: Option<u64>, | |
| 21 | 추가: password: Option<Secret>, | |
| 22 | 추가: input_closed: bool, | |
| 20 | 23 | } |
| 21 | 24 | struct Job<W> { |
| 22 | 25 | state: Arc<Mutex<State<W>>>, |
| 26 | 추가: wake: Arc<Condvar>, | |
| 27 | 추가: next_challenge: u64, | |
| 23 | 28 | started: Instant, |
| 24 | 29 | terminal: Terminal, |
| 25 | 30 | } |
| 26 | 31 | impl<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 | 추가: | |
| 27 | 71 | fn event(&mut self, event: Message) -> Result<()> { |
| 28 | 72 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 29 | 73 | state.writer.send(&event).map_err(|_| { |
| @@ -136,7 +180,7 @@ impl<W: Write> Job<W> { | ||
| 136 | 180 | } |
| 137 | 181 | self.event(Message::Accepted { |
| 138 | 182 | action: start.action.kind(), |
| 139 | 삭제: encryption: false, | |
| 183 | 추가: encryption: true, | |
| 140 | 184 | })?; |
| 141 | 185 | self.check()?; |
| 142 | 186 | match start.action { |
| @@ -172,7 +216,7 @@ impl<W: Write> Job<W> { | ||
| 172 | 216 | 0, |
| 173 | 217 | )?; |
| 174 | 218 | 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())?; | |
| 176 | 220 | let list_id = ListId { |
| 177 | 221 | catalog_version: 1, |
| 178 | 222 | format: catalog.format, |
| @@ -218,9 +262,6 @@ impl<W: Write> Job<W> { | ||
| 218 | 262 | Some(set) |
| 219 | 263 | } |
| 220 | 264 | }; |
| 221 | 삭제: if catalog.members.iter().any(|m| m.entry.encrypted) { | |
| 222 | 삭제: return Err(ErrorCode::UnsupportedFeature); | |
| 223 | 삭제: } | |
| 224 | 265 | if catalog |
| 225 | 266 | .members |
| 226 | 267 | .iter() |
| @@ -228,6 +269,28 @@ impl<W: Write> Job<W> { | ||
| 228 | 269 | { |
| 229 | 270 | return Err(ErrorCode::UnsafePath); |
| 230 | 271 | } |
| 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 | 추가: } | |
| 231 | 294 | if catalog.format == Format::Gzip { |
| 232 | 295 | let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; |
| 233 | 296 | let checked = archive::valid_name(&name, false) |
| @@ -299,9 +362,6 @@ impl<W: Write> Job<W> { | ||
| 299 | 362 | method, |
| 300 | 363 | encryption, |
| 301 | 364 | } => { |
| 302 | 삭제: if encryption != Encryption::None { | |
| 303 | 삭제: return Err(ErrorCode::UnsupportedFeature); | |
| 304 | 삭제: } | |
| 305 | 365 | if sources.len() > start.limits.entries as usize { |
| 306 | 366 | return Err(ErrorCode::Limit); |
| 307 | 367 | } |
| @@ -328,8 +388,22 @@ impl<W: Write> Job<W> { | ||
| 328 | 388 | data: snapshot.bytes, |
| 329 | 389 | }); |
| 330 | 390 | } |
| 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 | 추가: )?; | |
| 333 | 407 | let output = output_file.to_path()?; |
| 334 | 408 | let leaf = output |
| 335 | 409 | .file_name() |
| @@ -365,18 +439,23 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 365 | 439 | cancelled: false, |
| 366 | 440 | phase: 0, |
| 367 | 441 | fault: None, |
| 442 | 추가: challenge: None, | |
| 443 | 추가: password: None, | |
| 444 | 추가: input_closed: false, | |
| 368 | 445 | })); |
| 446 | 추가: let wake = Arc::new(Condvar::new()); | |
| 447 | 추가: let control_wake = Arc::clone(&wake); | |
| 369 | 448 | let control = Arc::clone(&state); |
| 370 | 449 | std::thread::spawn(move || { |
| 371 | 450 | loop { |
| 372 | 451 | let command = reader.read(); |
| 373 | 452 | 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); | |
| 379 | 457 | } |
| 458 | 추가: control_wake.notify_all(); | |
| 380 | 459 | } |
| 381 | 460 | break; |
| 382 | 461 | }; |
| @@ -387,6 +466,23 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 387 | 466 | break; |
| 388 | 467 | } |
| 389 | 468 | 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 | 추가: } | |
| 390 | 486 | Message::Cancel => { |
| 391 | 487 | let status = match state.phase { |
| 392 | 488 | 2 => CancelStatus::Finished, |
| @@ -397,6 +493,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 397 | 493 | CancelStatus::Requested |
| 398 | 494 | } |
| 399 | 495 | }; |
| 496 | 추가: control_wake.notify_all(); | |
| 400 | 497 | if state |
| 401 | 498 | .writer |
| 402 | 499 | .send(&Message::CancelAck { |
| @@ -418,6 +515,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 418 | 515 | }); |
| 419 | 516 | let mut context = Job { |
| 420 | 517 | state: Arc::clone(&state), |
| 518 | 추가: wake, | |
| 519 | 추가: next_challenge: 0, | |
| 421 | 520 | started: Instant::now(), |
| 422 | 521 | terminal: Terminal { |
| 423 | 522 | outcome: Outcome::Completed, |
| @@ -443,6 +542,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 443 | 542 | .lock() |
| 444 | 543 | .map_err(|_| std::io::Error::other("worker state poisoned"))?; |
| 445 | 544 | state.phase = 2; |
| 545 | 추가: state.challenge = None; | |
| 546 | 추가: state.password = None; | |
| 446 | 547 | if let Some(error) = state.fault.or(error) { |
| 447 | 548 | context.terminal.error = error; |
| 448 | 549 | context.terminal.outcome = if error == ErrorCode::None { |
| @@ -495,7 +495,7 @@ impl<R: Read> Reader<R> { | ||
| 495 | 495 | } |
| 496 | 496 | self.job = Some(job); |
| 497 | 497 | self.sequence += 1; |
| 498 | 삭제: let mut b = vec![0; len]; | |
| 498 | 추가: let mut b = zeroize::Zeroizing::new(vec![0; len]); | |
| 499 | 499 | self.input.read_exact(&mut b)?; |
| 500 | 500 | let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?; |
| 501 | 501 | self.terminal = matches!(message, Message::Terminal(_)); |
| @@ -522,6 +522,7 @@ impl<W: Write> Writer<W> { | ||
| 522 | 522 | return Err(invalid()); |
| 523 | 523 | } |
| 524 | 524 | let (kind, b) = m.encode()?; |
| 525 | 추가: let b = zeroize::Zeroizing::new(b); | |
| 525 | 526 | let mut h = Vec::with_capacity(32); |
| 526 | 527 | h.extend(b"ZAW1"); |
| 527 | 528 | h.extend(1u16.to_le_bytes()); |
| @@ -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가 필요함") |
바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기| @@ -413,7 +413,7 @@ fn create_store_and_deflate_zip() { | ||
| 413 | 413 | } |
| 414 | 414 | } |
| 415 | 415 | #[test] |
| 416 | 삭제: fn encrypted_creation_is_explicitly_unsupported() { | |
| 416 | 추가: fn encryption_password_eof_is_protocol_failure() { | |
| 417 | 417 | let s = Scratch::new(); |
| 418 | 418 | let e = execute(Start { |
| 419 | 419 | action: Action::CreateZip { |
| @@ -424,7 +424,7 @@ fn encrypted_creation_is_explicitly_unsupported() { | ||
| 424 | 424 | }, |
| 425 | 425 | limits: Limits::default(), |
| 426 | 426 | }); |
| 427 | 삭제: assert_eq!(terminal(&e).error, ErrorCode::UnsupportedFeature); | |
| 427 | 추가: assert_eq!(terminal(&e).error, ErrorCode::Protocol); | |
| 428 | 428 | assert!(!s.0.join("result.zip").exists()); |
| 429 | 429 | } |
| 430 | 430 | #[test] |
| @@ -598,14 +598,14 @@ fn cancel_ack_and_terminal_are_distinct() { | ||
| 598 | 598 | } |
| 599 | 599 | |
| 600 | 600 | #[test] |
| 601 | 삭제: fn encrypted_zip_rejects_without_outputs() { | |
| 601 | 추가: fn encrypted_zip_password_eof_preserves_outputs() { | |
| 602 | 602 | let mut bytes = include_bytes!("fixtures/store.zip").to_vec(); |
| 603 | 603 | bytes[6] |= 1; |
| 604 | 604 | let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap(); |
| 605 | 605 | bytes[central + 8] |= 1; |
| 606 | 606 | let s = Scratch::new(); |
| 607 | 607 | 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); | |
| 609 | 609 | assert_eq!(terminal(&e).publication, Publication::None); |
| 610 | 610 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 611 | 611 | } |
| @@ -801,3 +801,400 @@ fn zero_payload_gzip_is_not_tar() { | ||
| 801 | 801 | assert_eq!(list_id.format, Format::Gzip); |
| 802 | 802 | } |
| 803 | 803 | } |
| 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 | 추가: } |