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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*-
* Scram-rs
* Copyright (C) 2021  Aleksandr Morozov
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

use super::scram_error::{ScramResult, ScramRuntimeError, ScramErrorCode};
use super::{scram_error, scram_error_map};

use super::scram_common::ScramCommon;
use super::scram_hashing::ScramHashing;

/// A authentification callback returns this enum. 
/// 
/// The callback should use implemented functions to generate the result!
pub enum ScramPassword
{
    /// Default state for initialization!
    /// Should never be returned from the authentification backend.
    None,

    /// User was not found in auth DB, anyway in order to avoid timing
    /// attacks, the fake data will be generated
    UserNotFound
    {
        /// salted and hashed (SHA-?) password
        salted_hashed_password: Vec<u8>,
        /// plaintext salt used (non base64)
        salt: Vec<u8>,
        /// iteration count
        iterations: u32,
    },

    /// User was found with or without salt data
    UserPasswordData
    {
        /// salted and hashed (SHA-?) password
        salted_hashed_password: Vec<u8>,
        /// plaintext salt used (non base64)
        salt: Vec<u8>,
        /// iteration count
        iterations: u32,
    }
}

impl ScramPassword
{
    /// A default initialization. A program which utilizes this crate should 
    /// never use this function.
    pub fn default() -> Self
    {
        return Self::None;
    }

    /// Internal function to generate mock salt.
    fn scram_mock_salt() -> ScramResult<Vec<u8>>
    {
        //generate mock auth nonce (todo: to statically created)
        let mock_auth_nonce = ScramCommon::sc_random(ScramCommon::MOCK_AUTH_NONCE_LEN)?;

        return Ok(mock_auth_nonce);
    }

    /// A program which utilizes this crate should call this function if user was not
    /// found in DB. The execution should not be interrupted.
    /// 
    /// # Throws
    /// 
    /// May throw an error.
    pub fn not_found<S: ScramHashing>() -> ScramResult<Self>
    {
        // generate fake data
        let salt = ScramPassword::scram_mock_salt()?;

        let password_raw = ScramCommon::sc_random(ScramCommon::MOCK_AUTH_NONCE_LEN)?;

        let salted_password = S::derive(&password_raw, &salt, ScramCommon::SCRAM_DEFAULT_SALT_ITER)?;

        let ret = Self::UserNotFound
            {
                salted_hashed_password: salted_password,
                salt: salt,
                iterations: ScramCommon::SCRAM_DEFAULT_SALT_ITER,
            };

        return Ok(ret);
    }

    /// A program which utilizes this crate should call this function if user was found
    /// but password is encoded as plain text. This function requires that the correct
    /// [ScramHashing] which was previously used to initialize the server, should be used.
    /// 
    /// # Arguments
    /// 
    /// * `pass` - a plaintext password
    /// 
    /// # Throws
    /// 
    /// May throw an error.
    pub fn found_plaintext_password<S: ScramHashing>(pass: &[u8]) -> ScramResult<Self>
    {
        //generate salt and iterations
        let salt = ScramPassword::scram_mock_salt()?;

        let salted_password = S::derive(pass, &salt, ScramCommon::SCRAM_DEFAULT_SALT_ITER)?;

        let ret = Self::UserPasswordData
            {
                salted_hashed_password: salted_password,
                salt: salt,
                iterations: ScramCommon::SCRAM_DEFAULT_SALT_ITER,
            };

        return Ok(ret);
    }

    /// A program which utilizes this crate should call this function if user was found
    /// but password was salted and hashed and salt with iterations count were provided.
    /// 
    /// # Arguments
    /// 
    /// * `salted_hashed_password` - a salted and hashed password
    /// 
    /// * `salt` - a salt
    /// 
    /// * `iterations` - iterations count
    /// 
    /// # Throws
    /// 
    /// May throw an error.
    pub fn found_secret_password(salted_hashed_password: Vec<u8>, salt: Vec<u8>, iterations: u32) -> Self
    {
        return Self::UserPasswordData
            {
                salted_hashed_password: salted_hashed_password,
                salt: salt,
                iterations: iterations,
            };
    }

    /// Returns the reference to salt. Will panic! when misused.
    pub fn get_salt(&self) -> &[u8]
    {
        match *self
        {
            Self::None => panic!("misuse get_salt()"),
            Self::UserNotFound{ref salted_hashed_password, ref salt, ref iterations} => return &salt,
            Self::UserPasswordData{ref salted_hashed_password, ref salt, ref iterations} => return &salt,
        }
    }

    /// Returns the iteration count. Will panic! when misused.
    pub fn get_iterations(&self) -> u32
    {
        match *self
        {
            Self::None => panic!("misuse get_iterations()"),
            Self::UserNotFound{ref salted_hashed_password, ref salt, ref iterations} => return *iterations,
            Self::UserPasswordData{ref salted_hashed_password, ref salt, ref iterations} => return *iterations,
        }
    }

    /// Returns the salted and hashed password. Will panic! when misused.
    pub fn get_salted_hashed_password(&self) -> &[u8]
    {
        match *self
        {
            Self::None => panic!("misuse get_salted_hashed_password()"),
            Self::UserNotFound{ref salted_hashed_password, ..} => return &salted_hashed_password,
            Self::UserPasswordData{ref salted_hashed_password, ..} => return &salted_hashed_password,
        }
    }
}

/// A authentification backend which is behind the SCRAM lib.
/// A program which uses this crate should implement this trait to its auth
/// instance.
/// 
/// # Examples
/// 
/// ```
/// impl ScramAuthServer for AuthServer
/// {
///     fn get_password_for_user(&self, username: &str) -> ScramPassword
///     {
///         let password = match self.lookup(username)
///         {
///             Some(r) => ScramPassword::found_plaintext_password(r.as_bytes()),
///             None => 
///             {
///                 match self.scram_type.scram_name
///                 {
///                     "SCRAM-SHA-256" => ScramPassword::not_found<ScramSha256>(),
///                     "SCRAM-SHA-512" => ScramPassword::not_found<ScramSha512>(),
///                     _ => panic!("should not happen"),
///                 }
///             }
///         };
/// 
///         return password;
/// 
///     }
/// }
/// ```
pub trait ScramAuthServer
{
    fn get_password_for_user(&self, username: &str) -> ScramPassword;
}

/// A authentification backend which is behind the SCRAM lib.
/// A program which uses this crate should implement this trait to its auth
/// instance.
/// 
/// # Examples
/// 
/// ```
/// impl ScramAuthClient for <ProgramStruct>
/// {
///     fn get_username(&self) -> &String
///     {
///         return &self.username;
///     }
/// 
///     fn get_password(&self) -> &String
///     {
///         return &self.password;
///     }
/// }
/// ```
pub trait ScramAuthClient
{
    fn get_username(&self) -> &String;
    fn get_password(&self) -> &String;
}

#[test]
fn test_speed()
{
    use std::time::Instant;
    use super::scram_hashing::ScramSha256;

    let start = Instant::now();

    let res = ScramPassword::not_found::<ScramSha256>();
    assert_eq!(res.is_ok(), true);

    let el = start.elapsed();
    println!("not found took: {:?}", el);

    let start = Instant::now();

    let res = ScramPassword::found_plaintext_password::<ScramSha256>(b"123");
    assert_eq!(res.is_ok(), true);
    
    let el = start.elapsed();
    println!("found_plaintext_password: {:?}", el);

}