pkix-path 0.7.1

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! GOST R 34.10 signature verification, implemented here because no
//! crate provides it.
//!
//! # Why this file exists
//!
//! `streebog` and `gost94` give the GOST hash functions, but nothing on
//! crates.io implements the GOST R 34.10 *signature* scheme. And unlike
//! [`crate::brainpool_p512r1`] -- a missing curve under an algorithm
//! this crate already had -- GOST R 34.10 is its own signature
//! equation, so none of the ECDSA machinery applies.
//!
//! Six self-issued roots in `third_party/trust-stores/ru-national/` are
//! signed with it, from the Russian Ministry of Digital Development
//! (`dit@digital.gov.ru`, earlier `dit@minsvyaz.ru`). All six use one
//! curve, `id-GostR3410-2001-CryptoPro-A-ParamSet`, which is what makes
//! this tractable: a family would not have been.
//!
//! # Why there was an argument against doing it
//!
//! Our OpenSSL has no GOST at all -- the engine is gone from modern
//! builds, and `openssl list -signature-algorithms` shows nothing. So
//! unlike every other primitive added to this crate, there is no second
//! implementation to differential-test against. Writing a signature
//! verifier with nothing independent to check it against is how you ship
//! one that quietly accepts bad signatures.
//!
//! # What replaces the oracle
//!
//! RFC 7091 §7 reproduces GOST R 34.10-2012's own test example, and it
//! gives the *intermediate* values -- `e`, `v`, `z1`, `z2`, `x_C`, `r`,
//! `s` -- not just a verdict. That is better than an oracle for finding
//! a mistake, because a wrong step is localised instead of just
//! producing "invalid".
//!
//! The example is on `id-GostR3410-2001-TestParamSet`, not CryptoPro-A,
//! so both curves are defined here. The verification equation is
//! curve-independent, so:
//!
//! - the **RFC vector** validates the equation, on its own curve;
//! - the **six certificates** validate the CryptoPro-A parameters and
//!   the X.509 encoding conventions, since a wrong byte order cannot
//!   produce a valid signature by accident.
//!
//! Together those cover what an oracle would have.
//!
//! # The encoding conventions, which are the trap
//!
//! RFC 4491 specifies two byte orders and they disagree with each other:
//!
//! - **The public key** (§2.3.2) is a DER `OCTET STRING` *inside* the
//!   `subjectPublicKey` BIT STRING, 64 octets, first 32 the
//!   **little-endian** `x` and second 32 the **little-endian** `y`.
//! - **The signature** (§2.2.2) is 64 raw octets, first 32 the
//!   **big-endian** `s` and second 32 the **big-endian** `r`.
//!
//! So the key is little-endian, the signature is big-endian, and `s`
//! comes before `r` -- the reverse of ECDSA's `SEQUENCE { r, s }`, and
//! not a `SEQUENCE` at all.
//!
//! # This is a stopgap
//!
//! If a `gost-r34-10` crate appears, delete this and depend on it. The
//! curve parameters here are the ones it will use.

/// id-GostR3410-2001-CryptoPro-A-ParamSet (RFC 4357 §11.4)
pub mod cryptopro_a {
    use elliptic_curve::bigint::{Odd, U256};

    /// The curve.
    #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
    pub struct GostCryptoProA;

    const MODULUS_HEX: &str = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd97";
    const ORDER_HEX: &str = "ffffffffffffffffffffffffffffffff6c611070995ad10045841b09b761b893";
    const ORDER: Odd<U256> = Odd::<U256>::from_be_hex(ORDER_HEX);

    /// The base field, modulo p. Its own module because
    /// `monty_field_params!` emits a `use`.
    // `primefield 0.14.0`'s `monty_field_params!` calls the deprecated
    // `crypto_bigint::Uint::bits`. The call is upstream's, this
    // workspace builds with `-D warnings`, and the attribute is scoped
    // to the module so it stops applying the moment a `primefield`
    // release uses `bit_width`. Same note as `brainpool_p512r1`.
    #[expect(deprecated)]
    mod field {
        use super::MODULUS_HEX;
        use elliptic_curve::bigint::U256;
        use elliptic_curve::{
            ff::PrimeField,
            ops::BatchInvert,
            subtle::{Choice, ConstantTimeEq, CtOption},
        };

