synta-python 0.1.4

Python extension module for the synta ASN.1 library
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Python bindings for Kerberos V5 and PKINIT types from [`synta_krb5`].
//!
//! This module builds the ``synta.krb5`` Python submodule, exposing the
//! Kerberos V5 and PKINIT ASN.1 types needed for certificate construction
//! and for parsing Kerberos AS exchanges.
//!
//! # Contents
//!
//! ## Principal-name support
//!
//! * [`PyKrb5PrincipalName`] — the RFC 4556 `KRB5PrincipalName` OtherName
//!   value embedded in PKINIT certificates.
//! * `KRB5_PRINCIPAL_NAME_OID` — `ObjectIdentifier` for `id-pkinit-san`
//!   (1.3.6.1.5.2.2, RFC 4556 §3.2.2).
//! * `NT_*` integer constants — principal name types from RFC 4120 §6.2.
//!
//! ## PKINIT protocol types (RFC 4556 + RFC 6112 + RFC 8636)
//!
//! Provided by [`crate::pkinit::register_pkinit_classes`]:
//!
//! | Python class                  | RFC / section       | Description                                    |
//! |-------------------------------|---------------------|------------------------------------------------|
//! | `EncryptionKey`               | RFC 3961 §2         | Algorithm type and raw key material            |
//! | `Checksum`                    | RFC 3961 §4         | Algorithm type and raw checksum bytes          |
//! | `KDFAlgorithmId`              | RFC 8636 §3.1       | KDF OID used in the PKINIT exchange            |
//! | `IssuerAndSerialNumber`       | RFC 4556 §3.2.2     | Certificate identified by issuer + serial      |
//! | `ExternalPrincipalIdentifier` | RFC 4556 §3.2.2     | Certificate by name, issuer/serial, or SKI     |
//! | `PKAuthenticator`             | RFC 4556 §3.2.1     | Client proof of liveness in AS-REQ             |
//! | `AuthPack`                    | RFC 4556 §3.2.1     | Signed client authentication package           |
//! | `PaPkAsReq`                   | RFC 4556 §3.2.2     | PKINIT pre-authentication request              |
//! | `DHRepInfo`                   | RFC 4556 §3.2.4     | KDC Diffie-Hellman reply data                  |
//! | `KDCDHKeyInfo`                | RFC 4556 §3.2.4     | KDC DH public key and nonce                   |
//! | `ReplyKeyPack`                | RFC 4556 §3.2.3     | Session key and checksum from KDC              |
//! | `PaPkAsRep`                   | RFC 4556 §3.2.4     | PKINIT pre-authentication reply (CHOICE)       |
//!
//! # Principal name types (`NT_*`)
//!
//! | Constant           | Value | RFC / source     | Typical use                          |
//! |--------------------|-------|------------------|--------------------------------------|
//! | `NT_UNKNOWN`       | 0     | RFC 4120 §6.2    | Unknown / unspecified                |
//! | `NT_PRINCIPAL`     | 1     | RFC 4120 §6.2    | User or host principal               |
//! | `NT_SRV_INST`      | 2     | RFC 4120 §6.2    | Service + instance (e.g. `krbtgt`)   |
//! | `NT_SRV_HST`       | 3     | RFC 4120 §6.2    | Service + hostname                   |
//! | `NT_SRV_XHST`      | 4     | RFC 4120 §6.2    | Service + host (remaining components)|
//! | `NT_UID`           | 5     | RFC 4120 §6.2    | Unique ID                            |
//! | `NT_X500_PRINCIPAL`| 6     | RFC 4120 §6.2    | Encoded X.500 DN                     |
//! | `NT_SMTP_NAME`     | 7     | RFC 4120 §6.2    | SMTP email address                   |
//! | `NT_ENTERPRISE`    | 10    | RFC 6806 §5      | Enterprise principal (UPN-like)      |
//! | `NT_WELLKNOWN`     | 11    | RFC 8062 §3      | Well-known principal (anonymous)     |
//! | `NT_SRV_HST_DOMAIN`| 12    | MS-SFU §2.1      | Host-based service (Windows)         |
//!
//! # Register
//!
//! Call [`register_krb5_module`] from the extension crate's `#[pymodule]`:
//!
//! ```rust,ignore
//! krb5::register_krb5_module(m)?;
//! ```

