matc 0.1.3

Matter protocol library (controller side)
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
use anyhow::Result;
use clap::{Parser, Subcommand};
use matc::util::asn1;
use matc::util::cryptoutil::{
    read_data_from_pem, read_private_key_from_pem, secret_key_to_rfc5915, sha1_enc, write_pem,
};
use std::time::{Duration, SystemTime};
use x509_cert::der::{Decode, Encode};

const OID_SIG_ECDSA_WITH_SHA256: &str = "1.2.840.10045.4.3.2";
const OID_EC_PUBLIC_KEY: &str = "1.2.840.10045.2.1";
const OID_P256: &str = "1.2.840.10045.3.1.7";
const OID_CN: &str = "2.5.4.3";
const OID_MATTER_VENDOR_ID: &str = "1.3.6.1.4.1.37244.2.1";
const OID_MATTER_PRODUCT_ID: &str = "1.3.6.1.4.1.37244.2.2";
const OID_BASIC_CONSTRAINTS: &str = "2.5.29.19";
const OID_KEY_USAGE: &str = "2.5.29.15";
const OID_SKID: &str = "2.5.29.14";
const OID_AKID: &str = "2.5.29.35";

#[derive(Parser)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
#[allow(clippy::enum_variant_names)]
enum Commands {
    /// Create a self-signed CA certificate (PAA-style)
    CreateCa {
        #[arg(long, default_value = "Matter PAA")]
        cn: String,
        #[arg(long)]
        vendor_id: u16,
        #[arg(long, default_value = "paa-cert.pem")]
        out_cert: String,
        #[arg(long, default_value = "paa-key.pem")]
        out_key: String,
        #[arg(long, default_value = "30")]
        validity_years: u32,
    },
    /// Create an intermediate CA certificate (PAI-style) signed by the PAA
    CreatePai {
        #[arg(long, default_value = "Matter PAI")]
        cn: String,
        #[arg(long)]
        vendor_id: u16,
        #[arg(long, default_value = "paa-cert.pem")]
        ca_cert: String,
        #[arg(long, default_value = "paa-key.pem")]
        ca_key: String,
        #[arg(long, default_value = "pai-cert.pem")]
        out_cert: String,
        #[arg(long, default_value = "pai-key.pem")]
        out_key: String,
        #[arg(long, default_value = "20")]
        validity_years: u32,
    },
    /// Create a leaf certificate signed by the CA (DAC-style)
    CreateDac {
        #[arg(long, default_value = "Matter Device")]
        cn: String,
        #[arg(long)]
        vendor_id: u16,
        #[arg(long)]
        product_id: u16,
        #[arg(long, default_value = "paa-cert.pem")]
        ca_cert: String,
        #[arg(long, default_value = "paa-key.pem")]
        ca_key: String,
        #[arg(long, default_value = "dac-cert.pem")]
        out_cert: String,
        #[arg(long, default_value = "dac-key.pem")]
        out_key: String,
        #[arg(long, default_value = "10")]
        validity_years: u32,
    },
}

/// Append a DER INTEGER tag+length+value for a u64 serial number.
fn write_serial(enc: &mut asn1::Encoder, serial: u64) {
    let mut bytes = serial.to_be_bytes().to_vec();
    // Strip leading zeros (but keep at least one byte)
    while bytes.len() > 1 && bytes[0] == 0 {
        bytes.remove(0);
    }
    // Ensure positive: prepend 0x00 if high bit is set
    if bytes[0] & 0x80 != 0 {
        bytes.insert(0, 0x00);
    }
    let mut raw = vec![0x02u8]; // INTEGER tag
    let len = bytes.len();
    if len < 0x80 {
        raw.push(len as u8);
    } else {
        raw.push(0x81);
        raw.push(len as u8);
    }
    raw.extend_from_slice(&bytes);
    enc.write_raw(&raw);
}