        primefield::monty_field_params! {
            name: FieldParams,
            modulus: MODULUS_HEX,
            uint: U256,
            byte_order: primefield::ByteOrder::BigEndian,
            multiplicative_generator: 7,
            doc: "Montgomery parameters for this curve's field modulus"
        }
        primefield::monty_field_element! {
            name: FieldElement,
            params: FieldParams,
            uint: U256,
            doc: "Element of the base field"
        }
        primefield::monty_field_arithmetic! {
            name: FieldElement,
            params: FieldParams,
            uint: U256
        }
        impl BatchInvert for FieldElement {}

        #[cfg(test)]
        mod tests {
            use super::{FieldElement, U256};
            primefield::test_primefield!(FieldElement, U256);
        }
    }

    /// The scalar field, modulo q.
    // `primefield 0.14.0`'s `monty_field_params!` calls the deprecated
    // `crypto_bigint::Uint::bits`. The call is upstream's, this
    // workspace builds with `-D warnings`, and the attribute is scoped
    // to the module so it stops applying the moment a `primefield`
    // release uses `bit_width`. Same note as `brainpool_p512r1`.
    #[expect(deprecated)]
    mod scalar {
        use super::{GostCryptoProA, ORDER, ORDER_HEX};
        use elliptic_curve::bigint::U256;
        use elliptic_curve::{
            ff::PrimeField,
            ops::BatchInvert,
            scalar::{FromUintUnchecked, IsHigh},
            subtle::{Choice, ConstantTimeEq, ConstantTimeGreater as _, CtOption},
        };

        primefield::monty_field_params! {
            name: ScalarParams,
            modulus: ORDER_HEX,
            uint: U256,
            byte_order: primefield::ByteOrder::BigEndian,
            multiplicative_generator: 2,
            doc: "Montgomery parameters for this curve's scalar modulus"
        }
        primefield::monty_field_element! {
            name: Scalar,
            params: ScalarParams,
            uint: U256,
            doc: "Element of the scalar field"
        }
        primefield::monty_field_arithmetic! {
            name: Scalar,
            params: ScalarParams,
            uint: U256
        }
        primefield::monty_field_reduce! {
            name: Scalar,
            params: ScalarParams,
            uint: U256,
        }
        elliptic_curve::scalar_impls!(GostCryptoProA, Scalar);
        primeorder::wnaf::impl_wnaf_size_for_scalar!(Scalar);
        impl BatchInvert for Scalar {}

        impl AsRef<Scalar> for Scalar {
            fn as_ref(&self) -> &Scalar {
                self
            }
        }
        impl FromUintUnchecked for Scalar {
            type Uint = U256;
            fn from_uint_unchecked(uint: Self::Uint) -> Self {
                Self::from_uint_unchecked(uint)
            }
        }
        impl IsHigh for Scalar {
            fn is_high(&self) -> Choice {
                const MODULUS_SHR1: U256 = ORDER.as_ref().shr_vartime(1);
                self.to_canonical().ct_gt(&MODULUS_SHR1)
            }
        }

        #[cfg(test)]
        mod tests {
            use super::{Scalar, U256};
            primefield::test_primefield!(Scalar, U256);
        }
    }

    pub use self::{field::FieldElement, scalar::Scalar};

    impl elliptic_curve::Curve for GostCryptoProA {
        type FieldBytesSize = elliptic_curve::consts::U32;
        type Uint = U256;
        const ORDER: Odd<U256> = ORDER;
    }
    impl elliptic_curve::PrimeCurve for GostCryptoProA {}
    impl elliptic_curve::point::PointCompression for GostCryptoProA {
        const COMPRESS_POINTS: bool = false;
    }

    /// Affine point on this curve.
    pub type AffinePoint = primeorder::AffinePoint<GostCryptoProA>;
    /// Projective point on this curve.
    pub type ProjectivePoint = primeorder::ProjectivePoint<GostCryptoProA>;