use pyo3::prelude::*;
use pyo3::types::PyBytes;

use synta::tag::{TagClass, TAG_SEQUENCE};
use synta::traits::{Decode, Encode};
use synta::{Decoder, Encoder, Encoding};

use synta_krb5::constants::{
    ETYPE_AES128_CTS_HMAC_SHA1_96, ETYPE_AES128_CTS_HMAC_SHA256_128, ETYPE_AES256_CTS_HMAC_SHA1_96,
    ETYPE_AES256_CTS_HMAC_SHA384_192, ETYPE_CAMELLIA128_CTS_CMAC, ETYPE_CAMELLIA256_CTS_CMAC,
    ETYPE_DES3_CBC_MD5, ETYPE_DES3_CBC_SHA1, ETYPE_DES3_CBC_SHA1_KD, ETYPE_DES_CBC_CRC,
    ETYPE_DES_CBC_MD4, ETYPE_DES_CBC_MD5, ETYPE_DES_HMAC_SHA1, ETYPE_RC4_HMAC, ETYPE_RC4_HMAC_EXP,
    ID_PKINIT_SAN_COMPONENTS, NT_ENTERPRISE, NT_PRINCIPAL, NT_SMTP_NAME, NT_SRV_HST,
    NT_SRV_HST_DOMAIN, NT_SRV_INST, NT_SRV_XHST, NT_UID, NT_UNKNOWN, NT_WELLKNOWN,
    NT_X500_PRINCIPAL,
};
use synta_krb5::kerberos_v5::Int32;

use crate::error::SyntaErr;
use crate::types::PyObjectIdentifier;

/// Build a `PyObjectIdentifier` from a slice of OID arc components.
///
/// Returns `Err` only on OOM; the components are hardcoded constants
/// that are always valid OIDs.
fn oid_const(py: Python<'_>, components: &[u32]) -> PyResult<Py<pyo3::PyAny>> {
    use synta::ObjectIdentifier;
    let inner = ObjectIdentifier::new(components).expect("hardcoded OID is always valid");
    Ok(Py::new(py, PyObjectIdentifier::from_oid(inner))?.into_any())
}

// ─── encoding helpers ────────────────────────────────────────────────────────

/// Append a SEQUENCE TLV wrapping `inner` to `enc`.
fn write_sequence(enc: &mut Encoder, inner: &[u8]) -> Result<(), synta::Error> {
    enc.write_tag(synta::Tag::universal_constructed(TAG_SEQUENCE))?;
    enc.write_length(inner.len())?;
    enc.write_bytes(inner);
    Ok(())
}

/// Append a context-specific explicit tag `[tag_num]` wrapping `inner`.
fn write_explicit_ctx(enc: &mut Encoder, tag_num: u32, inner: &[u8]) -> Result<(), synta::Error> {
    enc.write_tag(synta::Tag::new(TagClass::ContextSpecific, true, tag_num))?;
    enc.write_length(inner.len())?;
    enc.write_bytes(inner);
    Ok(())
}

/// Encode `value` as DER, returning the bytes.
fn encode_to_vec<T: Encode>(value: &T) -> Result<Vec<u8>, synta::Error> {
    let mut enc = Encoder::new(Encoding::Der);
    value.encode(&mut enc)?;
    enc.finish()
}

// ─── decoding helpers ────────────────────────────────────────────────────────

