rusticata / asn1-rs

Parsers/Encoders for ASN.1 BER/DER data
Apache License 2.0
9 stars 14 forks source link

Consume embedded SEQUENCE in a clean way #33

Open Arenash13 opened 5 months ago

Arenash13 commented 5 months ago

I have a BER schema which looks like the following :

SEQUENCE {
    typeA SEQUENCE {...}
    typeB SEQUENCE {...}
}

I try to retrieve fields that are located in typeA SEQUENCE, how can I inspect it in a way to deal with errors, i.e. is it possible to do something like the following :

let (rem, result) = Sequence::from_ber_and_then(input, |i| {
     let (rem2, a) = Sequence::from_ber_and_then(input, |j| {
          let (rem2, a) = u32::from_der(input)?;
          ....
         Ok(...)
})?;

Is it the right to do that ? I'm not able to find the correct code to write in order to run that.

Thanks in advance

chifflier commented 5 months ago

You have multiple options

If you know the definition of your types, the recommended solution is to create a struct for each sequence and derive parsers to be able to call from_der. See for example this unit test:

Resulting code would look like:

#[derive(Debug, PartialEq, DerSequence)]
pub struct MyType {
    a: TypeA,
    b: TypeB,
}

#[derive(Debug, PartialEq, DerSequence)]
pub struct TypeA {
    field1: u32,
    ...
}

let (rem, obj) = MyType::from_der(input)?;

If you can't derive or prefer to use manual parsers, the solution you describe will work, but it will not be idiomatic. You have multiple solutions (again, deriving is preferred):

Arenash13 commented 5 months ago

Thanks for your answer !

I will check for the idiomatic way if my use case grows. For now, I only need to retrieve a few fields in the BER data