    impl elliptic_curve::CurveArithmetic for GostCryptoProA {
        type AffinePoint = AffinePoint;
        type ProjectivePoint = ProjectivePoint;
        type Scalar = Scalar;
    }
    impl elliptic_curve::hazmat::FieldArithmetic for GostCryptoProA {
        type FieldElement = FieldElement;
    }
    impl elliptic_curve::PrimeCurveArithmetic for GostCryptoProA {
        type CurveGroup = ProjectivePoint;
    }

    impl primeorder::PrimeCurveParams for GostCryptoProA {
        type PointArithmetic = primeorder::point_arithmetic::EquationAIsGeneric;
        type Backend = primeorder::mul_backend::VariableOnly;

        const EQUATION_A: FieldElement = FieldElement::from_hex_vartime(
            "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd94",
        );
        const EQUATION_B: FieldElement = FieldElement::from_hex_vartime(
            "00000000000000000000000000000000000000000000000000000000000000a6",
        );
        const GENERATOR: (FieldElement, FieldElement) = (
            FieldElement::from_hex_vartime(
                "0000000000000000000000000000000000000000000000000000000000000001",
            ),
            FieldElement::from_hex_vartime(
                "8d91e471e0989cda27df505a453f2b7635294f2ddf23e3b122acc99c9e9f1e14",
            ),
        );
    }
}

/// id-GostR3410-2001-TestParamSet (RFC 7091 §7.1)
pub mod test_param_set {
    use elliptic_curve::bigint::{Odd, U256};

    /// The curve.
    #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
    pub struct GostTestParamSet;

    const MODULUS_HEX: &str = "8000000000000000000000000000000000000000000000000000000000000431";
    const ORDER_HEX: &str = "8000000000000000000000000000000150fe8a1892976154c59cfc193accf5b3";
    const ORDER: Odd<U256> = Odd::<U256>::from_be_hex(ORDER_HEX);

    /// The base field, modulo p. Its own module because
    /// `monty_field_params!` emits a `use`.
    // `primefield 0.14.0`'s `monty_field_params!` calls the deprecated
    // `crypto_bigint::Uint::bits`. The call is upstream's, this
    // workspace builds with `-D warnings`, and the attribute is scoped
    // to the module so it stops applying the moment a `primefield`
    // release uses `bit_width`. Same note as `brainpool_p512r1`.
    #[expect(deprecated)]
    mod field {
        use super::MODULUS_HEX;
        use elliptic_curve::bigint::U256;
        use elliptic_curve::{
            ff::PrimeField,
            ops::BatchInvert,
            subtle::{Choice, ConstantTimeEq, CtOption},
        };

        primefield::monty_field_params! {
            name: FieldParams,
            modulus: MODULUS_HEX,
            uint: U256,
            byte_order: primefield::ByteOrder::BigEndian,
            multiplicative_generator: 7,
            doc: "Montgomery parameters for this curve's field modulus"
        }
        primefield::monty_field_element! {
            name: FieldElement,
            params: FieldParams,
            uint: U256,
            doc: "Element of the base field"
        }
        primefield::monty_field_arithmetic! {
            name: FieldElement,
            params: FieldParams,
            uint: U256
        }
        impl BatchInvert for FieldElement {}

        #[cfg(test)]
        mod tests {
            use super::{FieldElement, U256};
            primefield::test_primefield!(FieldElement, U256);
        }
    }

    /// The scalar field, modulo q.
    // `primefield 0.14.0`'s `monty_field_params!` calls the deprecated
    // `crypto_bigint::Uint::bits`. The call is upstream's, this
    // workspace builds with `-D warnings`, and the attribute is scoped
    // to the module so it stops applying the moment a `primefield`
    // release uses `bit_width`. Same note as `brainpool_p512r1`.
    #[expect(deprecated)]
    mod scalar {
        use super::{GostTestParamSet, ORDER, ORDER_HEX};
        use elliptic_curve::bigint::U256;
        use elliptic_curve::{
            ff::PrimeField,
            ops::BatchInvert,
            scalar::{FromUintUnchecked, IsHigh},
            subtle::{Choice, ConstantTimeEq, ConstantTimeGreater as _, CtOption},
        };

