Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_shield/tests/packet_bounds.rs

10.8 KiB, 5 runs

created by r656224696:77724, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A packet is read from untrusted bytes, and every length in it is the sender's word.
2//! Each test below gives a length that points past the end of the packet, or near the
3//! top of `usize`, at one field the reader takes, and wants an error, never a panic: a
4//! panic in the receive loop stops the server for every peer.
5
6mod common;
7
8use common::*;
9
10use oxedyne_fe2o3_shield::srv::{
11 cfg::ServerConfig,
12 constant,
13 msg::{
14 app::{
15 Answer,
16 AppMsgKind,
17 },
18 packet::{
19 PacketMeta,
20 PacketValidationArtefactRelativeIndices,
21 PacketValidator,
22 },
23 syntax as srv_syntax,
24 },
25 pow::PowPristine,
26};
27
28use oxedyne_fe2o3_core::{
29 prelude::*,
30 byte::FromBytes,
31 rand::RanDef,
32};
33use oxedyne_fe2o3_crypto::sign::SignatureScheme;
34use oxedyne_fe2o3_hash::{
35 hash::HashScheme,
36 pow::{
37 PowVars,
38 ProofOfWork,
39 },
40};
41use oxedyne_fe2o3_net::id;
42
43use std::{
44 net::{
45 IpAddr,
46 Ipv4Addr,
47 },
48 panic::{
49 catch_unwind,
50 AssertUnwindSafe,
51 },
52};
53
54type Pris = PowPristine<CODE_LEN, { constant::POW_PREFIX_LEN }, { constant::POW_PREIMAGE_LEN }>;
55type Validator = PacketValidator<HashScheme, SignatureScheme>;
56type Meta = PacketMeta<{ id::MID_LEN }, { id::UID_LEN }, id::Mid, id::Uid>;
57
58/// Runs `f`, turning a panic into a test error naming the case.
59fn unpanicked<T>(case: &str, f: impl FnOnce() -> Outcome<T>) -> Outcome<Outcome<T>> {
60 match catch_unwind(AssertUnwindSafe(f)) {
61 Ok(outcome) => Ok(outcome),
62 Err(_) => Err(err!("Case '{}' panicked.", case; Test, Panic)),
63 }
64}
65
66fn powvars() -> Outcome<PowVars<{ constant::POW_PREFIX_LEN }, { constant::POW_PREIMAGE_LEN }, Pris>> {
67 let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
68 Ok(PowVars {
69 zbits: 0,
70 pristine: res!(Pris::new_rx([0u8; CODE_LEN], ip, ip, constant::POW_TIME_HORIZON_SEC)),
71 })
72}
73
74fn validator(pow: bool, sig: bool) -> Outcome<Validator> {
75 let pow = match pow {
76 true => match ServerConfig::default_packet_pow_hash_scheme() {
77 Some(h) => Some(res!(ProofOfWork::new(h))),
78 None => return Err(err!("No default proof of work hasher."; Test, Missing)),
79 },
80 false => None,
81 };
82 Ok(PacketValidator {
83 pow,
84 sig: if sig { Some(SignatureScheme::new_ed25519()) } else { None },
85 })
86}
87
88#[test]
89fn test_artefact_lengths_past_the_end_are_refused_at_each_field() -> Outcome<()> {
90 // (case, validation artefact bytes, must it be refused?)
91 let cases: Vec<(&str, Vec<u8>, bool)> = vec![
92 ("nothing at all", vec![], false),
93 ("pow id without its length", vec![1], true),
94 ("pow length past the end", vec![1, 0xff, 0xff, 0, 0], true),
95 ("bare signature past the end", vec![2, 0xff, 0xff, 1], true),
96 ("keyed artefact past the end", vec![3, 0, 9, 0, 1, 7, 0, 1, 7], true),
97 ("key length past the end", vec![3, 0, 6, 0xff, 0xff, 7, 0, 1, 7], true),
98 ("key past its artefact", vec![3, 0, 2, 0, 1, 7, 0, 1, 7], true),
99 ("signature length past end", vec![3, 0, 6, 0, 1, 7, 0xff, 0xff, 7], true),
100 ("signature id after the pow", vec![1, 0, 2, 9, 9, 3, 0xff], true),
101 ];
102 for (case, byts, refused) in cases {
103 let result = res!(unpanicked(case, || {
104 PacketValidationArtefactRelativeIndices::from_bytes(&byts)
105 }));
106 if refused && result.is_ok() {
107 return Err(err!("Case '{}' was accepted.", case; Test, Unexpected));
108 }
109 }
110
111 // A proof of work followed by nothing is a packet without a signature, not a fault.
112 let (ind, n) = res!(res!(unpanicked("pow alone", || {
113 PacketValidationArtefactRelativeIndices::from_bytes(&[1, 0, 2, 9, 9])
114 })));
115 assert_eq!(ind.pow, Some(3..5));
116 assert!(ind.sig.is_none());
117 assert_eq!(n, 5);
118 Ok(())
119}
120
121#[test]
122fn test_validate_refuses_ranges_outside_the_packet() -> Outcome<()> {
123 let buf = [0u8; 64];
124 let app = AppMsgKind::Request.typ();
125 // (case, start of artefacts, signature ranges)
126 let cases: Vec<(&str, usize, (std::ops::Range<usize>, Option<(std::ops::Range<usize>, std::ops::Range<usize>)>))> = vec![
127 ("signature past the end", 0, (60..70, None)),
128 ("signature range of usize", 0, (0..usize::MAX, None)),
129 ("signature at usize top", 0, (usize::MAX - 2..usize::MAX, None)),
130 ("artefacts start at the top", usize::MAX, (0..4, None)),
131 ("key past the end", 0, (0..40, Some((60..92, 92..100)))),
132 ("keyed signature past end", 0, (0..40, Some((0..32, 60..124)))),
133 ("keyed start at the top", usize::MAX - 1, (0..40, Some((0..32, 32..40)))),
134 ];
135 for (case, n0, sig) in cases {
136 let ind = PacketValidationArtefactRelativeIndices { pow: None, sig: Some(sig) };
137 let v = res!(validator(false, true));
138 let result = res!(unpanicked(case, || {
139 v.validate::<{ constant::POW_PREFIX_LEN }, { constant::POW_PREIMAGE_LEN }, Pris>(
140 &buf, n0, ind, None, app,
141 ).map(|r| r.is_valid().map(|(ok, _)| ok))
142 }));
143 if result.is_ok() {
144 return Err(err!("Case '{}' was accepted.", case; Test, Unexpected));
145 }
146 }
147
148 // And the proof of work range likewise.
149 for (case, n0, rng) in [
150 ("pow past the end", 0, 60..90),
151 ("pow at the usize top", usize::MAX, 0..24),
152 ] {
153 let ind = PacketValidationArtefactRelativeIndices { pow: Some(rng), sig: None };
154 let v = res!(validator(true, false));
155 let pv = res!(powvars());
156 let result = res!(unpanicked(case, || {
157 v.validate(&buf, n0, ind, Some(pv), app).map(|r| r.is_valid().map(|(ok, _)| ok))
158 }));
159 if result.is_ok() {
160 return Err(err!("Case '{}' was accepted.", case; Test, Unexpected));
161 }
162 }
163 Ok(())
164}
165
166#[test]
167fn test_pow_trace_of_a_short_artefact_is_refused() -> Outcome<()> {
168 let v = res!(validator(true, false));
169 let pv = res!(powvars());
170 for len in [0usize, 9, 15] {
171 let artefact = vec![0u8; len];
172 let result = res!(unpanicked(&fmt!("trace of {} bytes", len), || {
173 v.trace(Some(&pv), &artefact)
174 }));
175 if result.is_ok() {
176 return Err(err!("A {}-byte proof of work artefact was traced.", len; Test, Unexpected));
177 }
178 }
179 Ok(())
180}
181
182/// Where the validation artefacts of a real packet start.
183fn artefacts_at(packet: &[u8]) -> Outcome<usize> {
184 let (meta, n1) = res!(Meta::from_bytes(packet));
185 Ok(n1 + meta.chnk.chunk_size as usize)
186}
187
188/// A packet whose lengths lie is dropped, and the server goes on to serve the next.
189#[tokio::test]
190async fn test_bad_packet_then_good_packet_is_served() -> Outcome<()> {
191 log_set_level!("warn");
192 let addr = res!(serve(reverse).await);
193 let noise = res!(tokio::net::UdpSocket::bind("127.0.0.1:0").await, IO, Network);
194 let noise_addr = res!(noise.local_addr(), IO, Network);
195 let forger = res!(protocol(&loopback_config(), 9));
196 let syntax = res!(srv_syntax::base_msg());
197 let build = || forger.build_app(
198 syntax.clone(),
199 AppMsgKind::Request,
200 <id::Mid as RanDef>::randef(),
201 payload(64, 21),
202 noise_addr.ip(),
203 addr.ip(),
204 );
205
206 // Each lie written over a real packet: (case, offset from the artefacts, bytes).
207 let pow_len = 1 + 2 + constant::POW_TIMESTAMP_LEN + constant::POW_NONCE_LEN + 8;
208 let lies: Vec<(&str, usize, Vec<u8>)> = vec![
209 ("pow length past the end", 1, vec![0xff, 0xff]),
210 ("pow artefact too short", 1, vec![0, 9]),
211 ("key length past the end", pow_len + 3, vec![0xff, 0xff]),
212 ];
213 for (case, off, lie) in &lies {
214 let mut packet = res!(build());
215 assert_eq!(packet.len(), 1, "a 64-byte payload should fit in one packet");
216 let mut packet = packet.remove(0);
217 let at = res!(artefacts_at(&packet)) + off;
218 assert!(at + lie.len() <= packet.len(), "case '{}' writes past the packet", case);
219 packet[at..at + lie.len()].copy_from_slice(lie);
220 res!(noise.send_to(&packet, addr).await, IO, Network);
221 }
222
223 let honest = res!(build());
224 res!(noise.send_to(&honest[0], addr).await, IO, Network);
225 let mut heard = [0u8; constant::UDP_BUFFER_SIZE];
226 match tokio::time::timeout(PATIENCE, noise.recv_from(&mut heard)).await {
227 Ok(Ok(_)) => Ok(()),
228 _ => Err(err!(
229 "An honest packet sent after {} lying ones was not answered.", lies.len();
230 Test, Unexpected)),
231 }
232}
233
234/// `server_accept_unknown_users` false: a peer the server has never met is not served.
235#[tokio::test]
236async fn test_unknown_user_refused_when_config_says_no() -> Outcome<()> {
237 log_set_level!("warn");
238 let mut cfg = loopback_config();
239 cfg.server_accept_unknown_users = false;
240 let addr = res!(serve_with(cfg, reverse).await);
241 let (client, _) = res!(dial(10).await);
242 match client.ask(addr, payload(32, 5), QUIET).await {
243 Ok(_) => Err(err!(
244 "A server configured to refuse unknown users answered one."; Test, Unexpected)),
245 Err(_) => Ok(()),
246 }
247}
248
249/// `server_accept_unknown_users` true: the same peer is served.
250#[tokio::test]
251async fn test_unknown_user_served_when_config_says_yes() -> Outcome<()> {
252 log_set_level!("warn");
253 let addr = res!(serve_with(loopback_config(), reverse).await);
254 let (client, _) = res!(dial(11).await);
255 let sent = payload(32, 5);
256 let heard = res!(client.ask(addr, sent.clone(), PATIENCE).await);
257 let mut want = sent;
258 want.reverse();
259 assert_eq!(heard, want);
260 Ok(())
261}
262
263/// A panic while serving one packet, here the handler's, is caught by the receive loop,
264/// which goes on to serve the next.
265#[tokio::test]
266async fn test_panic_in_one_packet_does_not_stop_the_server() -> Outcome<()> {
267 log_set_level!("error");
268 async fn fragile(payload: Vec<u8>, src: std::net::SocketAddr) -> Outcome<Answer> {
269 if payload.first() == Some(&0xee) {
270 panic!("a handler fault");
271 }
272 reverse(payload, src).await
273 }
274 let addr = res!(serve(fragile).await);
275 let (client, _) = res!(dial(12).await);
276 let mut doomed = payload(32, 1);
277 doomed[0] = 0xee;
278 if client.ask(addr, doomed, QUIET).await.is_ok() {
279 return Err(err!("The panicking request was answered."; Test, Unexpected));
280 }
281 let sent = payload(32, 2);
282 let heard = res!(client.ask(addr, sent.clone(), PATIENCE).await);
283 let mut want = sent;
284 want.reverse();
285 assert_eq!(heard, want, "the server stopped answering after a panic");
286 Ok(())
287}