rusticata / der-parser

BER/DER parser written in pure Rust. Fast, zero-copy, safe.
Apache License 2.0
84 stars 29 forks source link

How do I convert an `asn1_rs::Any` to a `BerObject`? #67

Closed lilyball closed 6 months ago

lilyball commented 1 year ago

NOT A CONTRIBUTION

I'm looking to update my code that uses x509-parser (and transitively der-parser). I have code that takes an x509_parser::x509::AlgorithmIdentifier, reads the parameters field, and pretty-prints it. In x509-parser v0.12, the parameters are a DerObject so that works. In v0.15 it's an Any. The pretty-printing provided by der-parser exists on BerObject.

So, my question, how do I convert an asn1_rs::Any to a BerObject? I would have expected BerObject to implement TryFrom<Any> but it doesn't[^1]. Is there any alternative way I'm missing?

[^1]: I see in the source a comment saying this is because of the lack of a max_depth argument, but I would have expected such an implementation to be recursive, and perhaps a method on BerObject for converting from Any with a maximum depth specified.

chifflier commented 1 year ago

Hi, Thank you for your report. The Any type is expected to be more generic than BerObject, and have more conversion traits etc. However, I see multiple issues here:

In addition to the above comments, I was wondering why you need a BerObject. Is it only for printing?

chifflier commented 1 year ago

Note: since Any contains the header and raw data, the ber_read_element_content_as function can be used. I've used it to implement TryFrom, here's the relevant code:

let (header, data) = (any.header, any.data);
let (_, content) = ber_read_element_content_as(
    data,
    header.tag(),
    header.length(),
    header.constructed(),
    MAX_RECURSION,
)?;
let obj = BerObject::from_header_and_content(header, content);

Of course, this is only useful until TryFrom is merged.

lilyball commented 1 year ago

In addition to the above comments, I was wondering why you need a BerObject. Is it only for printing?

In this particular case, yes. I'm updating code that pretty-printed algorithm parameters and now it can't. I stopped doing the upgrade when I hit this issue so I don't know if I'm going to run into Any anywhere else, but I don't expect to need anything beyond pretty-printing and possibly custom parsing of the contents for custom oids.

lilyball commented 1 year ago

Actually what I said wasn't true, I also have code that tests if the parameters is an Oid, a Sequence, or Null, though I should be able to adapt that to operate on the Any directly.