/// Write a UTCTime (years ≤ 2049) or GeneralizedTime (years ≥ 2050) into the encoder.
fn write_x509_time(enc: &mut asn1::Encoder, st: SystemTime) -> Result<()> {
    if let Ok(utc) = x509_cert::der::asn1::UtcTime::from_system_time(st) {
        let mut v = Vec::new();
        x509_cert::der::EncodeValue::encode_value(&utc, &mut v)?;
        enc.write_string_with_tag(0x17, std::str::from_utf8(&v)?)?;
    } else {
        let gt = x509_cert::der::asn1::GeneralizedTime::from_system_time(st)?;
        let mut v = Vec::new();
        x509_cert::der::EncodeValue::encode_value(&gt, &mut v)?;
        enc.write_string_with_tag(0x18, std::str::from_utf8(&v)?)?;
    }
    Ok(())
}

/// Build a complete DER-encoded Name (SEQUENCE of RDNs).
fn build_dn(cn: &str, vendor_id: u16, product_id: Option<u16>) -> Result<Vec<u8>> {
    let mut enc = asn1::Encoder::new();
    enc.start_seq(0x30)?; // Name SEQUENCE

    // CN RDN
    enc.start_seq(0x31)?; // SET
    enc.start_seq(0x30)?; // AttributeTypeAndValue
    enc.write_oid(OID_CN)?;
    enc.write_string(cn)?;
    enc.end_seq();
    enc.end_seq();

    // VendorID RDN
    enc.start_seq(0x31)?;
    enc.start_seq(0x30)?;
    enc.write_oid(OID_MATTER_VENDOR_ID)?;
    enc.write_string(&format!("{:04X}", vendor_id))?;
    enc.end_seq();
    enc.end_seq();

    // ProductID RDN (leaf certs only)
    if let Some(pid) = product_id {
        enc.start_seq(0x31)?;
        enc.start_seq(0x30)?;
        enc.write_oid(OID_MATTER_PRODUCT_ID)?;
        enc.write_string(&format!("{:04X}", pid))?;
        enc.end_seq();
        enc.end_seq();
    }

    enc.end_seq(); // Name SEQUENCE
    Ok(enc.encode())
}

/// Encode a single X.509v3 extension into the encoder.
fn add_ext(enc: &mut asn1::Encoder, oid: &str, critical: bool, value: &[u8]) -> Result<()> {
    enc.start_seq(0x30)?;
    enc.write_oid(oid)?;
    if critical {
        enc.write_bool(true)?;
    }
    enc.write_octet_string(value)?;
    enc.end_seq();
    Ok(())
}

