libeufin

Integration and sandbox testing for FinTech APIs and data formats
Log | Files | Refs | Submodules | README | LICENSE

pw.rs (6805B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use anyhow::anyhow;
     18 use aws_lc_rs::{constant_time::verify_slices_are_equal, digest::SHA256};
     19 use rand::{TryRng as _, rngs::SysRng};
     20 use taler_api::error::{ApiResult, failure};
     21 use taler_common::{encoding::base64, error_code::ErrorCode};
     22 
     23 // NIST Password Guidelines 2024
     24 const PASSWORD_MIN_LEN: usize = 8;
     25 const PASSWORD_MAX_LEN: usize = 64;
     26 
     27 /** Check if a string is a valid password */
     28 pub fn checkpw(pw: &str, check_quality: bool) -> ApiResult<()> {
     29     if !check_quality {
     30         return Ok(());
     31     }
     32     let len = pw.len();
     33 
     34     if len < PASSWORD_MIN_LEN {
     35         Err(failure(
     36             ErrorCode::BANK_PASSWORD_TOO_SHORT,
     37             format_args!(
     38                 "Password is too short, expect at least {PASSWORD_MIN_LEN} characters got {len}"
     39             ),
     40         ))
     41     } else if len > PASSWORD_MAX_LEN {
     42         Err(failure(
     43             ErrorCode::BANK_PASSWORD_TOO_LONG,
     44             format_args!(
     45                 "Password is too long, expect at most {PASSWORD_MAX_LEN} characters got {len}",
     46             ),
     47         ))
     48     } else {
     49         Ok(())
     50     }
     51 }
     52 
     53 #[derive(Debug, PartialEq, Eq)]
     54 pub struct PwCheck {
     55     pub matches: bool,
     56     pub outdated: bool,
     57 }
     58 
     59 pub enum PwCrypto {
     60     Bcrypt { cost: u32 },
     61     Sha256,
     62 }
     63 
     64 fn bcrypt(cost: u32, salt: [u8; 16], pw: &[u8]) -> [u8; 24] {
     65     // The bcrypt spec specifies that passwords should be null terminated
     66     // strings, but if longer than 72 bytes, are truncated at 72 bytes (thereby
     67     // losing the null byte at the end).
     68     let copy_len = pw.len().min(72);
     69     let mut pass = [0u8; 72];
     70     pass[..copy_len].copy_from_slice(&pw[..copy_len]);
     71     let used = (copy_len + 1).min(72);
     72     let truncated = &pass[..used];
     73     bcrypt::bcrypt(cost, salt, truncated)
     74 }
     75 
     76 impl PwCrypto {
     77     /** Hash [pw] using [cfg] hashing method */
     78     pub fn hashpw(&self, pw: &str) -> String {
     79         match self {
     80             PwCrypto::Bcrypt { cost } => {
     81                 let mut salt = [0u8; 16];
     82                 SysRng.try_fill_bytes(&mut salt).unwrap();
     83                 let pwh = bcrypt(*cost, salt, pw.as_bytes());
     84                 format!("bcrypt${cost}${}${}", base64::fmt(salt), base64::fmt(pwh))
     85             }
     86             PwCrypto::Sha256 => {
     87                 let pwh = aws_lc_rs::digest::digest(&SHA256, pw.as_bytes());
     88                 format!("sha256${}", base64::fmt(pwh))
     89             }
     90         }
     91     }
     92 
     93     /** Check whether [pw] match hashed [storedPwHash] and if it should be rehashed */
     94     pub fn checkpw(&self, pw: &str, stored_pw_hash: &str) -> anyhow::Result<PwCheck> {
     95         let (alg, args) = stored_pw_hash
     96             .split_once('$')
     97             .ok_or(anyhow!("bad password hash format"))?;
     98         let (matches, outdated) = match alg {
     99             "sha256" => {
    100                 let [hash] = split_n(args, '$').ok_or(anyhow!("bad password hash format"))?;
    101                 let pwh = aws_lc_rs::digest::digest(&SHA256, pw.as_bytes());
    102                 (hash_matches(pwh, hash), true)
    103             }
    104             "sha256-salted" => {
    105                 let [salt, hash] = split_n(args, '$').ok_or(anyhow!("bad password hash format"))?;
    106                 let pwh = aws_lc_rs::digest::digest(&SHA256, format!("{salt}|{pw}").as_bytes());
    107                 (hash_matches(pwh, hash), true)
    108             }
    109             "bcrypt" => {
    110                 let [cost, salt, hash] =
    111                     split_n(args, '$').ok_or(anyhow!("bad password hash format"))?;
    112                 let cost: u32 = cost.parse()?;
    113                 let salt = base64::decode(salt)?
    114                     .try_into()
    115                     .map_err(|_| anyhow!("bad password hash format"))?;
    116                 let pwh = bcrypt(cost, salt, pw.as_bytes());
    117                 (
    118                     hash_matches(pwh, hash),
    119                     match self {
    120                         PwCrypto::Bcrypt { cost: expected } => cost != *expected,
    121                         PwCrypto::Sha256 => false,
    122                     },
    123                 )
    124             }
    125             alg => return Err(anyhow!("unsupported hash algo: {alg}")),
    126         };
    127 
    128         Ok(PwCheck { matches, outdated })
    129     }
    130 }
    131 
    132 fn hash_matches(computed: impl AsRef<[u8]>, stored: &str) -> bool {
    133     verify_slices_are_equal(base64::encode(computed).as_bytes(), stored.as_bytes()).is_ok()
    134 }
    135 
    136 fn split_n<const N: usize>(input: &str, sep: char) -> Option<[&str; N]> {
    137     let mut iter = input.split(sep);
    138 
    139     let mut result = [""; N];
    140 
    141     for split in result.iter_mut().take(N) {
    142         *split = iter.next()?;
    143     }
    144 
    145     if iter.next().is_some() {
    146         None
    147     } else {
    148         Some(result)
    149     }
    150 }
    151 
    152 #[test]
    153 fn pwh() {
    154     let pw = "myinsecurepw";
    155     let crypto = PwCrypto::Bcrypt { cost: 4 };
    156     // Check roundtrip
    157     let hash = crypto.hashpw(pw);
    158     assert_eq!(
    159         crypto.checkpw(pw, &hash).unwrap(),
    160         PwCheck {
    161             matches: true,
    162             outdated: false
    163         }
    164     );
    165     assert_eq!(
    166         crypto.checkpw("other", &hash).unwrap(),
    167         PwCheck {
    168             matches: false,
    169             outdated: false
    170         }
    171     );
    172 
    173     // Check outdated algorithm
    174     let outdated = PwCrypto::Sha256.hashpw(pw);
    175     assert_eq!(
    176         crypto.checkpw(pw, &outdated).unwrap(),
    177         PwCheck {
    178             matches: true,
    179             outdated: true
    180         }
    181     );
    182     assert_eq!(
    183         crypto.checkpw("other", &outdated).unwrap(),
    184         PwCheck {
    185             matches: false,
    186             outdated: true
    187         }
    188     );
    189 
    190     // Check outdated options
    191     let better = PwCrypto::Bcrypt { cost: 5 };
    192     assert_eq!(
    193         better.checkpw(pw, &hash).unwrap(),
    194         PwCheck {
    195             matches: true,
    196             outdated: true
    197         }
    198     );
    199     assert_eq!(
    200         better.checkpw("other", &hash).unwrap(),
    201         PwCheck {
    202             matches: false,
    203             outdated: true
    204         }
    205     );
    206 
    207     // Check compatibility with kotlin hashes
    208     let hash = "bcrypt$4$PfNp4JBeMU/t5mS5zaUY3A==$0Tjw0KzNA3ca3y9BVkh/e3TJDlHsdkEA";
    209     assert_eq!(
    210         crypto.checkpw("password", hash).unwrap(),
    211         PwCheck {
    212             matches: true,
    213             outdated: false
    214         }
    215     );
    216 }