fn read_tag_check(
    dec: &mut Decoder<'_>,
    class: TagClass,
    number: u32,
    constructed: bool,
    label: &'static str,
) -> PyResult<()> {
    let tag = dec.read_tag().map_err(SyntaErr)?;
    if tag.class() != class || tag.number() != number || tag.is_constructed() != constructed {
        return Err(pyo3::exceptions::PyValueError::new_err(format!(
            "KRB5PrincipalName: expected {label} (class={class:?}, tag={number}), \
             got class={:?} tag={} constructed={}",
            tag.class(),
            tag.number(),
            tag.is_constructed()
        )));
    }
    Ok(())
}

fn read_definite_len(dec: &mut Decoder<'_>) -> PyResult<usize> {
    Ok(dec
        .read_length()
        .map_err(SyntaErr)?
        .definite()
        .map_err(SyntaErr)?)
}

/// Read a constructed TLV with the given tag and return the content bytes.
fn read_content<'a>(
    dec: &mut Decoder<'a>,
    class: TagClass,
    number: u32,
    label: &'static str,
) -> PyResult<&'a [u8]> {
    read_tag_check(dec, class, number, true, label)?;
    let len = read_definite_len(dec)?;
    Ok(dec.read_bytes(len).map_err(SyntaErr)?)
}

/// Read a SEQUENCE and return its content bytes.
fn read_sequence<'a>(dec: &mut Decoder<'a>, label: &'static str) -> PyResult<&'a [u8]> {
    read_content(dec, TagClass::Universal, TAG_SEQUENCE, label)
}

/// Read a context-specific explicit tag `[N]` and return its content bytes.
fn read_explicit_ctx<'a>(
    dec: &mut Decoder<'a>,
    tag_num: u32,
    label: &'static str,
) -> PyResult<&'a [u8]> {
    read_content(dec, TagClass::ContextSpecific, tag_num, label)
}

// ─── KRB5PrincipalName encode / decode ──────────────────────────────────────

/// Encode a `KRB5PrincipalName` (RFC 4556) SEQUENCE to DER.
///
/// ```asn1
/// KRB5PrincipalName ::= SEQUENCE {
///     realm         [0] GeneralString,
///     principalName [1] PrincipalName
/// }
/// PrincipalName ::= SEQUENCE {
///     name-type   [0] Int32,
///     name-string [1] SEQUENCE OF GeneralString
/// }
/// ```
fn encode_krb5principalname(
    realm: &str,
    name_type: i32,
    components: &[String],
) -> PyResult<Vec<u8>> {
    // 1. name-string: SEQUENCE OF GeneralString
    let ns_items: Result<Vec<Vec<u8>>, synta::Error> = components
        .iter()
        .map(|c| encode_to_vec(&synta::GeneralString::new(c.as_bytes().to_vec())))
        .collect();
    let ns_items = ns_items.map_err(SyntaErr)?;
    let ns_flat: Vec<u8> = ns_items.concat();

    let mut ns_seq_enc = Encoder::new(Encoding::Der);
    write_sequence(&mut ns_seq_enc, &ns_flat).map_err(SyntaErr)?;
    let ns_seq_bytes = ns_seq_enc.finish().map_err(SyntaErr)?;

    // 2. name-type: INTEGER
    let nt_bytes = encode_to_vec(&synta::Integer::from_i64(name_type as i64)).map_err(SyntaErr)?;

    // 3. PrincipalName = SEQUENCE { [0] name-type, [1] name-string }
    let mut nt_ctx = Encoder::new(Encoding::Der);
    write_explicit_ctx(&mut nt_ctx, 0, &nt_bytes).map_err(SyntaErr)?;
    let nt_ctx_bytes = nt_ctx.finish().map_err(SyntaErr)?;

    let mut ns_ctx = Encoder::new(Encoding::Der);
    write_explicit_ctx(&mut ns_ctx, 1, &ns_seq_bytes).map_err(SyntaErr)?;
    let ns_ctx_bytes = ns_ctx.finish().map_err(SyntaErr)?;

    let pn_inner = [nt_ctx_bytes, ns_ctx_bytes].concat();
    let mut pn_enc = Encoder::new(Encoding::Der);
    write_sequence(&mut pn_enc, &pn_inner).map_err(SyntaErr)?;
    let pn_bytes = pn_enc.finish().map_err(SyntaErr)?;

    // 4. realm: GeneralString
    let realm_gs_bytes =
        encode_to_vec(&synta::GeneralString::new(realm.as_bytes().to_vec())).map_err(SyntaErr)?;

    // 5. Outer SEQUENCE { [0] realm, [1] principalName }
    let mut realm_ctx = Encoder::new(Encoding::Der);
    write_explicit_ctx(&mut realm_ctx, 0, &realm_gs_bytes).map_err(SyntaErr)?;
    let realm_ctx_bytes = realm_ctx.finish().map_err(SyntaErr)?;

    let mut pn_ctx = Encoder::new(Encoding::Der);
    write_explicit_ctx(&mut pn_ctx, 1, &pn_bytes).map_err(SyntaErr)?;
    let pn_ctx_bytes = pn_ctx.finish().map_err(SyntaErr)?;

    let outer_content = [realm_ctx_bytes, pn_ctx_bytes].concat();
    let mut outer = Encoder::new(Encoding::Der);
    write_sequence(&mut outer, &outer_content).map_err(SyntaErr)?;
    Ok(outer.finish().map_err(SyntaErr)?)
}

