]> git.lizzy.rs Git - PAKEs.git/blob - srp/src/client.rs
d47983e8459a8056ded91ecd47221b31f62d26c9
[PAKEs.git] / srp / src / client.rs
1 //! SRP client implementation.
2 //!
3 //! # Usage
4 //! First create SRP client struct by passing to it SRP parameters (shared
5 //! between client and server) and randomly generated `a`:
6 //!
7 //! ```ignore
8 //! use srp::groups::G_2048;
9 //! use sha2::Sha256;
10 //!
11 //! let mut a = [0u8; 64];
12 //! rng.fill_bytes(&mut a);
13 //! let client = SrpClient::<Sha256>::new(&a, &G_2048);
14 //! ```
15 //!
16 //! Next send handshake data (username and `a_pub`) to the server and receive
17 //! `salt` and `b_pub`:
18 //!
19 //! ```ignore
20 //! let a_pub = client.get_a_pub();
21 //! let (salt, b_pub) = conn.send_handshake(username, a_pub);
22 //! ```
23 //!
24 //! Compute private key using `salt` with any password hashing function.
25 //! You can use method from SRP-6a, but it's recommended to use specialized
26 //! password hashing algorithm instead (e.g. PBKDF2, argon2 or scrypt).
27 //! Next create verifier instance, note that `get_verifier` consumes client and
28 //! can return error in case of malicious `b_pub`.
29 //!
30 //! ```ignore
31 //! let private_key = srp_private_key::<Sha256>(username, password, salt);
32 //! let verifier = client.get_verifier(&private_key, &b_pub)?;
33 //! ```
34 //!
35 //! Finally verify the server: first generate user proof,
36 //! send it to the server and verify server proof in the reply. Note that
37 //! `verify_server` method will return error in case of incorrect server reply.
38 //!
39 //! ```ignore
40 //! let user_proof = verifier.get_proof();
41 //! let server_proof = conn.send_proof(user_proof);
42 //! let key = verifier.verify_server(server_proof)?;
43 //! ```
44 //!
45 //! `key` contains shared secret key between user and the server. Alternatively
46 //! you can directly extract shared secret key using `get_key()` method and
47 //! handle authentication through different (secure!) means (e.g. by using
48 //! authenticated cipher mode).
49 //!
50 //! For user registration on the server first generate salt (e.g. 32 bytes long)
51 //! and get password verifier which depends on private key. Send username, salt
52 //! and password verifier over protected channel to protect against
53 //! Man-in-the-middle (MITM) attack for registration.
54 //!
55 //! ```ignore
56 //! let pwd_verifier = client.get_password_verifier(&private_key);
57 //! conn.send_registration_data(username, salt, pwd_verifier);
58 //! ```
59
60 use std::marker::PhantomData;
61
62 use digest::{Digest, Output};
63 use num_bigint::BigUint;
64
65 use crate::tools::powm;
66 use crate::types::{SrpAuthError, SrpGroup};
67
68 /// SRP client state before handshake with the server.
69 pub struct SrpClient<'a, D: Digest> {
70     params: &'a SrpGroup,
71
72     a: BigUint,
73     a_pub: BigUint,
74
75     d: PhantomData<D>,
76 }
77
78 /// SRP client state after handshake with the server.
79 pub struct SrpClientVerifier<D: Digest> {
80     proof: Output<D>,
81     server_proof: Output<D>,
82     key: Output<D>,
83 }
84
85 /// Compute user private key as described in the RFC 5054. Consider using proper
86 /// password hashing algorithm instead.
87 pub fn srp_private_key<D: Digest>(username: &[u8], password: &[u8], salt: &[u8]) -> Output<D> {
88     let p = {
89         let mut d = D::new();
90         d.update(username);
91         d.update(b":");
92         d.update(password);
93         d.finalize()
94     };
95     let mut d = D::new();
96     d.update(salt);
97     d.update(p.as_slice());
98     d.finalize()
99 }
100
101 impl<'a, D: Digest> SrpClient<'a, D> {
102     /// Create new SRP client instance.
103     pub fn new(a: &[u8], params: &'a SrpGroup) -> Self {
104         let a = BigUint::from_bytes_be(a);
105         let a_pub = params.powm(&a);
106
107         Self {
108             params,
109             a,
110             a_pub,
111             d: Default::default(),
112         }
113     }
114
115     /// Get password verfier for user registration on the server
116     pub fn get_password_verifier(&self, private_key: &[u8]) -> Vec<u8> {
117         let x = BigUint::from_bytes_be(private_key);
118         let v = self.params.powm(&x);
119         v.to_bytes_be()
120     }
121
122     fn calc_key(&self, b_pub: &BigUint, x: &BigUint, u: &BigUint) -> Output<D> {
123         let n = &self.params.n;
124         let k = self.params.compute_k::<D>();
125         let interm = (k * self.params.powm(x)) % n;
126         // Because we do operation in modulo N we can get: (kv + g^b) < kv
127         let v = if *b_pub > interm {
128             (b_pub - &interm) % n
129         } else {
130             (n + b_pub - &interm) % n
131         };
132         // S = |B - kg^x| ^ (a + ux)
133         let s = powm(&v, &(&self.a + (u * x) % n), n);
134         D::digest(&s.to_bytes_be())
135     }
136
137     /// Process server reply to the handshake.
138     pub fn process_reply(
139         self,
140         private_key: &[u8],
141         b_pub: &[u8],
142     ) -> Result<SrpClientVerifier<D>, SrpAuthError> {
143         let u = {
144             let mut d = D::new();
145             d.update(&self.a_pub.to_bytes_be());
146             d.update(b_pub);
147             let h = d.finalize();
148             BigUint::from_bytes_be(h.as_slice())
149         };
150
151         let b_pub = BigUint::from_bytes_be(b_pub);
152
153         // Safeguard against malicious B
154         if &b_pub % &self.params.n == BigUint::default() {
155             return Err(SrpAuthError {
156                 description: "Malicious b_pub value",
157             });
158         }
159
160         let x = BigUint::from_bytes_be(private_key);
161         let key = self.calc_key(&b_pub, &x, &u);
162         // M1 = H(A, B, K)
163         let proof = {
164             let mut d = D::new();
165             d.update(&self.a_pub.to_bytes_be());
166             d.update(&b_pub.to_bytes_be());
167             d.update(&key);
168             d.finalize()
169         };
170
171         // M2 = H(A, M1, K)
172         let server_proof = {
173             let mut d = D::new();
174             d.update(&self.a_pub.to_bytes_be());
175             d.update(&proof);
176             d.update(&key);
177             d.finalize()
178         };
179
180         Ok(SrpClientVerifier {
181             proof,
182             server_proof,
183             key,
184         })
185     }
186
187     /// Process server reply to the handshake with username and salt.
188     #[allow(non_snake_case)]
189     pub fn process_reply_with_username_and_salt(
190         self,
191         username: &[u8],
192         salt: &[u8],
193         private_key: &[u8],
194         b_pub: &[u8],
195     ) -> Result<SrpClientVerifier<D>, SrpAuthError> {
196         let u = {
197             let mut d = D::new();
198             d.update(&self.a_pub.to_bytes_be());
199             d.update(b_pub);
200             let h = d.finalize();
201             BigUint::from_bytes_be(h.as_slice())
202         };
203
204         let b_pub = BigUint::from_bytes_be(b_pub);
205
206         // Safeguard against malicious B
207         if &b_pub % &self.params.n == BigUint::default() {
208             return Err(SrpAuthError {
209                 description: "Malicious b_pub value",
210             });
211         }
212
213         let x = BigUint::from_bytes_be(private_key);
214         let key = self.calc_key(&b_pub, &x, &u);
215         // M1 = H(H(N)^H(g), H(I), salt, A, B, K)
216         let proof = {
217             let mut d = D::new();
218             d.update(username);
219             let h = d.finalize_reset();
220             let I: &[u8] = h.as_slice();
221
222             d.update(self.params.compute_hash_n_xor_hash_g::<D>());
223             d.update(I);
224             d.update(salt);
225             d.update(&self.a_pub.to_bytes_be());
226             d.update(&b_pub.to_bytes_be());
227             d.update(&key.to_vec());
228             d.finalize()
229         };
230
231         // M2 = H(A, M1, K)
232         let server_proof = {
233             let mut d = D::new();
234             d.update(&self.a_pub.to_bytes_be());
235             d.update(&proof);
236             d.update(&key);
237             d.finalize()
238         };
239
240         Ok(SrpClientVerifier {
241             proof,
242             server_proof,
243             key,
244         })
245     }
246
247     /// Get public ephemeral value for handshaking with the server.
248     pub fn get_a_pub(&self) -> Vec<u8> {
249         self.a_pub.to_bytes_be()
250     }
251 }
252
253 impl<D: Digest> SrpClientVerifier<D> {
254     /// Get shared secret key without authenticating server, e.g. for using with
255     /// authenticated encryption modes. DO NOT USE this method without
256     /// some kind of secure authentication
257     pub fn get_key(self) -> Output<D> {
258         self.key
259     }
260
261     /// Verification data for sending to the server.
262     pub fn get_proof(&self) -> Output<D> {
263         self.proof.clone()
264     }
265
266     /// Verify server reply to verification data. It will return shared secret
267     /// key in case of success.
268     pub fn verify_server(self, reply: &[u8]) -> Result<Output<D>, SrpAuthError> {
269         if self.server_proof.as_slice() != reply {
270             Err(SrpAuthError {
271                 description: "Incorrect server proof",
272             })
273         } else {
274             Ok(self.key)
275         }
276     }
277 }