diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/client.rs | 211 | ||||
-rw-r--r-- | src/lib.rs | 59 | ||||
-rw-r--r-- | src/prime.bin | 1 | ||||
-rw-r--r-- | src/server.rs | 147 | ||||
-rw-r--r-- | src/tools.rs | 19 | ||||
-rw-r--r-- | src/types.rs | 39 |
6 files changed, 476 insertions, 0 deletions
diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..ee19e88 --- /dev/null +++ b/src/client.rs @@ -0,0 +1,211 @@ +//! SRP client implementation. +//! +//! # Usage +//! First create SRP client struct by passing to it SRP parameters (shared +//! between client and server) and RNG instance (OS RNG is recommended): +//! +//! ```ignore +//! let srp_params = SrpParams{n, g, k}; +//! let mut rng = rand::os::OsRng::new().unwrap(); +//! let client = SrpClient::<Sha256>::new(&srp_params, &mut rng); +//! ``` +//! +//! Next send handshake data (username and `a_pub`) to the server and receive +//! `salt` and `b_pub`: +//! +//! ```ignore +//! let a_pub = client.get_a_pub(); +//! let (salt, b_pub) = conn.send_handshake(username, a_pub); +//! ``` +//! +//! Compute private key using `salt` with any password hashing function. +//! You can use method from SRP-6a, but it's recommended to use specialized +//! password hashing algorithm instead (e.g. PBKDF2, argon2 or scrypt). +//! Next create verifier instance, note that `get_verifier` consumes client and +//! can return error in case of malicious `b_pub`. +//! +//! ```ignore +//! let private_key = srp6a_private_key::<Sha256>(username, password, salt); +//! let verifier = client.get_verifier(&private_key, &b_pub)?; +//! ``` +//! +//! Finally verify the server: first generate user proof, +//! send it to the server and verify server proof in the reply. Note that +//! `verify_server` method will return error in case of incorrect server reply. +//! +//! ```ignore +//! let user_proof = verifier.get_proof(); +//! let server_proof = conn.send_proof(user_proof); +//! let key = verifier.verify_server(server_proof)?; +//! ``` +//! +//! `key` contains shared secret key between user and the server. Alternatively +//! you can directly extract shared secret key using `get_key()` method and +//! handle authentification through different (secure!) means (e.g. by using +//! authentificated cipher mode). +//! +//! For user registration on the server first generate salt (e.g. 32 bytes long) +//! and get password verifier which depends on private key. Send useranme, salt +//! and password verifier over protected channel to protect against MitM for +//! registration. +//! +//! ```ignore +//! let pwd_verifier = SrpClient::<Sha256>::register(&private_key, &srp_params); +//! conn.send_registration_data(username, salt, pwd_verifier); +//! ``` +use std::marker::PhantomData; + +use rand::Rng; +use num::{BigUint, Zero}; +use digest::Digest; +use generic_array::GenericArray; + +use tools::powm; +use types::{SrpAuthError, SrpParams}; + +/// SRP client state before handshake with the server. +pub struct SrpClient<'a, D: Digest> { + params: &'a SrpParams, + + a: BigUint, + a_pub: BigUint, + + d: PhantomData<D> +} + +/// SRP client state after handshake with the server. +pub struct SrpClientVerifier<D: Digest> { + proof: GenericArray<u8, D::OutputSize>, + server_proof: GenericArray<u8, D::OutputSize>, + key: GenericArray<u8, D::OutputSize>, +} + +/// Compute user private key as described in the SRP6a. Consider using proper +/// password hashing algorithm instead. +pub fn srp6a_private_key<D: Digest>(username: &[u8], password: &[u8], + salt: &[u8] + ) -> GenericArray<u8, D::OutputSize> +{ + let p = { + let mut d = D::new(); + d.input(username); + d.input(b":"); + d.input(password); + d.result() + }; + let mut d = D::new(); + d.input(salt); + d.input(&p); + d.result() +} + +impl<'a, D: Digest> SrpClient<'a, D> { + /// Create new SRP client instance. + pub fn new<R: Rng>(params: &'a SrpParams, rng: &mut R) -> Self { + let l = params.n.bits()/8; + let buf = rng.gen_iter::<u8>().take(l).collect::<Vec<u8>>(); + let a = BigUint::from_bytes_le(&buf); + let a_pub = params.powm(&a); + + Self { params, a, a_pub, d: Default::default() } + } + + /// Get password verfier for user registration on the server + pub fn get_password_verifier(&self, private_key: &[u8]) -> Vec<u8> { + let x = BigUint::from_bytes_le(&private_key); + let v = self.params.powm(&x); + v.to_bytes_le() + } + + fn calc_key(&self, b_pub: &BigUint, x: &BigUint, u: &BigUint) + -> GenericArray<u8, D::OutputSize> + { + let n = &self.params.n; + let interm = (&self.params.k * self.params.powm(x)) % n; + // Because we do operation in modulo N we can get: (kv + g^b) < kv + let v = if b_pub > &interm { + (b_pub - &interm) % n + } else { + (n + b_pub - &interm) % n + }; + // S = |B - kg^x| ^ (a + ux) + let s = powm(&v, &(&self.a + (u*x) % n ), n); + D::digest(&s.to_bytes_le()) + } + + /// Process server reply to the handshake. + pub fn process_reply(self, private_key: &[u8], b_pub: &[u8]) + -> Result<SrpClientVerifier<D>, SrpAuthError> + { + let u = { + let mut d = D::new(); + d.input(&self.a_pub.to_bytes_le()); + d.input(b_pub); + BigUint::from_bytes_le(&d.result()) + }; + + let b_pub = BigUint::from_bytes_le(b_pub); + + // Safeguard against malicious B + if &b_pub % &self.params.n == BigUint::zero() { + return Err(SrpAuthError{ description: "Malicious b_pub value" }) + } + + let x = BigUint::from_bytes_le(&private_key); + let key = self.calc_key(&b_pub, &x, &u); + // M1 = H(A, B, K) + let proof = { + let mut d = D::new(); + d.input(&self.a_pub.to_bytes_le()); + d.input(&b_pub.to_bytes_le()); + d.input(&key); + d.result() + }; + + // M2 = H(A, M1, K) + let server_proof = { + let mut d = D::new(); + d.input(&self.a_pub.to_bytes_le()); + d.input(&proof); + d.input(&key); + d.result() + }; + + Ok(SrpClientVerifier { + proof: proof, + server_proof: server_proof, + key: key, + }) + } + + /// Get public ephemeral value for handshaking with the server. + pub fn get_a_pub(&self) -> Vec<u8> { + self.a_pub.to_bytes_le() + } +} + +impl<D: Digest> SrpClientVerifier<D> { + /// Get shared secret key without authenticating server, e.g. for using with + /// authenticated encryption modes. DO NOT USE this method without + /// some kind of secure authentification. + pub fn get_key(self) -> GenericArray<u8, D::OutputSize> { + self.key + } + + /// Verification data for sending to the server. + pub fn get_proof(&self) -> GenericArray<u8, D::OutputSize> { + self.proof.clone() + } + + /// Verify server reply to verification data. It will return shared secret + /// key in case of success. + pub fn verify_server(self, reply: &[u8]) + -> Result<GenericArray<u8, D::OutputSize>, SrpAuthError> + { + if self.server_proof.as_slice() != reply { + Err(SrpAuthError{ description: "Incorrect server proof" }) + } else { + Ok(self.key) + } + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..9401514 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,59 @@ +//! [Secure Remote Password][1] (SRP) protocol implementation. +//! +//! This implementation uses little-endian serialization of big integers and is +//! generic over hash functions using `Digest` trait, so you will need to choose +//! a hash function, e.g. `Sha256` from `sha2` crate. Additionally this crate +//! allows to use a specialized password hashing algorithms for private key +//! computation instead of method described in the SRP literature. +//! +//! Currently compatability with over implementations was not tested. +//! +//! # Algorithm description +//! Here we briefly describe implemented algroithm. For additionall information +//! refer to SRP literature. All arithmetic is done modulo `N`, where `N` is a +//! large safe prime (`N = 2q+1`, where `q` is prime). +//! +//! Client | | Server +//! -------|-------|-------- +//! | — `I` —> | (lookup `s`, `v`) +//! `x = PH(P, s)` | <— `s`, `v` — | +//! `a_pub = g^a` | — `a_pub` —> | `b_pub = k*v + g^b` +//! `u = H(a_pub || b_pub)` | <— `b_pub` — | `u = H(a_pub || b_pub)` +//! `s = (b_pub - k*g^x)^(a+u*x)` | | `S = (b_pub - k*g^x)^(a+u*x)` +//! `K = H(s)` | | `K = H(s)` +//! `M1 = H(A || B || K)` | — `M1` —> | (verify `M1`) +//! (verify `M2`) | <— `M2` — | `M2 = H(A || M1 || K)` +//! +//! `||` denotes concatenation, variables and notations have the following +//! meaning: +//! +//! - `I` — user identity (username) +//! - `P` — user password +//! - `H` — one-way hash function +//! - `HP` — password hashing algroithm, in the SRP described as +//! `H(s || I || P)` or `H(s || P)` +//! - `^` — (modular) exponentiation +//! - `x` — user private key +//! - `s` — salt generated by user and stored on the server +//! - `v` — password verifier equal to `g^x` and stored on the server +//! - `a`, `b` — secret ephemeral values +//! - `A`, `B` — Public ephemeral values +//! - `u` — scrambling parameter +//! - `g` — a generator modulo `N` +//! - `k` — multiplier parameter (`k = H(N || g)` in SRP-6a) +//! +//! [1]: https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol +extern crate num; +extern crate digest; +extern crate generic_array; +extern crate rand; + +mod tools; +pub mod client; +pub mod server; +pub mod types; + +/// 1024 bit prime number which can be used as `n` in the `SrpParams`. +/// +/// For conversion to `BigUint` use `BigUint::from_bytes_le(SRP_PRIME)`. +pub const PRIME: &'static [u8] = include_bytes!("prime.bin"); diff --git a/src/prime.bin b/src/prime.bin new file mode 100644 index 0000000..d2109b7 --- /dev/null +++ b/src/prime.bin @@ -0,0 +1 @@ +_P<=èyCp^ >Hhw
Bb{+2,ZuHEXrӋto 'Tw;䪗Dl'$2/A-tcK2-懘2u7
\ No newline at end of file diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..e82ebf6 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,147 @@ +//! SRP server implementation +//! +//! # Usage +//! First receive user's username and public value `a_pub`, retrieve from a +//! database `UserRecord` for a given username and initialize SRP server state: +//! +//! ```ignore +//! let mut rng = rand::os::OsRng::new().unwrap(); +//! let (username, a_pub) = conn.receive_handshake(); +//! let user = db.retrieve_user_record(username); +//! let server = SrpServer::<Sha256>::new(&user, &a_pub, &srp_params, &mut rng)?; +//! ``` +//! +//! Next send to user `b_pub` and `salt` from user record: +//! +//! ```ignore +//! let b_pub = server.get_b_pub(); +//! conn.reply_to_handshake(&user.salt, b_pub); +//! ``` +//! +//! And finally recieve user proof, verify it and send server proof as reply: +//! +//! ```ignore +//! let user_proof = conn.receive_proof(); +//! let server_proof = server.verify(user_proof)?; +//! conn.send_proof(server_proof); +//! ``` +//! +//! To get the shared secret use `get_key` method. As alternative to using +//! `verify` method it's also possible to use this key for authentificated +//! encryption. +use std::marker::PhantomData; + +use rand::Rng; +use num::{BigUint, Zero}; +use digest::Digest; +use generic_array::GenericArray; + +use tools::powm; +use types::{SrpAuthError, SrpParams}; + +/// Data provided by users upon registration, usually stored in the database. +pub struct UserRecord<'a> { + pub username: &'a [u8], + pub salt: &'a [u8], + /// Password verifier + pub verifier: &'a [u8], +} + +/// SRP server state +pub struct SrpServer<D: Digest> { + b: BigUint, + a_pub: BigUint, + b_pub: BigUint, + + key: GenericArray<u8, D::OutputSize>, + + d: PhantomData<D> +} + +impl< D: Digest> SrpServer< D> { + /// Create new server state with randomly generated `b`. + pub fn new<R: Rng>(user: &UserRecord, a_pub: &[u8], params: &SrpParams, + rng: &mut R) + -> Result<Self, SrpAuthError> + { + let l = params.n.bits()/8; + let b = rng.gen_iter::<u8>().take(l).collect::<Vec<u8>>(); + Self::new_with_b(user, a_pub, &b, params) + } + + /// Create new server state with given `b`. + /// + /// Usefull if it's not convenient to keep `SrpServer` state between + /// handshake and verification steps. (e.g. when working over HTTP and + /// storing `b` in a database) + pub fn new_with_b(user: &UserRecord, a_pub: &[u8], b: &[u8], + params: &SrpParams) + -> Result<Self, SrpAuthError> + { + let a_pub = BigUint::from_bytes_le(a_pub); + // Safeguard against malicious A + if &a_pub % ¶ms.n == BigUint::zero() { + return Err(SrpAuthError { description: "Malicious a_pub value" }) + } + let v = BigUint::from_bytes_le(user.verifier); + let b = BigUint::from_bytes_le(b) % ¶ms.n; + // kv + g^b + let interm = (¶ms.k * &v) % ¶ms.n; + let b_pub = (interm + ¶ms.powm(&b)) % ¶ms.n; + // H(A || B) + let u = { + let mut d = D::new(); + d.input(&a_pub.to_bytes_le()); + d.input(&b_pub.to_bytes_le()); + d.result() + }; + let d = Default::default(); + //(Av^u) ^ b + let key = { + let u = BigUint::from_bytes_le(&u); + let t = (&a_pub * powm(&v, &u, ¶ms.n)) % ¶ms.n; + let s = powm(&t, &b, ¶ms.n); + D::digest(&s.to_bytes_le()) + }; + Ok(Self { b, a_pub, b_pub, key, d}) + } + + /// Get private `b` value. (see `new_with_b` documentation) + pub fn get_b(&self) -> Vec<u8> { + self.b.to_bytes_le() + } + + /// Get public `b_pub` value for sending to the user. + pub fn get_b_pub(&self) -> Vec<u8> { + self.b_pub.to_bytes_le() + } + + /// Get shared secret between user and the server. (do not forget to verify + /// that keys are the same!) + pub fn get_key(&self) -> GenericArray<u8, D::OutputSize> { + self.key.clone() + } + + /// Process user proof of having the same shared secret and compute + /// server proof for sending to the user. + pub fn verify(&self, user_proof: &[u8]) + -> Result<GenericArray<u8, D::OutputSize>, SrpAuthError> + { + // M = H(A, B, K) + let mut d = D::new(); + d.input(&self.a_pub.to_bytes_le()); + d.input(&self.b_pub.to_bytes_le()); + d.input(&self.key); + + if user_proof == d.result().as_slice() { + // H(A, M, K) + let mut d = D::new(); + d.input(&self.a_pub.to_bytes_le()); + d.input(user_proof); + d.input(&self.key); + Ok(d.result()) + } else { + Err(SrpAuthError { description: "Incorrect user proof" }) + } + } +} diff --git a/src/tools.rs b/src/tools.rs new file mode 100644 index 0000000..8cb6910 --- /dev/null +++ b/src/tools.rs @@ -0,0 +1,19 @@ +use num::BigUint; + +pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { + let zero = BigUint::new(vec![0]); + let one = BigUint::new(vec![1]); + let two = BigUint::new(vec![2]); + let mut exp = exp.clone(); + let mut result = one.clone(); + let mut base = base % modulus; + + while exp > zero { + if &exp % &two == one { + result = (result * &base) % modulus; + } + exp = exp >> 1; + base = (&base * &base) % modulus; + } + result +} diff --git a/src/types.rs b/src/types.rs new file mode 100644 index 0000000..aa8a0dc --- /dev/null +++ b/src/types.rs @@ -0,0 +1,39 @@ +//! Additional SRP types. +use std::{fmt, error}; +use num::BigUint; +use tools::powm; + +/// SRP authentification error. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct SrpAuthError { + pub(crate) description: &'static str +} + +impl fmt::Display for SrpAuthError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "SRP authentification error") + } +} + +impl error::Error for SrpAuthError { + fn description(&self) -> &str { + self.description + } +} + +/// Parameters of SRP shared between client and server. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct SrpParams { + /// A large safe prime (N = 2q+1, where q is prime) + pub n: BigUint, + /// A generator modulo N (e.g. 2) + pub g: BigUint, + /// Multiplier parameter (k = H(N, g) in SRP-6a, k = 3 for legacy SRP-6) + pub k: BigUint, +} + +impl SrpParams { + pub(crate) fn powm(&self, v: &BigUint) -> BigUint { + powm(&self.g, v, &self.n) + } +} |