/// Build a complete TBSCertificate DER SEQUENCE.
#[allow(clippy::too_many_arguments)]
fn encode_tbs(
    subject_pubkey: &[u8],
    subject_dn: &[u8],
    issuer_dn: &[u8],
    ca_pubkey: &[u8],
    serial: u64,
    not_before: SystemTime,
    not_after: SystemTime,
    ca_pathlen: Option<u8>,
) -> Result<Vec<u8>> {
    let mut enc = asn1::Encoder::new();
    enc.start_seq(0x30)?; // TBSCertificate

    // Version v3
    enc.start_seq(0xa0)?;
    enc.write_int(2)?;
    enc.end_seq();

    // Serial number
    write_serial(&mut enc, serial);

    // Signature algorithm
    enc.start_seq(0x30)?;
    enc.write_oid(OID_SIG_ECDSA_WITH_SHA256)?;
    enc.end_seq();

    // Issuer DN (pre-encoded)
    enc.write_raw(issuer_dn);

    // Validity
    enc.start_seq(0x30)?;
    write_x509_time(&mut enc, not_before)?;
    write_x509_time(&mut enc, not_after)?;
    enc.end_seq();

    // Subject DN (pre-encoded)
    enc.write_raw(subject_dn);

    // SubjectPublicKeyInfo
    enc.start_seq(0x30)?;
    enc.start_seq(0x30)?;
    enc.write_oid(OID_EC_PUBLIC_KEY)?;
    enc.write_oid(OID_P256)?;
    enc.end_seq();
    let mut pk_bs = vec![0x00u8]; // unused bits prefix for BIT STRING
    pk_bs.extend_from_slice(subject_pubkey);
    enc.write_octet_string_with_tag(0x03, &pk_bs)?;
    enc.end_seq();

    // Build SKID and AKID values
    let skid_val = {
        let mut e = asn1::Encoder::new();
        e.write_octet_string(&sha1_enc(subject_pubkey))?;
        e.encode()
    };
    let akid_val = {
        let mut e = asn1::Encoder::new();
        e.start_seq(0x30)?;
        e.write_octet_string_with_tag(0x80, &sha1_enc(ca_pubkey))?;
        e.encode()
    };

    // Extensions [3] EXPLICIT
    enc.start_seq(0xa3)?;
    enc.start_seq(0x30)?;

    if let Some(pathlen) = ca_pathlen {
        // BasicConstraints: CA:TRUE, pathlen:N
        let bc = [0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01, pathlen];
        add_ext(&mut enc, OID_BASIC_CONSTRAINTS, true, &bc)?;
        // KeyUsage: Certificate Sign + CRL Sign
        add_ext(&mut enc, OID_KEY_USAGE, true, &[0x03, 0x02, 0x01, 0x06])?;
    } else {
        // BasicConstraints: CA:FALSE (empty SEQUENCE)
        add_ext(&mut enc, OID_BASIC_CONSTRAINTS, true, &[0x30, 0x00])?;
        // KeyUsage: Digital Signature
        add_ext(&mut enc, OID_KEY_USAGE, true, &[0x03, 0x02, 0x07, 0x80])?;
    }

    // SubjectKeyIdentifier
    add_ext(&mut enc, OID_SKID, false, &skid_val)?;
    // AuthorityKeyIdentifier
    add_ext(&mut enc, OID_AKID, false, &akid_val)?;

    enc.end_seq(); // extensions SEQUENCE
    enc.end_seq(); // [3] EXPLICIT

    enc.end_seq(); // TBSCertificate
    Ok(enc.encode())
}

/// Sign TBS bytes and assemble the complete DER Certificate.
fn encode_cert(tbs: &[u8], ca_private: &p256::SecretKey) -> Result<Vec<u8>> {
    let signing_key = ecdsa::SigningKey::from(ca_private);
    let (sig, _) = signing_key.sign_recoverable(tbs)?;
    let sig_der = sig.to_der();

    let mut enc = asn1::Encoder::new();
    enc.start_seq(0x30)?; // Certificate
    enc.write_raw(tbs);
    enc.start_seq(0x30)?;
    enc.write_oid(OID_SIG_ECDSA_WITH_SHA256)?;
    enc.end_seq();
    let mut sig_bs = vec![0x00u8]; // unused bits prefix
    sig_bs.extend_from_slice(sig_der.as_bytes());
    enc.write_octet_string_with_tag(0x03, &sig_bs)?;
    enc.end_seq(); // Certificate
    Ok(enc.encode())
}

fn create_ca(
    cn: &str,
    vendor_id: u16,
    out_cert: &str,
    out_key: &str,
    validity_years: u32,
) -> Result<()> {
    let key = p256::SecretKey::random(&mut rand::thread_rng());
    let pubkey = key.public_key().to_sec1_bytes().to_vec();

    let serial: u64 = rand::random();
    let now = SystemTime::now();
    let not_after = now + Duration::from_secs(validity_years as u64 * 365 * 24 * 3600);

    let dn = build_dn(cn, vendor_id, None)?;
    let tbs = encode_tbs(&pubkey, &dn, &dn, &pubkey, serial, now, not_after, Some(1))?;
    let cert_der = encode_cert(&tbs, &key)?;

    write_pem("CERTIFICATE", &cert_der, out_cert)?;
    let key_der = secret_key_to_rfc5915(&key)?;
    write_pem("EC PRIVATE KEY", &key_der, out_key)?;

    println!("Created CA cert: {out_cert}");
    println!("Created CA key:  {out_key}");
    Ok(())
}

