Yin Lei
Yin Lei

Reputation: 91

How to set APLN protocols before TLS handshake with OpenSSL in Rust?

I want to set the APLN protocols to "h2" and "http/1.1" before the TLS handshake. I am using .set_alpn_protos(). However, my attempt yields an error at runtime:

context.set_alpn_protos(b"\x06h2\x08http/1.1").expect("set ALPN error");
thread 'main' panicked at 'set ALPN error: ErrorStack([])', src/checker/tls/get_tls_info.rs:58:56

I can set them successfully in Python like this:

ssl.set_alpn_protos([b'h2', b'http/1.1'])

What am I doing wrong?

Upvotes: 1

Views: 781

Answers (1)

cafce25
cafce25

Reputation: 27187

From the docs you linked (emphasis mine):

It consists of a sequence of supported protocol names prefixed by their byte length.

replace \x06 with \x02 since b"h2" is 2 bytes not 6

context.set_alpn_protos(b"\x02h2\x08http/1.1").expect("set ALPN error");

You could also use something like the following to calculate the wire format from a list similar to pythons:

let protos: &[&[u8]] = &[b"h21", b"http/1.1"];
let wire = protos.into_iter().flat_map(|proto| {
    let mut proto = proto.to_vec();
    let len: u8 = proto.len().try_into().expect("proto is too long");
    proto.insert(0, len);
    proto
}).collect::<Vec<_>>();

Upvotes: 3

Related Questions