        primefield::monty_field_params! {
            name: ScalarParams,
            modulus: ORDER_HEX,
            uint: U256,
            byte_order: primefield::ByteOrder::BigEndian,
            multiplicative_generator: 2,
            doc: "Montgomery parameters for this curve's scalar modulus"
        }
        primefield::monty_field_element! {
            name: Scalar,
            params: ScalarParams,
            uint: U256,
            doc: "Element of the scalar field"
        }
        primefield::monty_field_arithmetic! {
            name: Scalar,
            params: ScalarParams,
            uint: U256
        }
        primefield::monty_field_reduce! {
            name: Scalar,
            params: ScalarParams,
            uint: U256,
        }
        elliptic_curve::scalar_impls!(GostTestParamSet, Scalar);
        primeorder::wnaf::impl_wnaf_size_for_scalar!(Scalar);
        impl BatchInvert for Scalar {}

        impl AsRef<Scalar> for Scalar {
            fn as_ref(&self) -> &Scalar {
                self
            }
        }
        impl FromUintUnchecked for Scalar {
            type Uint = U256;
            fn from_uint_unchecked(uint: Self::Uint) -> Self {
                Self::from_uint_unchecked(uint)
            }
        }
        impl IsHigh for Scalar {
            fn is_high(&self) -> Choice {
                const MODULUS_SHR1: U256 = ORDER.as_ref().shr_vartime(1);
                self.to_canonical().ct_gt(&MODULUS_SHR1)
            }
        }

        #[cfg(test)]
        mod tests {
            use super::{Scalar, U256};
            primefield::test_primefield!(Scalar, U256);
        }
    }

    pub use self::{field::FieldElement, scalar::Scalar};

    impl elliptic_curve::Curve for GostTestParamSet {
        type FieldBytesSize = elliptic_curve::consts::U32;
        type Uint = U256;
        const ORDER: Odd<U256> = ORDER;
    }
    impl elliptic_curve::PrimeCurve for GostTestParamSet {}
    impl elliptic_curve::point::PointCompression for GostTestParamSet {
        const COMPRESS_POINTS: bool = false;
    }

    /// Affine point on this curve.
    pub type AffinePoint = primeorder::AffinePoint<GostTestParamSet>;
    /// Projective point on this curve.
    pub type ProjectivePoint = primeorder::ProjectivePoint<GostTestParamSet>;

    impl elliptic_curve::CurveArithmetic for GostTestParamSet {
        type AffinePoint = AffinePoint;
        type ProjectivePoint = ProjectivePoint;
        type Scalar = Scalar;
    }
    impl elliptic_curve::hazmat::FieldArithmetic for GostTestParamSet {
        type FieldElement = FieldElement;
    }
    impl elliptic_curve::PrimeCurveArithmetic for GostTestParamSet {
        type CurveGroup = ProjectivePoint;
    }

    impl primeorder::PrimeCurveParams for GostTestParamSet {
        type PointArithmetic = primeorder::point_arithmetic::EquationAIsGeneric;
        type Backend = primeorder::mul_backend::VariableOnly;

