├── rustfmt.toml ├── .gitignore ├── .github └── workflows │ └── rust.yml ├── Cargo.toml ├── LICENSE ├── src ├── error.rs └── lib.rs └── README.md /rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | 13 | #Added by cargo 14 | 15 | /target 16 | .*.sw? 17 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "phpass" 3 | version = "0.1.4" 4 | authors = ["Joshua Koudys "] 5 | edition = "2021" 6 | license = "MIT" 7 | description = "PHPass, the WordPress password hasher, re-implemented in rust" 8 | homepage = "https://github.com/clausehound/phpass" 9 | repository = "https://github.com/clausehound/phpass" 10 | readme = "README.md" 11 | documentation = "https://github.com/clausehound/phpass" 12 | keywords = ["wordpress", "phpass", "password", "salt", "hash"] 13 | 14 | [dependencies] 15 | base64-compat = "1.0.0" 16 | md5 = "^0.7" 17 | rand = "0.8.5" 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Joshua Koudys 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::{array, fmt}; 2 | 3 | #[derive(Debug)] 4 | pub enum Error { 5 | OldWPFormat, 6 | InvalidId(String), 7 | InvalidPasses(Option), 8 | DecodeError(base64::DecodeError), 9 | CopyDecoded(std::array::TryFromSliceError), 10 | VerificationError, 11 | } 12 | 13 | impl std::error::Error for Error {} 14 | 15 | impl From for Error { 16 | fn from(e: base64::DecodeError) -> Self { 17 | Self::DecodeError(e) 18 | } 19 | } 20 | 21 | impl From for Error { 22 | fn from(e: array::TryFromSliceError) -> Self { 23 | Self::CopyDecoded(e) 24 | } 25 | } 26 | 27 | impl fmt::Display for Error { 28 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 29 | match self { 30 | Error::OldWPFormat => write!(f, "Old WP one-pass md5 encoding not supported"), 31 | Error::InvalidPasses(c) => write!(f, "Found invalid character for passes: {:?}", c), 32 | Error::InvalidId(s) => write!(f, "Found invalid ID set in crypto: {:?}", s), 33 | Error::VerificationError => write!(f, "Calculated hash does not match checksum"), 34 | Error::DecodeError(e) => e.fmt(f), 35 | Error::CopyDecoded(e) => e.fmt(f), 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PhPass 2 | A rust implementation of the password hashing algorithm used by WordPress. https://www.openwall.com/phpass/ 3 | 4 | ## What 5 | WordPress, the most popular blogging platform of all time, is the main application of the PhPass password algorithm. Since WP is nothing if not broad and backwards-compatible in its support, they avoided using a more modern checksum (e.g. SHA256) in favour of old-fashioned, long-broken md5. To make up for this, they'll run MD5 on a salted (and re-salted) input 256 times. 6 | 7 | ## Why 8 | We often don't know which ideas and projects will become successful when we make them, and frequently sites evolve naturally from a simple, managed WordPress blog, to one with a custom plugin, to a hosted PHP app with WordPress as one of its packages, to away from PHP entirely. Those who move to rust (which is wonderful) will want some way to keep those old logins working. 9 | 10 | It's also considerably faster than the native PHP version, so could be used in quickly auditing your WordPress user database, to flag and disable accounts with insecure (easy to guess) passwords. 11 | 12 | ## How 13 | This crate provides the basics to decode the PhPass checksum and salt from the standard WordPress hash string, and verify against a cleartext password. 14 | 15 | TODO: proper rustdoc and an examples dir 16 | 17 | ### Getting started 18 | 19 | ```rs 20 | // mysql_async querying our user's hash 21 | let hash: String = pool 22 | .get_conn() 23 | .await? 24 | .first_exec( 25 | "SELECT user_pass FROM wp_users WHERE user_email = ?;", 26 | (&auth_data.email,) 27 | ) 28 | .await? 29 | .1 30 | .ok_or(MyError)?; 31 | 32 | // Return on failed verify through the beauty of ? 33 | PhPass::try_from(hash)?.verify(&auth_data.password)?; 34 | ``` 35 | 36 | Making a new password with a random hash: 37 | ```rs 38 | let phpass = PhPass::new("swordfish"); 39 | 40 | // Display or to_string() will generate the full hash string 41 | println!("{}", phpass); 42 | ``` 43 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Originally based on phpass, but they seemed to be 2 | // imitating the non-standard FreeBSD multipass md5, as described: 3 | // https://docs.rs/pwhash/0.3.0/pwhash/md5_crypt/index.html 4 | // except instead of: 5 | // $1${salt}${checksum} 6 | // We look like: 7 | // $P$[passes; 1][salt; 8]{checksum} 8 | pub mod error; 9 | use error::Error; 10 | use rand::{thread_rng, Rng}; 11 | use std::borrow::Cow; 12 | use std::convert::{TryFrom, TryInto}; 13 | use std::fmt; 14 | 15 | #[derive(Debug)] 16 | pub struct PhPass<'a> { 17 | // Passes as a power of 2**passes 18 | passes: usize, 19 | salt: Cow<'a, str>, 20 | // This will always match 16-bytes, however long it's encoded, 21 | // because that's how big an MD5 sum is 22 | hash: [u8; 16], 23 | } 24 | 25 | // It'd be nice if the base64 crate gave me access to this. 26 | const CRYPT: &str = r"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; 27 | 28 | impl<'a> TryFrom<&'a str> for PhPass<'a> { 29 | type Error = Error; 30 | 31 | fn try_from(s: &'a str) -> Result { 32 | // TODO: For full old-WordPress support, allow 32-bit hashes 33 | if s.len() < 34 { 34 | return Err(Error::OldWPFormat); 35 | } 36 | 37 | // TODO: were this part of a suite of crypto algos, this ID would 38 | // choose PHPass. 39 | if &s[0..3] != "$P$" { 40 | return Err(Error::InvalidId(s[0..3].to_string())); 41 | } 42 | 43 | // 4th character, decoded on table, as a power of 2 44 | // TODO: access the table directly and avoid this overhead, 45 | // since it's only 1 character 46 | let passes = s.chars().nth(3); 47 | let passes = CRYPT 48 | .find(passes.ok_or(Error::InvalidPasses(passes))?) 49 | .ok_or(Error::InvalidPasses(passes))?; 50 | 51 | // We pad by 0s, encoded as . 52 | let encoded = &s[12..]; 53 | let len = encoded.len(); 54 | let hash = base64::decode_config( 55 | &std::iter::repeat(b'.') 56 | // Base64 encodes on 3-byte boundaries 57 | .take(3 - len % 3) 58 | .chain(encoded.bytes().rev()) 59 | .collect::>(), 60 | base64::CRYPT, 61 | )? 62 | .iter() 63 | // Then those backwards-fed inputs need their outputs reversed. 64 | .rev() 65 | .take(16) 66 | .copied() 67 | .collect::>() 68 | .as_slice() 69 | .try_into()?; 70 | 71 | Ok(Self { 72 | passes, 73 | salt: Cow::Borrowed(&s[4..12]), 74 | hash, 75 | }) 76 | } 77 | } 78 | 79 | impl fmt::Display for PhPass<'_> { 80 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 81 | let iter = self.hash.chunks_exact(3); 82 | // Remain is a tiny nibble, since we're encoding a 16-byte hash 83 | let end = base64::encode_config(&[0, 0, iter.remainder()[0]], base64::CRYPT) 84 | .chars() 85 | .rev() 86 | // Get rid of trailing 0s 87 | .take(2) 88 | .collect::(); 89 | 90 | let mapped = iter 91 | .map(|chunk| { 92 | // To work around the wacky ltr on streaming the string, but 93 | // rtl for reading the bits from the 24-bit sequence, we'll 94 | base64::encode_config( 95 | &chunk.iter().rev().copied().collect::>(), 96 | base64::CRYPT, 97 | ) 98 | .chars() 99 | .rev() 100 | .collect::() 101 | }) 102 | .chain(std::iter::once(end)) 103 | .collect::(); 104 | 105 | write!( 106 | f, 107 | "$P${}{}{}", 108 | &CRYPT[self.passes..self.passes + 1], 109 | self.salt, 110 | mapped 111 | ) 112 | } 113 | } 114 | 115 | #[cfg(test)] 116 | mod tests { 117 | use super::*; 118 | 119 | #[test] 120 | fn test_round_trip() { 121 | let random_salt = PhPass::new("hello").to_string(); 122 | let phpass = PhPass::try_from(random_salt.as_ref()).unwrap(); 123 | assert!( 124 | phpass.verify("hello").is_ok(), 125 | "Failed to verify random-salt password hash" 126 | ) 127 | } 128 | 129 | #[test] 130 | fn test_verify_parse() { 131 | let phpass = PhPass::try_from("$P$BgUdq1RzEBYd9Tm/uZC7mz/l5F.x4N1").unwrap(); 132 | 133 | assert!( 134 | phpass.verify("development").is_ok(), 135 | "Failed to verify parsed password hash" 136 | ) 137 | } 138 | 139 | #[test] 140 | fn test_verify_new() { 141 | let phpass = PhPass::new("world!"); 142 | 143 | assert!( 144 | phpass.verify("world!").is_ok(), 145 | "Failed to verify random-salt password hash" 146 | ) 147 | } 148 | } 149 | 150 | fn checksum, U: AsRef<[u8]>>(pass: T, salt: U, passes: usize) -> [u8; 16] { 151 | let pass = pass.as_ref(); 152 | let salt = salt.as_ref(); 153 | let checksum = (0..1 << passes).fold(md5::compute([salt, pass].concat()), |a, _| { 154 | md5::compute([&a.0, pass].concat()) 155 | }); 156 | checksum.0 157 | } 158 | 159 | impl PhPass<'_> { 160 | // Make a new PhPass with a random salt 161 | pub fn new<'a, T: AsRef<[u8]>>(pass: T) -> PhPass<'a> { 162 | let mut rng = thread_rng(); 163 | let passes = 13; 164 | let salt = base64::encode(&rng.gen::<[u8; 6]>()); 165 | let hash = checksum(&pass, &salt, passes); 166 | 167 | PhPass { 168 | passes, 169 | salt: Cow::Owned(salt), 170 | hash, 171 | } 172 | } 173 | 174 | pub fn verify>(&self, pass: T) -> Result<(), Error> { 175 | if self.hash == checksum(pass, self.salt.as_ref(), self.passes) { 176 | Ok(()) 177 | } else { 178 | Err(Error::VerificationError) 179 | } 180 | } 181 | } 182 | --------------------------------------------------------------------------------