fn create_pai(
    cn: &str,
    vendor_id: u16,
    ca_cert: &str,
    ca_key: &str,
    out_cert: &str,
    out_key: &str,
    validity_years: u32,
) -> Result<()> {
    let key = p256::SecretKey::random(&mut rand::thread_rng());
    let pubkey = key.public_key().to_sec1_bytes().to_vec();

    let ca_private = read_private_key_from_pem(ca_key)?;
    let ca_pubkey = ca_private.public_key().to_sec1_bytes().to_vec();

    let ca_cert_der = read_data_from_pem(ca_cert)?;
    let ca_x509 = x509_cert::Certificate::from_der(&ca_cert_der)?;
    let issuer_dn_bytes = ca_x509.tbs_certificate.subject.to_der()?;

    let serial: u64 = rand::random();
    let now = SystemTime::now();
    let not_after = now + Duration::from_secs(validity_years as u64 * 365 * 24 * 3600);

    let subject_dn = build_dn(cn, vendor_id, None)?;
    let tbs = encode_tbs(
        &pubkey,
        &subject_dn,
        &issuer_dn_bytes,
        &ca_pubkey,
        serial,
        now,
        not_after,
        Some(0),
    )?;
    let cert_der = encode_cert(&tbs, &ca_private)?;

    write_pem("CERTIFICATE", &cert_der, out_cert)?;
    let key_der = secret_key_to_rfc5915(&key)?;
    write_pem("EC PRIVATE KEY", &key_der, out_key)?;

    println!("Created PAI cert: {out_cert}");
    println!("Created PAI key:  {out_key}");
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn create_dac(
    cn: &str,
    vendor_id: u16,
    product_id: u16,
    ca_cert: &str,
    ca_key: &str,
    out_cert: &str,
    out_key: &str,
    validity_years: u32,
) -> Result<()> {
    let key = p256::SecretKey::random(&mut rand::thread_rng());
    let pubkey = key.public_key().to_sec1_bytes().to_vec();

    let ca_private = read_private_key_from_pem(ca_key)?;
    let ca_pubkey = ca_private.public_key().to_sec1_bytes().to_vec();

    // Extract issuer DN bytes from the CA certificate
    let ca_cert_der = read_data_from_pem(ca_cert)?;
    let ca_x509 = x509_cert::Certificate::from_der(&ca_cert_der)?;
    let issuer_dn_bytes = ca_x509.tbs_certificate.subject.to_der()?;

    let serial: u64 = rand::random();
    let now = SystemTime::now();
    let not_after = now + Duration::from_secs(validity_years as u64 * 365 * 24 * 3600);

    let subject_dn = build_dn(cn, vendor_id, Some(product_id))?;
    let tbs = encode_tbs(
        &pubkey,
        &subject_dn,
        &issuer_dn_bytes,
        &ca_pubkey,
        serial,
        now,
        not_after,
        None,
    )?;
    let cert_der = encode_cert(&tbs, &ca_private)?;

    write_pem("CERTIFICATE", &cert_der, out_cert)?;
    let key_der = secret_key_to_rfc5915(&key)?;
    write_pem("EC PRIVATE KEY", &key_der, out_key)?;

    println!("Created DAC cert: {out_cert}");
    println!("Created DAC key:  {out_key}");
    Ok(())
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    match cli.command {
        Commands::CreateCa {
            cn,
            vendor_id,
            out_cert,
            out_key,
            validity_years,
        } => {
            create_ca(&cn, vendor_id, &out_cert, &out_key, validity_years)?;
        }
        Commands::CreatePai {
            cn,
            vendor_id,
            ca_cert,
            ca_key,
            out_cert,
            out_key,
            validity_years,
        } => {
            create_pai(&cn, vendor_id, &ca_cert, &ca_key, &out_cert, &out_key, validity_years)?;
        }
        Commands::CreateDac {
            cn,
            vendor_id,
            product_id,
            ca_cert,
            ca_key,
            out_cert,
            out_key,
            validity_years,
        } => {
            create_dac(
                &cn,
                vendor_id,
                product_id,
                &ca_cert,
                &ca_key,
                &out_cert,
                &out_key,
                validity_years,
            )?;
        }
    }
    Ok(())
}