1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
mod file_type;
use clap::Parser;
use file_type::{Archive, FileType, Jpg, Wmv};
use std::error::Error;
use std::fs::File;
use std::io::{self};

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct Args {
    /// Name of the zip file
    #[clap(short, long)]
    zip_name: String,

    /// Name of the file to test extraction with
    #[clap(short, long)]
    file_name: String,

    /// File type
    #[clap(short = 't', long)]
    file_type: String,
}

pub struct Config {
    pub archive: zip::ZipArchive<File>,
    pub file_name: String,
    pub file_type: FileTypeKind,
}

#[derive(PartialEq, Eq, Debug)]
pub enum FileTypeKind {
    Wmv(Wmv),
    Jpg(Jpg),
    Archive(Archive),
}

impl Config {
    pub fn new(args: Args) -> Result<Config, Box<dyn Error>> {
        let zip_path = std::path::Path::new(&args.zip_name);
        let ft = &args.file_type.as_str();
        let file_type = determine_file_type((&ft).to_string())?;
        let zip_file = std::fs::File::open(&zip_path)?;
        let mut archive = zip::ZipArchive::new(zip_file)?;
        check_if_file_exists_in_zip(&mut archive, &args.file_name)?;
        Ok(Config {
            archive,
            file_name: args.file_name,
            file_type: file_type.into(),
        })
    }
}

pub fn run<R>(mut config: Config, input: R) -> Result<String, &'static str>
where
    R: io::BufRead,
{
    let mut correct_password = String::from("");
    for line in input.lines() {
        match line {
            Ok(password) => {
                if let Ok(file) = config
                    .archive
                    .by_name_decrypt(&config.file_name, password.as_bytes())
                {
                    match file {
                        Ok(f) => {
                            let data: Vec<u8> = io::Read::bytes(f)
                                .take(12) // arbitrary number
                                .map(|d| d.unwrap_or(0))
                                .collect();
                            if is_header_valid(&data, &config.file_type) {
                                correct_password = password.to_string();
                                break;
                            }
                        }
                        Err(_) => (),
                    }
                }
            }
            Err(_) => break,
        }
    }
    if correct_password.is_empty() {
        return Err("Password wasn't found");
    }
    Ok(correct_password.to_string())
}

fn is_header_valid(data: &[u8], file_type: &FileTypeKind) -> bool {
    match file_type {
        FileTypeKind::Wmv(wmv) => wmv.is_valid_header(data),
        FileTypeKind::Jpg(jpg) => jpg.is_valid_header(data),
        FileTypeKind::Archive(archive) => archive.is_valid_header(data),
    }
}

fn determine_file_type(file_type: String) -> Result<FileTypeKind, &'static str> {
    match file_type.to_ascii_lowercase().as_str() {
        "asf" | "wma" | "wmv" => Ok(FileTypeKind::Wmv(Wmv::new())),
        "jpg" => Ok(FileTypeKind::Jpg(Jpg::new())),
        "zip" | "apk" | "jar" => Ok(FileTypeKind::Archive(Archive::new())),
        _ => Err("Unknown file type"),
    }
}

fn check_if_file_exists_in_zip(
    archive: &mut zip::ZipArchive<File>,
    file_name: &str,
) -> Result<(), &'static str> {
    match archive.by_name_decrypt(file_name, b"") {
        Ok(_) => Ok(()),
        Err(ref e) if e.to_string() == zip::result::ZipError::FileNotFound.to_string() => {
            Err("File doesn't exist in zip")
        }
        Err(_) => Err("Something went wrong locating file in zip"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_determine_file_type() {
        if let Ok(jpg) = determine_file_type(String::from("jpg")) {
            assert_eq!(
                std::mem::discriminant(&jpg),
                std::mem::discriminant(&FileTypeKind::Jpg(Jpg { header: vec![0] }))
            );
        } else {
            panic!("file type not determined correctly");
        }
    }

    #[test]
    fn test_is_valid_header() {
        let data = [0xFF, 0xD8];
        let file_type = determine_file_type((String::from("jpg")).to_string()).unwrap();
        let ft = match file_type {
            FileTypeKind::Jpg(jpg) => jpg,
            _ => panic!("Unable to determine file type"),
        };
        assert_eq!(true, ft.is_valid_header(&data));
    }

    #[test]
    fn test_blitz_zip_with_jpg() {
        let mut test_zip_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        test_zip_path.push("test_data/cats.zip");
        let config = Config::new(Args {
            zip_name: test_zip_path.into_os_string().into_string().unwrap(),
            file_name: String::from("kitten.jpg"),
            file_type: String::from("jpg"),
        })
        .unwrap();
        let wordlist = std::fs::read_to_string("test_data/wordlist.txt")
            .expect("Something went wrong reading the file");
        if let Ok(password) = run(config, wordlist.as_bytes()) {
            assert_eq!(password, "fun");
        } else {
            panic!("password validation logic faild");
        }
    }
}