summaryrefslogtreecommitdiff
path: root/crates/tor-cell/tests/test_relaycell.rs
blob: 1d20b6f87d26de7a3e465533a341069747496cdd (plain)
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
// Tests for encoding/decoding relay messages into relay cell bodies.
#![allow(clippy::uninlined_format_args)]

use tor_bytes::Error;
use tor_cell::relaycell::{
    AnyRelayMsgOuter, RelayCellFormat, RelayCmd, RelayMsg, StreamId, UnparsedRelayMsg,
    msg::{self, AnyRelayMsg},
};

use std::convert::Infallible;
#[cfg(feature = "experimental-udp")]
use std::{
    net::{Ipv4Addr, Ipv6Addr},
    str::FromStr,
};
#[cfg(feature = "experimental-udp")]
use tor_cell::relaycell::udp::Address;

const CELL_BODY_LEN: usize = 509;

struct BadRng;
impl rand::TryRng for BadRng {
    type Error = Infallible;

    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
        Ok(0xf0f0f0f0)
    }
    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
        Ok(0xf0f0f0f0f0f0f0f0)
    }
    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {
        dest.fill(0xf0);
        Ok(())
    }
}

// I won't tell if you don't.
impl rand::TryCryptoRng for BadRng {}

fn decode(body: &str) -> Box<[u8; CELL_BODY_LEN]> {
    let mut body = body.to_string();
    body.retain(|c| !c.is_whitespace());
    let mut body = hex::decode(body).unwrap();
    body.resize(CELL_BODY_LEN, 0xf0); // see BadRng

    let mut result = [0; CELL_BODY_LEN];
    result.copy_from_slice(&body[..]);
    Box::new(result)
}

// Run several tests, requiring that that `body`, is the default encdoding of `msg` with `version`.
fn cell(version: RelayCellFormat, body: &str, id: Option<StreamId>, msg: AnyRelayMsg) {
    let body = decode(body);
    let mut bad_rng = BadRng;

    // encode the cell msg so that we can get its length
    let mut encoded_msg = Vec::new();
    msg.clone().encode_onto(&mut encoded_msg).unwrap();

    let expected = AnyRelayMsgOuter::new(id, msg);

    let decoded = AnyRelayMsgOuter::decode_singleton(version, body.clone()).unwrap();

    let unparsed = UnparsedRelayMsg::from_singleton_body(version, body).unwrap();

    // check the accessors for `UnparsedRelayMsg`
    assert_eq!(unparsed.cmd(), decoded.cmd());
    assert_eq!(unparsed.stream_id(), decoded.stream_id());
    if unparsed.cmd() == RelayCmd::DATA {
        assert_eq!(unparsed.data_len().map(usize::from), Ok(encoded_msg.len()));
    } else {
        // if not a DATA cell, then there are no data bytes
        assert_eq!(unparsed.data_len(), Ok(0));
    }

    let decoded_from_partial = unparsed.decode::<AnyRelayMsg>().unwrap();
    assert_eq!(decoded_from_partial.stream_id(), decoded.stream_id());
    assert_eq!(decoded_from_partial.cmd(), decoded.cmd());

    assert_eq!(format!("{:?}", expected), format!("{:?}", decoded));
    assert_eq!(
        format!("{:?}", expected),
        format!("{:?}", decoded_from_partial)
    );

    let encoded1 = decoded.encode(version, &mut bad_rng).unwrap();
    let encoded2 = expected.encode(version, &mut bad_rng).unwrap();

    assert_eq!(&encoded1[..], &encoded2[..]);
}

#[test]
fn bad_rng() {
    use rand::Rng;
    let mut rng = BadRng;

    assert_eq!(rng.next_u32(), 0xf0f0f0f0);
    assert_eq!(rng.next_u64(), 0xf0f0f0f0f0f0f0f0);
    let mut buf = [0u8; 19];
    rng.fill_bytes(&mut buf);
    assert_eq!(
        &buf,
        &[
            0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
            0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
        ]
    );
}