/// Decode a `KRB5PrincipalName` (RFC 4556) DER blob.
///
/// Returns `(realm, name_type, components)`.
fn decode_krb5principalname(data: &[u8]) -> PyResult<(String, i32, Vec<String>)> {
    let ve = |s: &str| pyo3::exceptions::PyValueError::new_err(s.to_string());

    // Outer SEQUENCE
    let mut outer = Decoder::new(data, Encoding::Der);
    let outer_content = read_sequence(&mut outer, "outer SEQUENCE")?;

    // [0] realm GeneralString
    let mut seq = Decoder::new(outer_content, Encoding::Der);
    let realm_bytes = read_explicit_ctx(&mut seq, 0, "[0] realm")?;
    let mut realm_dec = Decoder::new(realm_bytes, Encoding::Der);
    let realm_gs = synta::GeneralString::decode(&mut realm_dec).map_err(SyntaErr)?;
    let realm = String::from_utf8(realm_gs.as_bytes().to_vec())
        .map_err(|_| ve("KRB5PrincipalName: realm is not valid UTF-8"))?;

    // [1] principalName PrincipalName
    let pn_bytes = read_explicit_ctx(&mut seq, 1, "[1] principalName")?;

    // PrincipalName SEQUENCE
    let mut pn_dec = Decoder::new(pn_bytes, Encoding::Der);
    let pn_inner = read_sequence(&mut pn_dec, "PrincipalName SEQUENCE")?;

    // [0] name-type Int32
    let mut pn_inner_dec = Decoder::new(pn_inner, Encoding::Der);
    let nt_bytes = read_explicit_ctx(&mut pn_inner_dec, 0, "[0] name-type")?;
    let mut nt_dec = Decoder::new(nt_bytes, Encoding::Der);
    let int32 = Int32::decode(&mut nt_dec).map_err(SyntaErr)?;
    let name_type = int32.get();

    // [1] name-string SEQUENCE OF GeneralString
    let ns_ctx_bytes = read_explicit_ctx(&mut pn_inner_dec, 1, "[1] name-string")?;
    let mut ns_ctx_dec = Decoder::new(ns_ctx_bytes, Encoding::Der);
    let ns_bytes = read_sequence(&mut ns_ctx_dec, "name-string SEQUENCE")?;

    let mut components = Vec::new();
    let mut ns_dec = Decoder::new(ns_bytes, Encoding::Der);
    while !ns_dec.is_empty() {
        let gs = synta::GeneralString::decode(&mut ns_dec).map_err(SyntaErr)?;
        let s = String::from_utf8(gs.as_bytes().to_vec())
            .map_err(|_| ve("KRB5PrincipalName: name component is not valid UTF-8"))?;
        components.push(s);
    }

    Ok((realm, name_type, components))
}

