Skip to content

Commit 4b1e345

Browse files
committed
Fix exchange with keys that had Q automatically computed
fixes pyca#10790 closes pyca#10864
1 parent 48df2eb commit 4b1e345

File tree

4 files changed

+65
-10
lines changed

4 files changed

+65
-10
lines changed

docs/development/test-vectors.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,10 @@ Key exchange
224224
* ``vectors/cryptoraphy_vectors/asymmetric/ECDH/brainpool.txt`` contains
225225
Brainpool vectors from :rfc:`7027`.
226226

227+
* ``vectors/cryptography_vectors/asymmetric/DH/dhpub_cryptography_old.pem``
228+
contains a Diffie-Hellman public key generated with a previous version of
229+
``cryptography``.
230+
227231
X.509
228232
~~~~~
229233

src/rust/src/backend/dh.rs

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ pub(crate) struct DHPublicKey {
2525
#[pyo3::pyclass(frozen, module = "cryptography.hazmat.bindings._rust.openssl.dh")]
2626
struct DHParameters {
2727
dh: openssl::dh::Dh<openssl::pkey::Params>,
28+
29+
is_dhx: bool,
2830
}
2931

3032
#[pyo3::pyfunction]
@@ -51,7 +53,7 @@ fn generate_parameters(
5153

5254
let dh = openssl::dh::Dh::generate_params(key_size, generator)
5355
.map_err(|_| pyo3::exceptions::PyValueError::new_err("Unable to generate DH parameters"))?;
54-
Ok(DHParameters { dh })
56+
Ok(DHParameters { dh, is_dhx: false })
5557
}
5658

5759
pub(crate) fn private_key_from_pkey(
@@ -73,12 +75,13 @@ pub(crate) fn public_key_from_pkey(
7375
#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))]
7476
fn pkey_from_dh<T: openssl::pkey::HasParams>(
7577
dh: openssl::dh::Dh<T>,
78+
is_dhx: bool,
7679
) -> CryptographyResult<openssl::pkey::PKey<T>> {
7780
cfg_if::cfg_if! {
7881
if #[cfg(CRYPTOGRAPHY_IS_LIBRESSL)] {
7982
Ok(openssl::pkey::PKey::from_dh(dh)?)
8083
} else {
81-
if dh.prime_q().is_some() {
84+
if is_dhx {
8285
Ok(openssl::pkey::PKey::from_dhx(dh)?)
8386
} else {
8487
Ok(openssl::pkey::PKey::from_dh(dh)?)
@@ -87,6 +90,16 @@ fn pkey_from_dh<T: openssl::pkey::HasParams>(
8790
}
8891
}
8992

93+
fn is_dhx(id: openssl::pkey::Id) -> bool {
94+
cfg_if::cfg_if! {
95+
if #[cfg(any(CRYPTOGRAPHY_IS_LIBRESSL, CRYPTOGRAPHY_IS_BORINGSSL))] {
96+
false
97+
} else {
98+
id == openssl::pkey::Id::DHX
99+
}
100+
}
101+
}
102+
90103
#[pyo3::pyfunction]
91104
#[pyo3(signature = (data, backend=None))]
92105
fn from_der_parameters(
@@ -105,6 +118,7 @@ fn from_der_parameters(
105118

106119
Ok(DHParameters {
107120
dh: openssl::dh::Dh::from_pqg(p, q, g)?,
121+
is_dhx: asn1_params.q.is_some(),
108122
})
109123
}
110124

@@ -214,14 +228,18 @@ impl DHPrivateKey {
214228
let orig_dh = self.pkey.dh().unwrap();
215229
let dh = clone_dh(&orig_dh)?;
216230

217-
let pkey = pkey_from_dh(dh.set_public_key(orig_dh.public_key().to_owned()?)?)?;
231+
let pkey = pkey_from_dh(
232+
dh.set_public_key(orig_dh.public_key().to_owned()?)?,
233+
is_dhx(self.pkey.id()),
234+
)?;
218235

219236
Ok(DHPublicKey { pkey })
220237
}
221238

222239
fn parameters(&self) -> CryptographyResult<DHParameters> {
223240
Ok(DHParameters {
224241
dh: clone_dh(&self.pkey.dh().unwrap())?,
242+
is_dhx: is_dhx(self.pkey.id()),
225243
})
226244
}
227245

@@ -280,6 +298,8 @@ impl DHPublicKey {
280298
fn parameters(&self) -> CryptographyResult<DHParameters> {
281299
Ok(DHParameters {
282300
dh: clone_dh(&self.pkey.dh().unwrap())?,
301+
302+
is_dhx: is_dhx(self.pkey.id()),
283303
})
284304
}
285305

@@ -322,7 +342,7 @@ impl DHParameters {
322342
fn generate_private_key(&self) -> CryptographyResult<DHPrivateKey> {
323343
let dh = clone_dh(&self.dh)?.generate_key()?;
324344
Ok(DHPrivateKey {
325-
pkey: pkey_from_dh(dh)?,
345+
pkey: pkey_from_dh(dh, self.is_dhx)?,
326346
})
327347
}
328348

@@ -421,9 +441,11 @@ impl DHPrivateNumbers {
421441
) -> CryptographyResult<DHPrivateKey> {
422442
let _ = backend;
423443

424-
let dh = dh_parameters_from_numbers(py, self.public_numbers.get().parameter_numbers.get())?;
444+
let public_numbers = self.public_numbers.get();
445+
let parameter_numbers = public_numbers.parameter_numbers.get();
446+
let dh = dh_parameters_from_numbers(py, parameter_numbers)?;
425447

426-
let pub_key = utils::py_int_to_bn(py, self.public_numbers.get().y.bind(py))?;
448+
let pub_key = utils::py_int_to_bn(py, public_numbers.y.bind(py))?;
427449
let priv_key = utils::py_int_to_bn(py, self.x.bind(py))?;
428450

429451
let dh = dh.set_key(pub_key, priv_key)?;
@@ -435,7 +457,7 @@ impl DHPrivateNumbers {
435457
));
436458
}
437459

438-
let pkey = pkey_from_dh(dh)?;
460+
let pkey = pkey_from_dh(dh, parameter_numbers.q.is_some())?;
439461
Ok(DHPrivateKey { pkey })
440462
}
441463

@@ -474,11 +496,12 @@ impl DHPublicNumbers {
474496
) -> CryptographyResult<DHPublicKey> {
475497
let _ = backend;
476498

477-
let dh = dh_parameters_from_numbers(py, self.parameter_numbers.get())?;
499+
let parameter_numbers = self.parameter_numbers.get();
500+
let dh = dh_parameters_from_numbers(py, parameter_numbers)?;
478501

479502
let pub_key = utils::py_int_to_bn(py, self.y.bind(py))?;
480503

481-
let pkey = pkey_from_dh(dh.set_public_key(pub_key)?)?;
504+
let pkey = pkey_from_dh(dh.set_public_key(pub_key)?, parameter_numbers.q.is_some())?;
482505

483506
Ok(DHPublicKey { pkey })
484507
}
@@ -535,7 +558,10 @@ impl DHParameterNumbers {
535558
let _ = backend;
536559

537560
let dh = dh_parameters_from_numbers(py, self)?;
538-
Ok(DHParameters { dh })
561+
Ok(DHParameters {
562+
dh,
563+
is_dhx: self.q.is_some(),
564+
})
539565
}
540566

541567
fn __eq__(

tests/hazmat/primitives/test_dh.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,16 @@ def test_dh_vectors_with_q(self, backend, vector):
441441
assert int.from_bytes(symkey1, "big") == int(vector["z"], 16)
442442
assert int.from_bytes(symkey2, "big") == int(vector["z"], 16)
443443

444+
def test_exchange_old_key(self, backend):
445+
k = load_vectors_from_file(
446+
os.path.join("asymmetric", "DH", "dhpub_cryptography_old.pem"),
447+
lambda f: serialization.load_pem_public_key(f.read()),
448+
mode="rb",
449+
)
450+
assert isinstance(k, dh.DHPublicKey)
451+
# Ensure this doesn't raise.
452+
k.parameters().generate_private_key().exchange(k)
453+
444454
def test_public_key_equality(self, backend):
445455
key_bytes = load_vectors_from_file(
446456
os.path.join("asymmetric", "DH", "dhpub.pem"),
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
-----BEGIN PUBLIC KEY-----
2+
MIICJTCCARcGCSqGSIb3DQEDATCCAQgCggEBAP//////////yQ/aoiFowjTExmKL
3+
gNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVt
4+
bVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR
5+
7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue1SkH
6+
cJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoY DmyeDouwHoo+1xV3w
7+
b0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKrKpo//////////8CAQID
8+
ggEGAAKCAQEAoely6vSHw+/Q3zGYLaJj7eeQkfd25K8SvtC+FMY9D7jwS4g71pyr
9+
U3FJ98Fi45Wdksh+d4u7U089trF5Xbgui29bZ0HcQZtfHEEz0Mh69tkipCm2/QIj
10+
6eDlo6sPk9hhhvgg4MMGiWKhCtHrub3x1FHdmf7KjOhrGeb5apiudo7blGFzGhZ3
11+
NFnbff+ArVNd+rdVmSoZn0aMhXRConlDu/44IYe5/24VLl7G+BzZlIZO4P2M83fd
12+
mBOvR13cmYssQjEFTbaZVQvQHa3t0+aywfdCgsXGmTTK6QDCBP8D+vf1bmhEswzs
13+
oYn1GLtJ3VyYyMBPDBomd2ctchZgTzsX1w==
14+
-----END PUBLIC KEY-----
15+

0 commit comments

Comments
 (0)