#[test]
fn test_cells_v0() {
    cell(
        RelayCellFormat::V0,
        "02 0000 9999 12345678 000c 6e6565642d746f2d6b6e6f77 00000000",
        StreamId::new(0x9999),
        msg::Data::new(&b"need-to-know"[..]).unwrap().into(),
    );

    // length too big: 0x1f3 is one byte too many.
    let m = decode("02 0000 9999 12345678 01f3 6e6565642d746f2d6b6e6f77 00000000");
    assert_eq!(
        AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V0, m).err(),
        Some(Error::InvalidMessage(
            "Insufficient data in relay cell".into()
        ))
    );

    // check accessors.
    let m = decode("02 0000 9999 12345678 01f2 6e6565642d746f2d6b6e6f77 00000000");
    let c = AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V0, m).unwrap();
    assert_eq!(c.cmd(), RelayCmd::from(2));
    assert_eq!(c.msg().cmd(), RelayCmd::from(2));
    let (s, _) = c.into_streamid_and_msg();
    assert_eq!(s, StreamId::new(0x9999));

    // check accessors on `UnparsedRelayMsg`.
    let m = decode("02 0000 9999 12345678 01f2 6e6565642d746f2d6b6e6f77 00000000");
    let c = UnparsedRelayMsg::from_singleton_body(RelayCellFormat::V0, m).unwrap();
    assert_eq!(c.cmd(), RelayCmd::from(2));
    assert_eq!(c.stream_id(), StreamId::new(0x9999));
    assert_eq!(c.data_len(), Ok(0x01f2));

    // check `data_len()` with a cell that has an invalid length.
    let m = decode("02 0000 9999 12345678 04f2 6e6565642d746f2d6b6e6f77 00000000");
    let c = UnparsedRelayMsg::from_singleton_body(RelayCellFormat::V0, m).unwrap();
    assert!(c.data_len().is_err());
}

#[test]
fn test_valid_cells_v1() {
    // Correct DATA message, with stream ID.
    cell(
        RelayCellFormat::V1,
        "00000000000000000000000000000000 02 000c 3230 6e6565642d746f2d6b6e6f77 00000000",
        StreamId::new(0x3230),
        msg::Data::new(b"need-to-know").unwrap().into(),
    );
    // Correct Extended2 message, without stream ID.
    cell(
        RelayCellFormat::V1,
        "00000000000000000000000000000000 0f 001f 001d
              686f7720646f20796f7520646f20616e64207368616b652068616e6473 00000000",
        None,
        msg::Extended2::new(b"how do you do and shake hands".to_vec()).into(),
    );
    // Correct SENDME message, without stream ID.
    //
    // (Note that a 20-byte tag won't actually be used with the V1 format,
    // but the encoding still allows it.
    cell(
        RelayCellFormat::V1,
        "00000000000000000000000000000000 05 0017 01 0014
              326e64206c656e20697320726564756e64616e74 00000000",
        None,
        msg::Sendme::new_tag(*b"2nd len is redundant").into(),
    );

    // Check accessors on `UnparsedRelayMsg`.
    let m =
        decode("00000000000000000000000000000000 02 000c 3230 6e6565642d746f2d6b6e6f77 00000000");
    let c = UnparsedRelayMsg::from_singleton_body(RelayCellFormat::V1, m).unwrap();
    assert_eq!(c.cmd(), RelayCmd::from(2));
    assert_eq!(c.stream_id(), StreamId::new(0x3230));
    assert_eq!(c.data_len(), Ok(0x000c));

    // Check `data_len()` with a cell that has an invalid length.
    let m =
        decode("00000000000000000000000000000000 02 050c 3230 6e6565642d746f2d6b6e6f77 00000000");
    let c = UnparsedRelayMsg::from_singleton_body(RelayCellFormat::V1, m).unwrap();
    assert!(c.data_len().is_err());
}

#[test]
fn test_invalid_cells_v1() {
    // zero-valued stream ID on data message (which needs a stream.)
    {
        let body = decode("00000000000000000000000000000000 02 0001 0000 ff");
        let err = AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V1, body).unwrap_err();
        assert_eq!(
            err,
            Error::InvalidMessage("Zero-valued stream ID with relay command DATA".into(),),
        );
    }

    // Message too long to fit in cell
    {
        // 489 bytes (0x1e9) is one over the limit.
        let body = decode("00000000000000000000000000000000 02 01e9 3231 00");
        let err = AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V1, body).unwrap_err();
        assert_eq!(
            err,
            Error::InvalidMessage("Insufficient data in relay cell".into())
        );

        // Note that 0x01e8 succeeds.
        let body = decode("00000000000000000000000000000000 02 01e8 3231 00");
        let m = AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V1, body).unwrap();
        assert_eq!(m.cmd(), RelayCmd::DATA)
    }

    // Unrecognized command (not allowed in V1)
    {
        let body = decode("00000000000000000000000000000000 f0 0000 00000000");
        let err = AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V1, body).unwrap_err();
        assert_eq!(
            err,
            Error::InvalidMessage("Unrecognized relay command 240".into())
        );
    }
}