// ─── Python class ────────────────────────────────────────────────────────────

/// RFC 4556 ``KRB5PrincipalName`` — Kerberos principal embedded in a PKINIT
/// certificate as an ``OtherName`` Subject Alternative Name.
///
/// ``KRB5PrincipalName`` is defined in RFC 4556 §3.2.2 as:
///
/// ```text
/// KRB5PrincipalName ::= SEQUENCE {
///     realm         [0] Realm,          -- GeneralString
///     principalName [1] PrincipalName   -- RFC 4120 §5.2.2
/// }
///
/// PrincipalName ::= SEQUENCE {
///     name-type   [0] Int32,
///     name-string [1] SEQUENCE OF KerberosString  -- GeneralString
/// }
/// ```
///
/// The ``OtherName`` OID for this type is ``1.3.6.1.5.2.2``,
/// available as ``synta.krb5.KRB5_PRINCIPAL_NAME_OID``.
///
/// **Name types** — use the ``NT_*`` module constants:
///
/// * ``NT_PRINCIPAL`` (1) — user principal, e.g. ``alice@EXAMPLE.COM``
/// * ``NT_SRV_INST``  (2) — service + instance, e.g. ``krbtgt/EXAMPLE.COM``
/// * ``NT_SRV_HST``   (3) — service + hostname, e.g. ``host/server.example.com``
/// * ``NT_ENTERPRISE`` (10) — enterprise (UPN-style), e.g. ``user@domain.example``
///
/// **Display format**: Kerberos principal strings conventionally use
/// ``/`` to join components and ``@`` to separate from the realm:
/// ``service/instance@REALM``.  This class stores the components and realm
/// individually; format them yourself if you need a display string.
///
/// Example — PKINIT TGT principal for ``EXAMPLE.COM``:
///
/// ```python
/// import synta.krb5
///
/// name = synta.krb5.Krb5PrincipalName(
///     realm="EXAMPLE.COM",
///     name_type=synta.krb5.NT_SRV_INST,
///     components=["krbtgt", "EXAMPLE.COM"],
/// )
/// # OID for OtherName: synta.krb5.KRB5_PRINCIPAL_NAME_OID  (1.3.6.1.5.2.2)
/// der_bytes = name.to_der()   # DER SEQUENCE bytes for OtherName.value
/// ```
///
/// Example — decode from an OtherName SAN value:
///
/// ```python
/// parsed = synta.krb5.Krb5PrincipalName.from_der(der_bytes)
/// print(parsed.realm)              # "EXAMPLE.COM"
/// print("/".join(parsed.components) + "@" + parsed.realm)
/// # "krbtgt/EXAMPLE.COM@EXAMPLE.COM"
/// ```
#[pyclass(name = "Krb5PrincipalName", frozen)]
pub struct PyKrb5PrincipalName {
    realm: String,
    name_type: i32,
    components: Vec<String>,
}

