rtci-stun 0.5.0

STUN messages, attributes and a sans-I/O client (RFC 8489), for WebRTC
Documentation
//! The checks the STUN fuzz targets run, one function per target of the same name.
//!
//! They live in the crate so that two callers share them: the cargo-fuzz targets in `fuzz/`
//! (built with `--cfg fuzzing`) and the replay test (`fuzz_regressions_test`), which runs every
//! committed input in `fuzz/regressions/<target>/` through the same function in the ordinary
//! test job. Each function panics when its oracle is violated. Not part of the supported API.
#![allow(missing_docs)]

use crate::addr::{AlternateServer, MappedAddress, OtherAddress, ResponseOrigin};
use crate::alternate::TryAlternate;
use crate::attributes::{
    ATTR_ALTERNATE_DOMAIN, ATTR_ALTERNATE_SERVER, ATTR_NONCE, ATTR_OTHER_ADDRESS, ATTR_REALM,
    ATTR_RESPONSE_ORIGIN, ATTR_SOFTWARE, ATTR_USERNAME, ATTR_XOR_PEER_ADDRESS,
    ATTR_XOR_RELAYED_ADDRESS, STUN_ATTRIBUTES,
};
use crate::error_code::ErrorCodeAttribute;
use crate::fingerprint::FingerprintAttr;
use crate::integrity::{MessageIntegrity, MessageIntegritySha256};
use crate::long_term::LongTermCredentials;
use crate::message::{Getter, MESSAGE_HEADER_SIZE, Message};
use crate::nonce_cookie::SecurityFeatures;
use crate::password_algorithm::{PasswordAlgorithm, PasswordAlgorithms};
use crate::textattrs::TextAttribute;
use crate::uattrs::UnknownAttributes;
use crate::userhash::Userhash;
use crate::validated::Validator;
use crate::xoraddr::XorMappedAddress;

/// A STUN message parsed into a message that already holds attributes: no panic.
pub fn message_unmarshal_binary(data: &[u8]) {
    let mut m = Message::new();
    m.build(&[
        Box::new(TextAttribute::new(ATTR_SOFTWARE, "software".to_owned())),
        Box::new(XorMappedAddress {
            ip: "213.1.223.5".parse().unwrap(),
            port: 0,
        }),
    ])
    .unwrap();

    let _ = m.unmarshal_binary(data);
}

/// A STUN message (RFC 8489) and every attribute decoder the ICE agent and the TURN client
/// call on what a peer or server sends: MAPPED-ADDRESS and its aliases, XOR-MAPPED-ADDRESS
/// (IPv4 and IPv6 lengths), the text attributes, ERROR-CODE, UNKNOWN-ATTRIBUTES, FINGERPRINT
/// and MESSAGE-INTEGRITY, and what RFC 8489 added: MESSAGE-INTEGRITY-SHA256, USERHASH,
/// PASSWORD-ALGORITHM(S), ALTERNATE-DOMAIN, the nonce cookie, the validator, the long-term
/// challenge and the 300 (Try Alternate) reader. Decoding happens lazily, attribute by
/// attribute, so parsing the message alone never reaches these. Oracle: no panic.
pub fn message_attributes(data: &[u8]) {
    let mut m = Message::new();
    if m.unmarshal_binary(data).is_err() {
        return;
    }

    let _ = XorMappedAddress::default().get_from(&m);
    for t in [ATTR_XOR_PEER_ADDRESS, ATTR_XOR_RELAYED_ADDRESS] {
        let _ = XorMappedAddress::default().get_from_as(&m, t);
    }
    let _ = MappedAddress::default().get_from(&m);
    for t in [
        ATTR_ALTERNATE_SERVER,
        ATTR_RESPONSE_ORIGIN,
        ATTR_OTHER_ADDRESS,
    ] {
        let _ = MappedAddress::default().get_from_as(&m, t);
    }
    let _ = AlternateServer::default().get_from(&m);
    let _ = ResponseOrigin::default().get_from(&m);
    let _ = OtherAddress::default().get_from(&m);
    for t in [
        ATTR_USERNAME,
        ATTR_REALM,
        ATTR_NONCE,
        ATTR_SOFTWARE,
        ATTR_ALTERNATE_DOMAIN,
    ] {
        let _ = TextAttribute::get_from_as(&m, t);
    }
    if let Ok(nonce) = TextAttribute::get_from_as(&m, ATTR_NONCE) {
        let _ = SecurityFeatures::from_nonce(&nonce.text);
    }
    let _ = PasswordAlgorithm::default().get_from(&m);
    let _ = PasswordAlgorithms::default().get_from(&m);
    let _ = Userhash::default().get_from(&m);
    let _ = m.unknown_required_attributes(&STUN_ATTRIBUTES);
    let _ = ErrorCodeAttribute::default().get_from(&m);
    let _ = UnknownAttributes(Vec::new()).get_from(&m);
    let _ = FingerprintAttr.check(&m);

    if let Ok(provider) = crate::crypto::default_provider() {
        // A short-term key, as ICE uses; TURN's long-term key is a key of the same kind.
        let crypto = provider.crypto();
        let _ = MessageIntegrity::check(&mut m, b"password", crypto);
        let _ = MessageIntegritySha256::check_truncated(&m, 16, b"password", crypto);

        // The receive path of a usage: every check, then only the covered attributes.
        let validator = Validator::new()
            .known_attributes(&STUN_ATTRIBUTES)
            .allow_truncated_sha256(16);
        let _ = validator.authenticate(&m, b"password", crypto);
        if let Ok(view) = validator.unauthenticated(&m) {
            let _ = TryAlternate::from_response(&view);
        }
        if let Ok(mut credentials) = LongTermCredentials::new("user", "password") {
            let _ = credentials.challenge(&m, &m, crypto);
            let _ = credentials.check_response(&m, &Validator::new(), crypto);
        }
    }
}

/// Round trip of a STUN message (RFC 8489 sections 5 and 14).
///
/// * The header's length is what was consumed: 20 octets of header plus the length field, and
///   the attributes (each a 4-octet header and its value padded to 4) fill exactly that.
/// * Encoding the parsed message gives bytes that parse to an equal message (type, transaction
///   id, length and every attribute, in order), of the same length as the input; encoding that
///   again gives the same bytes (only attribute padding, which the parser does not keep, may
///   differ from the input).
pub fn message_roundtrip(data: &[u8]) {
    let mut first = Message::new();
    if first.unmarshal_binary(data).is_err() {
        return;
    }
    assert_eq!(
        MESSAGE_HEADER_SIZE + first.length as usize,
        data.len(),
        "the length field accounts for every octet after the header"
    );
    let attributes_len: usize = first
        .attributes
        .0
        .iter()
        .map(|a| 4 + (usize::from(a.length)).div_ceil(4) * 4)
        .sum();
    assert_eq!(
        attributes_len, first.length as usize,
        "the attributes, padded, fill the length the header declares"
    );
    for a in &first.attributes.0 {
        assert_eq!(usize::from(a.length), a.value.len(), "{:?}", a.typ);
    }

    let mut encoded = first.clone();
    encoded.encode();
    assert_eq!(
        encoded.raw.len(),
        data.len(),
        "encoding keeps the message's size"
    );

    let mut second = Message::new();
    second
        .unmarshal_binary(&encoded.raw)
        .expect("an encoded message parses");
    assert_eq!(second, first, "parse(encode(parse(x))) == parse(x)");

    let mut again = second.clone();
    again.encode();
    assert_eq!(again.raw, encoded.raw, "encoding is a fixed point");
}