#[test]
fn test_streamid() {
    let zero: Option<StreamId> = StreamId::new(0);
    let two: Option<StreamId> = StreamId::new(2);

    assert!(zero.is_none());
    assert!(two.is_some());

    assert_eq!(format!("{}", two.unwrap()), "2");

    assert_eq!(StreamId::get_or_zero(zero), 0_u16);
    assert_eq!(StreamId::get_or_zero(two), 2_u16);

    assert!(RelayCmd::DATA.accepts_streamid_val(two));
    assert!(!RelayCmd::DATA.accepts_streamid_val(zero));

    assert!(RelayCmd::EXTEND2.accepts_streamid_val(zero));
    assert!(!RelayCmd::EXTEND2.accepts_streamid_val(two));
}

#[cfg(feature = "experimental-udp")]
#[test]
fn test_address() {
    // IPv4
    let ipv4 = Ipv4Addr::from_str("1.2.3.4").expect("Unable to parse IPv4");
    let addr = Address::from_str("1.2.3.4").expect("Unable to parse Address");
    assert!(matches!(addr, Address::Ipv4(_)));
    assert_eq!(addr, Address::Ipv4(ipv4));

    // Wrong IPv4 should result in a hostname.
    let addr = Address::from_str("1.2.3.372").expect("Unable to parse Address");
    assert!(addr.is_hostname());

    // Common bad IPv4 patterns
    let addr = Address::from_str("0x23.42.42.42").expect("Unable to parse Address");
    assert!(addr.is_hostname());
    let addr = Address::from_str("0x7f000001").expect("Unable to parse Address");
    assert!(addr.is_hostname());
    let addr = Address::from_str("10.0.23").expect("Unable to parse Address");
    assert!(addr.is_hostname());
    let addr = Address::from_str("2e3:4::10.0.23").expect("Unable to parse Address");
    assert!(addr.is_hostname());

    // IPv6
    let ipv6 = Ipv6Addr::from_str("4242::9").expect("Unable to parse IPv6");
    let addr = Address::from_str("4242::9").expect("Unable to parse Address");
    assert!(matches!(addr, Address::Ipv6(_)));
    assert_eq!(addr, Address::Ipv6(ipv6));

    // Wrong IPv6 should result in a hostname.
    let addr = Address::from_str("4242::9::5").expect("Unable to parse Address");
    assert!(addr.is_hostname());

    // Hostname
    let hostname = "www.torproject.org";
    let addr = Address::from_str(hostname).expect("Unable to parse Address");
    assert!(addr.is_hostname());
    assert_eq!(addr, Address::Hostname(hostname.to_string().into_bytes()));

    // Empty hostname
    let hostname = "";
    let addr = Address::from_str(hostname).expect("Unable to parse Address");
    assert!(addr.is_hostname());
    assert_eq!(addr, Address::Hostname(hostname.to_string().into_bytes()));

    // Too long hostname.
    let hostname = "a".repeat(256);
    let addr = Address::from_str(hostname.as_str());
    assert!(addr.is_err());
    assert_eq!(
        addr.err(),
        Some(Error::InvalidMessage("Hostname too long".into()))
    );

    // Some Unicode emojis (go Gen-Z!).
    let hostname = "👍️👍️👍️";
    let addr = Address::from_str(hostname).expect("Unable to parse Address");
    assert!(addr.is_hostname());
    assert_eq!(addr, Address::Hostname(hostname.to_string().into_bytes()));

    // Address with nul byte. Not allowed.
    let hostname = "aaa\0aaa";
    let addr = Address::from_str(hostname);
    assert!(addr.is_err());
    assert_eq!(
        addr.err(),
        Some(Error::InvalidMessage("Nul byte not permitted".into()))
    );
}