#[pymethods]
impl PyKrb5PrincipalName {
    /// Create a new ``Krb5PrincipalName``.
    ///
    /// Args:
    ///     realm: Kerberos realm (ASCII string, e.g. ``"EXAMPLE.COM"``).
    ///     name_type: Principal name type.  Use one of the ``NT_*`` module
    ///         constants: ``NT_PRINCIPAL``, ``NT_SRV_INST``, ``NT_SRV_HST``,
    ///         ``NT_ENTERPRISE``, etc.
    ///     components: Name-string components.  The number and meaning of
    ///         components depends on ``name_type``:
    ///
    ///         * ``NT_PRINCIPAL`` — one component: the user name.
    ///         * ``NT_SRV_INST`` — two components: service name and instance
    ///           (e.g. ``["krbtgt", "EXAMPLE.COM"]``).
    ///         * ``NT_SRV_HST`` — two components: service name and hostname
    ///           (e.g. ``["host", "server.example.com"]``).
    ///         * ``NT_ENTERPRISE`` — one component: the enterprise name.
    ///
    /// Raises ``ValueError`` if ``realm`` or any component contains characters
    /// outside ASCII (Kerberos strings are ``GeneralString``, which is a subset
    /// of ASCII in practice).
    #[new]
    #[pyo3(signature = (realm, name_type, components))]
    fn new(realm: String, name_type: i32, components: Vec<String>) -> PyResult<Self> {
        if !realm.is_ascii() {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "realm must be an ASCII string",
            ));
        }
        for comp in &components {
            if !comp.is_ascii() {
                return Err(pyo3::exceptions::PyValueError::new_err(format!(
                    "name component {comp:?} must be an ASCII string"
                )));
            }
        }
        Ok(Self {
            realm,
            name_type,
            components,
        })
    }

    /// Kerberos realm string (e.g. ``"EXAMPLE.COM"``).
    ///
    /// Always ASCII.  Conventionally upper-case DNS domain name.
    #[getter]
    fn realm(&self) -> &str {
        &self.realm
    }

    /// Principal name type integer (one of the ``NT_*`` module constants).
    ///
    /// Common values: ``NT_PRINCIPAL`` (1), ``NT_SRV_INST`` (2),
    /// ``NT_SRV_HST`` (3), ``NT_ENTERPRISE`` (10).
    #[getter]
    fn name_type(&self) -> i32 {
        self.name_type
    }

    /// Name-string components as a list of ASCII strings.
    ///
    /// The list length and semantics depend on ``name_type``.  For
    /// ``NT_SRV_INST`` the conventional display form joins components with
    /// ``"/"`` and appends ``"@" + realm``, e.g.:
    ///
    /// ```python
    /// "/".join(name.components) + "@" + name.realm
    /// # -> "krbtgt/EXAMPLE.COM@EXAMPLE.COM"
    /// ```
    #[getter]
    fn components<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PyList>> {
        pyo3::types::PyList::new(py, self.components.iter())
    }

    /// Encode this ``Krb5PrincipalName`` to DER bytes.
    ///
    /// Returns the complete DER encoding of the ``KRB5PrincipalName``
    /// ``SEQUENCE``.  These bytes are the ``value`` field of an X.509
    /// ``OtherName`` SAN with OID ``1.3.6.1.5.2.2`` (id-pkinit-san).
    ///
    /// Example — build an OtherName value for a PKINIT TGT principal:
    ///
    /// ```python
    /// import synta.krb5
    ///
    /// name = synta.krb5.Krb5PrincipalName("EXAMPLE.COM", synta.krb5.NT_SRV_INST,
    ///                                      ["krbtgt", "EXAMPLE.COM"])
    /// oid = synta.krb5.KRB5_PRINCIPAL_NAME_OID   # ObjectIdentifier("1.3.6.1.5.2.2")
    /// other_name_value = name.to_der()
    /// # Pass (oid, other_name_value) to your X.509 library's OtherName constructor.
    /// ```
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let der = encode_krb5principalname(&self.realm, self.name_type, &self.components)?;
        Ok(PyBytes::new(py, &der))
    }

    /// Decode a ``Krb5PrincipalName`` from DER bytes.
    ///
    /// Parses the DER encoding of a ``KRB5PrincipalName`` SEQUENCE as it
    /// appears in the ``value`` field of an X.509 ``OtherName`` SAN with
    /// OID ``1.3.6.1.5.2.2``.
    ///
    /// Args:
    ///     data: DER-encoded ``KRB5PrincipalName`` SEQUENCE bytes.
    ///
    /// Returns a new ``Krb5PrincipalName`` instance.
    ///
    /// Raises ``ValueError`` on malformed or truncated input.
    ///
    /// Example — decode a ``KRB5PrincipalName`` from a certificate OtherName:
    ///
    /// ```python
    /// import synta, synta.krb5, synta.oids
    ///
    /// cert = synta.Certificate.from_der(der)
    /// san_der = cert.get_extension_value_der(synta.oids.SUBJECT_ALT_NAME)
    /// # ... extract the OtherName value bytes from the SAN extension ...
    /// # Check OtherName OID == synta.krb5.KRB5_PRINCIPAL_NAME_OID
    /// name = synta.krb5.Krb5PrincipalName.from_der(other_name_value)
    /// print(name.realm, name.name_type, name.components)
    /// ```
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let (realm, name_type, components) = decode_krb5principalname(data)?;
        Ok(Self {
            realm,
            name_type,
            components,
        })
    }

    /// Return a developer-readable string representation.
    ///
    /// Example:
    ///
    /// ```python
    /// >>> repr(synta.krb5.Krb5PrincipalName("EXAMPLE.COM", 2, ["krbtgt", "EXAMPLE.COM"]))
    /// "Krb5PrincipalName(realm='EXAMPLE.COM', name_type=2, components=['krbtgt', 'EXAMPLE.COM'])"
    /// ```
    fn __repr__(&self) -> String {
        format!(
            "Krb5PrincipalName(realm={:?}, name_type={}, components={:?})",
            self.realm, self.name_type, self.components
        )
    }

    /// Return ``True`` if both instances have identical realm, name_type,
    /// and components.
    fn __eq__(&self, other: PyRef<'_, Self>) -> bool {
        self.realm == other.realm
            && self.name_type == other.name_type
            && self.components == other.components
    }
}

