forked from pyca/bcrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
224 lines (194 loc) · 7.77 KB
/
lib.rs
File metadata and controls
224 lines (194 loc) · 7.77 KB
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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![deny(rust_2018_idioms)]
use base64::Engine;
use pyo3::types::PyBytesMethods;
use pyo3::PyTypeInfo;
use std::convert::TryInto;
use std::ffi::CString;
use std::io::Write;
use subtle::ConstantTimeEq;
pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::GeneralPurpose::new(
&base64::alphabet::BCRYPT,
base64::engine::general_purpose::NO_PAD,
);
#[pyo3::pyfunction]
#[pyo3(signature = (rounds=12, prefix=None), text_signature = "(rounds=12, prefix=b'2b')")]
fn gensalt<'p>(
py: pyo3::Python<'p>,
rounds: u16,
prefix: Option<&[u8]>,
) -> pyo3::PyResult<pyo3::Bound<'p, pyo3::types::PyBytes>> {
let prefix = prefix.unwrap_or(b"2b");
if prefix != b"2a" && prefix != b"2b" {
return Err(pyo3::exceptions::PyValueError::new_err(
"Supported prefixes are b'2a' or b'2b'",
));
}
if !(4..=31).contains(&rounds) {
return Err(pyo3::exceptions::PyValueError::new_err("Invalid rounds"));
}
let mut salt = [0; 16];
getrandom::fill(&mut salt).unwrap();
let encoded_salt = BASE64_ENGINE.encode(salt);
pyo3::types::PyBytes::new_with(
py,
1 + prefix.len() + 1 + 2 + 1 + encoded_salt.len(),
|mut b| {
write!(b, "$").unwrap();
b.write_all(prefix).unwrap();
write!(b, "$").unwrap();
write!(b, "{:02.2}", rounds).unwrap();
write!(b, "$").unwrap();
b.write_all(encoded_salt.as_bytes()).unwrap();
Ok(())
},
)
}
#[pyo3::pyfunction]
fn hashpw<'p>(
py: pyo3::Python<'p>,
password: &[u8],
salt: &[u8],
) -> pyo3::PyResult<pyo3::Bound<'p, pyo3::types::PyBytes>> {
// bcrypt originally suffered from a wraparound bug:
// http://www.openwall.com/lists/oss-security/2012/01/02/4
// This bug was corrected in the OpenBSD source by truncating inputs to 72
// bytes on the updated prefix $2b$, but leaving $2a$ unchanged for
// compatibility. However, pyca/bcrypt 2.0.0 *did* correctly truncate inputs
// on $2a$, so we do it here to preserve compatibility with 2.0.0
// Silent truncation is _probably_ not the best idea, even if the "original"
// OpenBSD implementation did/does this.
// We prefer to raise a ValueError in this case - if the user _wants_ to truncate,
// they can always do so manually by passing s[:72] instead of s into hashpw().
if password.len() > 72 {
return Err(pyo3::exceptions::PyValueError::new_err(
"password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72])",
));
}
// salt here is not just the salt bytes, but rather an encoded value
// containing a version number, number of rounds, and the salt.
// Should be [prefix, cost, hash]. This logic is copied from `bcrypt`
let [raw_version, raw_cost, remainder]: [&[u8]; 3] = salt
.split(|&b| b == b'$')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.try_into()
.map_err(|_| pyo3::exceptions::PyValueError::new_err("Invalid salt"))?;
let version = match raw_version {
b"2y" => bcrypt::Version::TwoY,
b"2b" => bcrypt::Version::TwoB,
b"2a" => bcrypt::Version::TwoA,
b"2x" => bcrypt::Version::TwoX,
_ => {
return Err(pyo3::exceptions::PyValueError::new_err("Invalid salt"));
}
};
let cost = std::str::from_utf8(raw_cost)
.map_err(|_| pyo3::exceptions::PyValueError::new_err("Invalid salt"))?
.parse::<u32>()
.map_err(|_| pyo3::exceptions::PyValueError::new_err("Invalid salt"))?;
if remainder.len() < 22 {
return Err(pyo3::exceptions::PyValueError::new_err("Invalid salt"));
}
// The last component can contain either just the salt, or the salt and
// the result hash, depending on if the `salt` value come from `hashpw` or
// `gensalt`.
let raw_salt = BASE64_ENGINE
.decode(&remainder[..22])
.map_err(|_| pyo3::exceptions::PyValueError::new_err("Invalid salt"))?
.try_into()
.map_err(|_| pyo3::exceptions::PyValueError::new_err("Invalid salt"))?;
let hashed = py
.detach(|| bcrypt::hash_with_salt(password, cost, raw_salt))
.map_err(|_| pyo3::exceptions::PyValueError::new_err("Invalid salt"))?;
Ok(pyo3::types::PyBytes::new(
py,
hashed.format_for_version(version).as_bytes(),
))
}
#[pyo3::pyfunction]
fn checkpw(py: pyo3::Python<'_>, password: &[u8], hashed_password: &[u8]) -> pyo3::PyResult<bool> {
Ok(hashpw(py, password, hashed_password)?
.as_bytes()
.ct_eq(hashed_password)
.into())
}
#[pyo3::pyfunction]
#[pyo3(signature = (password, salt, desired_key_bytes, rounds, ignore_few_rounds=false))]
fn kdf<'p>(
py: pyo3::Python<'p>,
password: &[u8],
salt: &[u8],
desired_key_bytes: usize,
rounds: u32,
ignore_few_rounds: bool,
) -> pyo3::PyResult<pyo3::Bound<'p, pyo3::types::PyBytes>> {
if password.is_empty() || salt.is_empty() {
return Err(pyo3::exceptions::PyValueError::new_err(
"password and salt must not be empty",
));
}
if desired_key_bytes == 0 || desired_key_bytes > 512 {
return Err(pyo3::exceptions::PyValueError::new_err(
"desired_key_bytes must be 1-512",
));
}
if rounds < 1 {
return Err(pyo3::exceptions::PyValueError::new_err(
"rounds must be 1 or more",
));
}
if rounds < 50 && !ignore_few_rounds {
// They probably think bcrypt.kdf()'s rounds parameter is logarithmic,
// expecting this value to be slow enough (it probably would be if this
// were bcrypt). Emit a warning.
pyo3::PyErr::warn(
py,
&pyo3::exceptions::PyUserWarning::type_object(py),
&CString::new(format!("Warning: bcrypt.kdf() called with only {rounds} round(s). This few is not secure: the parameter is linear, like PBKDF2.")).unwrap(),
3
)?;
}
pyo3::types::PyBytes::new_with(py, desired_key_bytes, |output| {
py.detach(|| {
bcrypt_pbkdf::bcrypt_pbkdf(password, salt, rounds, output).unwrap();
});
Ok(())
})
}
#[pyo3::pymodule(gil_used = false)]
mod _bcrypt {
use pyo3::types::PyModuleMethods;
#[pymodule_export]
use super::{checkpw, gensalt, hashpw, kdf};
// Not yet possible to add constants declaratively.
#[pymodule_init]
fn init(m: &pyo3::Bound<'_, pyo3::types::PyModule>) -> pyo3::PyResult<()> {
m.add("__title__", "bcrypt")?;
m.add(
"__summary__",
"Modern(-ish) password hashing for your software and your servers",
)?;
m.add("__uri__", "https://github.com/pyca/bcrypt/")?;
// When updating this, also update pyproject.toml
// This isn't named __version__ because passlib treats the existence of
// that attribute as proof that we're a different module
m.add("__version_ex__", "5.0.0")?;
let author = "The Python Cryptographic Authority developers";
m.add("__author__", author)?;
m.add("__email__", "cryptography-dev@python.org")?;
m.add("__license__", "Apache License, Version 2.0")?;
m.add("__copyright__", format!("Copyright 2013-2025 {author}"))?;
Ok(())
}
}