        const EQUATION_A: FieldElement = FieldElement::from_hex_vartime(
            "0000000000000000000000000000000000000000000000000000000000000007",
        );
        const EQUATION_B: FieldElement = FieldElement::from_hex_vartime(
            "5fbff498aa938ce739b8e022fbafef40563f6e6a3472fc2a514c0ce9dae23b7e",
        );
        const GENERATOR: (FieldElement, FieldElement) = (
            FieldElement::from_hex_vartime(
                "0000000000000000000000000000000000000000000000000000000000000002",
            ),
            FieldElement::from_hex_vartime(
                "08e2a8a0e65147d4bd6316030e16d19c85c97f0a9ca267122b96abbcea7e8fc8",
            ),
        );
    }
}
/// GOST R 34.10 signature verification, RFC 7091 §6.2 ("Algorithm II").
///
/// Defined once per curve by this macro rather than generically, because
/// the `elliptic_curve` trait bounds needed to write it generically are
/// considerably longer than the function.
///
/// Every argument is a 32-octet **big-endian** integer, so the caller
/// owns the byte-order conversions that RFC 4491 makes inconsistent
/// between the key and the signature. That is deliberate: the orders are
/// the part of GOST most likely to be got wrong, and keeping them out of
/// here means the arithmetic can be checked against the RFC's test
/// vector without any encoding in the way.
macro_rules! gost_verify_for_curve {
    ($fn_name:ident, $curve:ty, $scalar:ty) => {
        /// `true` when the signature verifies.
        ///
        /// `e_be` is the message representative from RFC 7091 §6.2 step
        /// 3, already reduced to 32 big-endian octets by the caller.
        pub fn $fn_name(
            qx_be: &[u8; 32],
            qy_be: &[u8; 32],
            r_be: &[u8; 32],
            s_be: &[u8; 32],
            e_be: &[u8; 32],
        ) -> bool {
            use elliptic_curve::{
                PrimeField as _, bigint::U256, point::AffineCoordinates as _,
                sec1::FromSec1Point as _,
            };

            // Step 1: 0 < r < q and 0 < s < q. `from_repr` is the check
            // -- it returns `None` for a value at or above the modulus --
            // and the zero test is explicit.
            let r = <$scalar>::from_repr((*r_be).into());
            let s = <$scalar>::from_repr((*s_be).into());
            let (Some(r), Some(s)) = (Option::<$scalar>::from(r), Option::<$scalar>::from(s))
            else {
                return false;
            };
            if bool::from(r.is_zero()) || bool::from(s.is_zero()) {
                return false;
            }

            // Step 3: e = alpha mod q, and e = 1 when that is zero.
            // `reduce` rather than `from_repr`: alpha is a hash and may
            // exceed q, which is not an error here but a reduction.
            let e = <$scalar as elliptic_curve::bigint::Reduce<U256>>::reduce(
                &U256::from_be_slice(e_be),
            );
            let e = if bool::from(e.is_zero()) {
                <$scalar>::ONE
            } else {
                e
            };

            // Step 4: v = e^-1 mod q. `e` is non-zero by the line above,
            // so the inverse exists.
            let Some(v) = Option::<$scalar>::from(e.invert()) else {
                return false;
            };

            // Step 5: z1 = s*v, z2 = -r*v.
            let z1 = s * v;
            let z2 = -(r * v);

            // The verification key as a point, via its SEC1 uncompressed
            // encoding. Going through SEC1 rather than setting
            // coordinates directly is what checks that Q is actually on
            // the curve: a point that is not is refused here instead of
            // producing arithmetic on a curve nobody specified.
            let mut sec1 = [0u8; 65];
            sec1[0] = 0x04;
            sec1[1..33].copy_from_slice(qx_be);
            sec1[33..65].copy_from_slice(qy_be);
            let Ok(point) = elliptic_curve::sec1::Sec1Point::<$curve>::from_bytes(&sec1) else {
                return false;
            };
            let q_affine = Option::<primeorder::AffinePoint<$curve>>::from(
                primeorder::AffinePoint::<$curve>::from_sec1_point(&point),
            );
            let Some(q_affine) = q_affine else {
                return false;
            };

            // Step 6: C = z1*P + z2*Q, then R = x_C mod q.
            let generator = primeorder::ProjectivePoint::<$curve>::GENERATOR;
            let c = generator * z1 + primeorder::ProjectivePoint::<$curve>::from(q_affine) * z2;
            // The identity has no x-coordinate to compare, so a signature
            // that produces it cannot verify. Checked on the projective
            // point, before `to_affine` has to invent coordinates for it.
            if bool::from(elliptic_curve::group::Group::is_identity(&c)) {
                return false;
            }
            let x_c = c.to_affine().x();
            // x_C is a FIELD element and R is a SCALAR: the comparison in
            // step 6 is `x_C mod q`, and p != q, so reducing is required
            // rather than a reinterpretation of the same number.
            let big_r = <$scalar as elliptic_curve::bigint::Reduce<U256>>::reduce(
                &U256::from_be_slice(&x_c),
            );

            // Step 7.
            big_r == r
        }
    };
}

gost_verify_for_curve!(
    verify_cryptopro_a,
    cryptopro_a::GostCryptoProA,
    cryptopro_a::Scalar
);
gost_verify_for_curve!(
    verify_test_param_set,
    test_param_set::GostTestParamSet,
    test_param_set::Scalar
);