// ─── submodule registration ──────────────────────────────────────────────────

/// Build and register the ``synta.krb5`` submodule into `parent`.
///
/// Adds the following to the submodule:
///
/// **Classes** — principal-name support:
/// `Krb5PrincipalName`
///
/// **Classes** — PKINIT protocol types (RFC 4556 + RFC 6112 + RFC 8636):
/// `EncryptionKey`, `Checksum`, `KDFAlgorithmId`, `IssuerAndSerialNumber`,
/// `ExternalPrincipalIdentifier`, `PKAuthenticator`, `AuthPack`, `PaPkAsReq`,
/// `DHRepInfo`, `KDCDHKeyInfo`, `ReplyKeyPack`, `PaPkAsRep`
///
/// **OID constant**: `KRB5_PRINCIPAL_NAME_OID` — `ObjectIdentifier` for
/// `id-pkinit-san` (1.3.6.1.5.2.2, RFC 4556 §3.2.2).
///
/// **Name-type constants** (RFC 4120 §6.2):
/// `NT_UNKNOWN`, `NT_PRINCIPAL`, `NT_SRV_INST`, `NT_SRV_HST`, `NT_SRV_XHST`,
/// `NT_UID`, `NT_X500_PRINCIPAL`, `NT_SMTP_NAME`, `NT_ENTERPRISE`,
/// `NT_WELLKNOWN`, `NT_SRV_HST_DOMAIN`
///
/// **Encryption-type constants** (RFC 3961 / RFC 3962 / RFC 6803 / RFC 8009):
/// `ETYPE_DES_CBC_CRC`, `ETYPE_DES_CBC_MD4`, `ETYPE_DES_CBC_MD5`,
/// `ETYPE_DES3_CBC_MD5`, `ETYPE_DES3_CBC_SHA1`, `ETYPE_DES_HMAC_SHA1`,
/// `ETYPE_DES3_CBC_SHA1_KD`, `ETYPE_AES128_CTS_HMAC_SHA1_96`,
/// `ETYPE_AES256_CTS_HMAC_SHA1_96`, `ETYPE_AES128_CTS_HMAC_SHA256_128`,
/// `ETYPE_AES256_CTS_HMAC_SHA384_192`, `ETYPE_RC4_HMAC`, `ETYPE_RC4_HMAC_EXP`,
/// `ETYPE_CAMELLIA128_CTS_CMAC`, `ETYPE_CAMELLIA256_CTS_CMAC`
///
/// Also installs the submodule into `sys.modules["synta.krb5"]` so that
/// ``import synta.krb5`` and ``from synta.krb5 import ...`` work after
/// ``import synta``.
pub fn register_krb5_module(parent: &Bound<'_, PyModule>) -> PyResult<()> {
    let py = parent.py();
    let m = PyModule::new(py, "krb5")?;

    // Principal name type constants (RFC 4120 §6.2)
    m.add("NT_UNKNOWN", NT_UNKNOWN)?;
    m.add("NT_PRINCIPAL", NT_PRINCIPAL)?;
    m.add("NT_SRV_INST", NT_SRV_INST)?;
    m.add("NT_SRV_HST", NT_SRV_HST)?;
    m.add("NT_SRV_XHST", NT_SRV_XHST)?;
    m.add("NT_UID", NT_UID)?;
    m.add("NT_X500_PRINCIPAL", NT_X500_PRINCIPAL)?;
    m.add("NT_SMTP_NAME", NT_SMTP_NAME)?;
    m.add("NT_ENTERPRISE", NT_ENTERPRISE)?;
    m.add("NT_WELLKNOWN", NT_WELLKNOWN)?;
    m.add("NT_SRV_HST_DOMAIN", NT_SRV_HST_DOMAIN)?;

    // Encryption type constants (RFC 3961, RFC 3962, RFC 6803, RFC 8009)
    m.add("ETYPE_DES_CBC_CRC", ETYPE_DES_CBC_CRC)?;
    m.add("ETYPE_DES_CBC_MD4", ETYPE_DES_CBC_MD4)?;
    m.add("ETYPE_DES_CBC_MD5", ETYPE_DES_CBC_MD5)?;
    m.add("ETYPE_DES3_CBC_MD5", ETYPE_DES3_CBC_MD5)?;
    m.add("ETYPE_DES3_CBC_SHA1", ETYPE_DES3_CBC_SHA1)?;
    m.add("ETYPE_DES_HMAC_SHA1", ETYPE_DES_HMAC_SHA1)?;
    m.add("ETYPE_DES3_CBC_SHA1_KD", ETYPE_DES3_CBC_SHA1_KD)?;
    m.add(
        "ETYPE_AES128_CTS_HMAC_SHA1_96",
        ETYPE_AES128_CTS_HMAC_SHA1_96,
    )?;
    m.add(
        "ETYPE_AES256_CTS_HMAC_SHA1_96",
        ETYPE_AES256_CTS_HMAC_SHA1_96,
    )?;
    m.add(
        "ETYPE_AES128_CTS_HMAC_SHA256_128",
        ETYPE_AES128_CTS_HMAC_SHA256_128,
    )?;
    m.add(
        "ETYPE_AES256_CTS_HMAC_SHA384_192",
        ETYPE_AES256_CTS_HMAC_SHA384_192,
    )?;
    m.add("ETYPE_RC4_HMAC", ETYPE_RC4_HMAC)?;
    m.add("ETYPE_RC4_HMAC_EXP", ETYPE_RC4_HMAC_EXP)?;
    m.add("ETYPE_CAMELLIA128_CTS_CMAC", ETYPE_CAMELLIA128_CTS_CMAC)?;
    m.add("ETYPE_CAMELLIA256_CTS_CMAC", ETYPE_CAMELLIA256_CTS_CMAC)?;

    // OID constants
    m.add(
        "KRB5_PRINCIPAL_NAME_OID",
        oid_const(py, ID_PKINIT_SAN_COMPONENTS)?,
    )?;

    // KRB5PrincipalName class
    m.add_class::<PyKrb5PrincipalName>()?;

    // PKINIT protocol types (RFC 4556 + RFC 6112 + RFC 8636)
    crate::pkinit::register_pkinit_classes(&m)?;

    crate::install_submodule(
        parent,
        &m,
        "synta.krb5",
        Some(
            "Kerberos V5 ASN.1 types: principal names, PKINIT protocol types, \
             name-type constants (NT_*), and encryption-type constants (ETYPE_*).",
        ),
    )
}