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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use std::cmp::min;

#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;

use hmac::crypto_mac::generic_array::{sequence::GenericSequence, ArrayLength, GenericArray};
use hmac::digest::{BlockInput, FixedOutput, Input, Reset};
use hmac::{Hmac, Mac};

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use crate::hash_primitive::{HashPrimitive, PRIMITIVES};


/// Tries to find the iteration count and the hash algorithm of the hash.
/// password - The password of the hash
/// hash - The hash itself
/// salt - The salt used in the derivation
/// max - The maximum number of iteration to try. Use 0 to try until aborted.
pub fn identify_all(
    password: &[u8],
    hash: &[u8],
    salt: &[u8],
    max: Option<usize>,
) -> Option<(HashPrimitive, usize)> {
    let found = Arc::new(AtomicBool::new(false));
    let runner = |primitive: &HashPrimitive| {
        Some((
            *primitive,
            primitive.get_identifier_threaded()(password, hash, salt, max, &found.clone())?,
        ))
    };

    // WASM doesn't "really" support threads for now, so this operation is not multithreaded in that case
    cfg_if::cfg_if! {
        if #[cfg(not(target_arch="wasm32"))] {
            return PRIMITIVES.into_par_iter().find_map_any(runner);
        }
        else {
            return PRIMITIVES.into_iter().iter.find_map(runner);
        }
    }
}

/// Tries to find the iteration count of the hash knowing its algorithm.
/// password - The password of the hash
/// hash - The hash itself
/// salt - The salt used in the derivation
/// max - The maximum number of iteration to try. Use 0 to try until aborted.
pub fn identify_iterations<T>(
    password: &[u8],
    hash: &[u8],
    salt: &[u8],
    max: Option<usize>,
) -> Option<usize>
    where
        T: Input + BlockInput + FixedOutput + Reset + Default + Clone,
        T::BlockSize: ArrayLength<u8>,
        T::OutputSize: ArrayLength<u8>,
{
    let found = Arc::new(AtomicBool::new(false));
    identify_iterations_threaded::<T>(password, hash, salt, max, &found)
}

/// Tries to find the iteration count of the hash knowing its algorithm. Takes an shared variable to know when to stop searching.
/// password - The password of the hash
/// hash - The hash itself
/// salt - The salt used in the derivation
/// max - The maximum number of iteration to try. Use 0 to try until aborted.
/// found - Shared variable to notify other threads if the hash has been identified.
pub fn identify_iterations_threaded<T>(
    password: &[u8],
    hash: &[u8],
    salt: &[u8],
    max: Option<usize>,
    found: &AtomicBool,
) -> Option<usize>
    where
        T: Input + BlockInput + FixedOutput + Reset + Default + Clone,
        T::BlockSize: ArrayLength<u8>,
        T::OutputSize: ArrayLength<u8>,
{
    // The accumulator is XORed after each iteration and compared to the value expected
    let mut accumulator = GenericArray::<u8, T::OutputSize>::generate(|_| 0);

    // The key is always the password, so we can instanciate it once and clone it.
    let prf = Hmac::<T>::new_varkey(&password).expect("HMAC accepts all key sizes");

    // First iteration
    // Only the first block needs to be validated, so we'll only need to use Salt | int(1)
    let mut data = salt.to_vec();
    data.extend_from_slice(&[0, 0, 0, 1]);

    let max = max.unwrap_or(std::usize::MAX);

    for i in 1..max {
        // HMAC the previous result with the hash as the key.
        let mut prf = prf.clone();
        prf.input(&data);
        data = prf.result().code().to_vec();

        // XOR the result into the accumulator
        for j in 0..min(accumulator.len(), data.len()) {
            accumulator[j] ^= data[j];
        }

        // Checks if the data is equal
        let mut is_equal = true;
        for j in 0..min(accumulator.len(), hash.len()) {
            if accumulator[j] != hash[j] {
                is_equal = false;
                break;
            }
        }

        // Returns the iteration count if found
        if is_equal {
            found.store(true, Ordering::Relaxed);
            return Some(i);
        }

        if found.load(Ordering::Relaxed) {
            return None;
        }
    }

    None
}

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

    #[test]
    fn test_identify_iterations_shorter_block_size() {
        use base64;
        use sha1::Sha1;

        let iterations = identify_iterations::<Sha1>(
            "password".as_bytes(),
            &base64::decode("EVeVmsezinX2Nv+J36elk6UA3mJFmJ4Nk2BWHnpbBCg=").unwrap(),
            &base64::decode("akL5xcl1RwlmlfAxkGp1NA==").unwrap(),
            None,
        )
            .unwrap();
        assert_eq!(iterations, 123);
    }

    #[test]
    fn test_identify_iterations_longer_block_size() {
        use base64;
        use sha2::Sha512;

        let iterations = identify_iterations::<Sha512>(
            "password".as_bytes(),
            &base64::decode("oElyEp3GgQxwdfE6uKfLqz40XB9CTF3iP003JhLPCuc=").unwrap(),
            &base64::decode("RtTNd9YXr4vQxiPQXooELA==").unwrap(),
            None,
        )
            .unwrap();
        assert_eq!(iterations, 123);
    }

    #[test]
    fn test_identify_all() {
        use base64;

        let (primitive, iterations) = identify_all(
            "password".as_bytes(),
            &base64::decode("Qp+q3JTY/2gnTSRHRNgn3g==").unwrap(),
            &base64::decode("al9TeCB42U/chevUbuaG1w==").unwrap(),
            None,
        )
            .unwrap();

        assert_eq!(primitive, HashPrimitive::HMACSHA256);
        assert_eq!(iterations, 125);
    }
}