@mark1russell7/harness 0.16.2 → 0.16.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,18 +13,21 @@
13
13
  //! what comes from the peer, `out` what goes to it: a simplex partition.
14
14
  //! - `rst PEER [--handshake pass]` / `clear-rst PEER […]`: the peer's next segment is answered with
15
15
  //! a reset, so its next send fails at once. A REJECT resets only the sender of the matched
16
- //! segment: the target's process never hears of it. With `--handshake pass` a SYN passes
17
- //! (`! --syn`), so a connect succeeds and the first segment after the SYN gets the reset: the
18
- //! last ACK of the handshake, or the first data.
16
+ //! segment: the process of the target does not see the reset. With `--handshake pass` each
17
+ //! SYN and each segment with no data passes, and the first segment with data gets the reset.
18
+ //! Thus the handshake completes, the target accepts the connection, and the first send of the
19
+ //! peer fails.
19
20
  //! - `reject PEER --code host|net|port|admin [--direction in|out|both] [--protocol …]` /
20
21
  //! `clear-reject PEER --code …`: each segment from the peer is answered with that ICMP
21
22
  //! unreachable. On an established socket Linux keeps it as a soft error (tcp_v4_err) and goes on
22
23
  //! retransmitting. By default it acts on TCP from the peer (`in`). `out` answers each packet that
23
24
  //! goes to the peer, and `--protocol all` each protocol: at a router, as a host that is down
24
25
  //! behind it.
25
- //! - `mtu PEER --above N` / `clear-mtu PEER --above N`: each segment from the peer longer than N
26
- //! bytes drops, as a path MTU black hole does, in the namespace that receives it. It acts on
27
- //! segments only when the sender's TSO and GSO and the receiver's GRO are off (`offload`).
26
+ //! - `mtu PEER --above N [--protocol tcp|udp|icmp|all]` / `clear-mtu PEER --above N […]`: each
27
+ //! packet from the peer longer than N bytes drops, as a path MTU black hole does, in the
28
+ //! namespace that receives it. By default it acts on TCP. `--protocol all` drops each protocol,
29
+ //! as a real black hole does. Thus a path-MTU search with ping also sees it. It acts on segments
30
+ //! only when the sender's TSO and GSO and the receiver's GRO are off (`offload`).
28
31
  //! - `fin-ack PEER` / `clear-fin-ack PEER`: the first ACK of each FIN that this end sends to the
29
32
  //! peer drops. The FIN goes again when its retransmission timer fires, and the ACK of the second
30
33
  //! FIN passes. Thus a connection that this end closes second stays in `LAST_ACK` until its timer
@@ -137,11 +140,25 @@ struct Options {
137
140
  via: Option<String>,
138
141
  }
139
142
 
140
- /// The match of the handshake in a reset: nothing, or ` ! --syn` when the SYN passes.
141
- fn handshake_match(handshake: Option<&str>) -> Result<&'static str, Box<dyn Error>> {
143
+ /// The u32 test of a segment with data: one byte or more after the TCP header. The connection
144
+ /// tracker gives the last ACK of a handshake the state ESTABLISHED, thus a match of the state cannot
145
+ /// tell that ACK from data. A u32 read takes 4 bytes and fails past the end of the packet. Thus the
146
+ /// test reads the 4 bytes that start 3 bytes before the end of the headers.
147
+ ///
148
+ /// - `0>>24&0xF1=0x41`: IPv4, and an IP header of an odd number of words. A header with no options
149
+ /// has 5 words. An IP header of an even number of words does not match: the labs send no options.
150
+ /// - `0>>22&0x38`: the length of the IP header less 4 bytes. The mask clears bit 2, and an odd
151
+ /// number of words always sets that bit.
152
+ /// - `@16>>26&0x3C`: the length of the TCP header, from the word of the data offset (TCP byte 12).
153
+ /// - `@1&0=0`: the read at the end of the headers less 3 bytes. It gets 4 bytes only when data follows.
154
+ const DATA: &str = "0>>24&0xF1=0x41&&0>>22&0x38@16>>26&0x3C@1&0=0";
155
+
156
+ /// The match of the handshake in a reset: nothing, or, when the handshake passes, ` ! --syn` and the
157
+ /// test of data. The last ACK of the handshake has no data, thus it passes too.
158
+ fn handshake_match(handshake: Option<&str>) -> Result<String, Box<dyn Error>> {
142
159
  Ok(match handshake {
143
- None => "",
144
- Some("pass") => " ! --syn",
160
+ None => String::new(),
161
+ Some("pass") => format!(" ! --syn -m u32 --u32 {DATA}"),
145
162
  Some(other) => return Err(format!("unknown handshake {other}: say pass").into()),
146
163
  })
147
164
  }
@@ -196,9 +213,10 @@ fn rules(action: &str, peer: Ipv4Addr, opts: &Options) -> Result<String, Box<dyn
196
213
  None => (format!("INPUT -s {peer}/32"), format!("OUTPUT -d {peer}/32")),
197
214
  Some(dev) => (format!("FORWARD -i {dev} -s {peer}/32"), format!("FORWARD -o {dev} -d {peer}/32")),
198
215
  };
199
- // a protocol limits only a black hole and a reject: the other rules match TCP by their nature
200
- if opts.protocol.is_some() && !matches!(action, "blackhole" | "clear" | "reject" | "clear-reject") {
201
- return Err(format!("--protocol acts on a blackhole or a reject, not on {action}").into());
216
+ // a protocol limits only a black hole, a reject and an MTU drop: the other rules match TCP by
217
+ // their nature
218
+ if opts.protocol.is_some() && !matches!(action, "blackhole" | "clear" | "reject" | "clear-reject" | "mtu" | "clear-mtu") {
219
+ return Err(format!("--protocol acts on a blackhole, a reject or an mtu, not on {action}").into());
202
220
  }
203
221
  if opts.handshake.is_some() && !matches!(action, "rst" | "clear-rst") {
204
222
  return Err(format!("--handshake acts on a rst, not on {action}").into());
@@ -214,8 +232,8 @@ fn rules(action: &str, peer: Ipv4Addr, opts: &Options) -> Result<String, Box<dyn
214
232
  format!("{op} {to}{p} -j DROP\n"),
215
233
  )?
216
234
  }
217
- // with the handshake that passes, a SYN goes through and the reset answers the segment
218
- // after it: the connect succeeds, and the first exchange on it fails
235
+ // with the handshake that passes, the SYN and each segment with no data go through, and the
236
+ // reset answers the first segment with data: the target accepts, and the first send fails
219
237
  "rst" | "clear-rst" => {
220
238
  let op = op("rst");
221
239
  let syn = handshake_match(opts.handshake.as_deref())?;
@@ -239,12 +257,13 @@ fn rules(action: &str, peer: Ipv4Addr, opts: &Options) -> Result<String, Box<dyn
239
257
  format!("{op} {to}{p} -j REJECT --reject-with {with}\n"),
240
258
  )?
241
259
  }
242
- // the long segments drop where they arrive. In the namespace of the sender, an OUTPUT drop
243
- // fails its sends with EPERM, and it does not lose them on the way
260
+ // the long packets drop where they arrive. In the namespace of the sender, an OUTPUT drop
261
+ // fails its sends with EPERM, and it does not lose them on the way. By default, TCP only
244
262
  "mtu" | "clear-mtu" => {
245
263
  let op = op("mtu");
246
264
  let above = opts.above.ok_or("--above N")?;
247
- format!("{op} {from} -p tcp -m length --length {}:65535 -j DROP\n", above + 1)
265
+ let p = protocol_match(opts.protocol.as_deref().unwrap_or("tcp"))?;
266
+ format!("{op} {from}{p} -m length --length {}:65535 -j DROP\n", above + 1)
248
267
  }
249
268
  // the mark of the connection counts the FINs that this end sent: 1 after the first FIN, 2
250
269
  // after the second. A pure ACK from the peer drops at mark 1. Each -I goes to the top of
@@ -760,18 +779,41 @@ mod tests {
760
779
  -D OUTPUT -d 10.0.0.2/32 -p udp -j REJECT --reject-with icmp-host-unreachable\n"
761
780
  );
762
781
  assert!(rules("reject", peer, &with(Some("up"), None)).is_err());
763
- // a protocol is one of four words, and only a black hole or a reject takes it
782
+ // a protocol is one of four words, and only a black hole, a reject or an MTU drop takes it
764
783
  assert!(options(&["--protocol".into(), "sctp".into()]).is_err());
765
784
  assert!(options(&["--protocol".into(), "tcp;x".into()]).is_err());
766
785
  assert_eq!(options(&["--protocol".into(), "all".into()]).unwrap().protocol.as_deref(), Some("all"));
767
786
  let tcp = Options { protocol: Some("tcp".into()), above: Some(1200), ..Options::default() };
768
- for action in ["rst", "clear-rst", "mtu", "fin-ack"] {
787
+ for action in ["rst", "clear-rst", "fin-ack"] {
769
788
  assert!(rules(action, peer, &tcp).is_err(), "{action}");
770
789
  }
790
+ assert!(rules("mtu", peer, &tcp).is_ok());
771
791
  }
772
792
 
773
793
  #[test]
774
- fn a_reset_after_the_handshake_lets_each_syn_pass() {
794
+ fn an_mtu_drop_takes_a_protocol_and_its_lift_deletes_the_same_rule() {
795
+ let peer: Ipv4Addr = "10.0.0.2".parse().unwrap();
796
+ let with = |protocol: Option<&str>| Options { protocol: protocol.map(Into::into), above: Some(1200), ..Options::default() };
797
+ // the default keeps the rule from before the option: TCP only
798
+ assert_eq!(rules("mtu", peer, &with(None)).unwrap(), rules("mtu", peer, &with(Some("tcp"))).unwrap());
799
+ for (protocol, rule) in [
800
+ ("tcp", "-I INPUT -s 10.0.0.2/32 -p tcp -m length --length 1201:65535 -j DROP\n"),
801
+ ("udp", "-I INPUT -s 10.0.0.2/32 -p udp -m length --length 1201:65535 -j DROP\n"),
802
+ ("icmp", "-I INPUT -s 10.0.0.2/32 -p icmp -m length --length 1201:65535 -j DROP\n"),
803
+ ("all", "-I INPUT -s 10.0.0.2/32 -m length --length 1201:65535 -j DROP\n"),
804
+ ] {
805
+ assert_eq!(rules("mtu", peer, &with(Some(protocol))).unwrap(), rule, "{protocol}");
806
+ assert_eq!(rules("clear-mtu", peer, &with(Some(protocol))).unwrap(), rule.replace("-I ", "-D "), "{protocol}");
807
+ }
808
+ let via = Options { protocol: Some("all".into()), above: Some(1200), via: Some("eth0".into()), ..Options::default() };
809
+ assert_eq!(
810
+ rules("mtu", peer, &via).unwrap(),
811
+ "-I FORWARD -i eth0 -s 10.0.0.2/32 -m length --length 1201:65535 -j DROP\n"
812
+ );
813
+ }
814
+
815
+ #[test]
816
+ fn a_reset_after_the_handshake_lets_each_syn_and_each_segment_with_no_data_pass() {
775
817
  let peer: Ipv4Addr = "10.0.0.2".parse().unwrap();
776
818
  let pass = Options { handshake: Some("pass".into()), ..Options::default() };
777
819
  // without the option, the rule is the one from before: the SYN gets the reset too
@@ -779,15 +821,17 @@ mod tests {
779
821
  rules("rst", peer, &Options::default()).unwrap(),
780
822
  "-I INPUT -s 10.0.0.2/32 -p tcp -j REJECT --reject-with tcp-reset\n"
781
823
  );
824
+ // one token for iptables-restore: the test has no space
825
+ assert!(!DATA.contains(' '));
782
826
  assert_eq!(
783
827
  rules("rst", peer, &pass).unwrap(),
784
- "-I INPUT -s 10.0.0.2/32 -p tcp ! --syn -j REJECT --reject-with tcp-reset\n"
828
+ format!("-I INPUT -s 10.0.0.2/32 -p tcp ! --syn -m u32 --u32 {DATA} -j REJECT --reject-with tcp-reset\n")
785
829
  );
786
830
  assert_eq!(rules("clear-rst", peer, &pass).unwrap(), rules("rst", peer, &pass).unwrap().replace("-I ", "-D "));
787
831
  let via = Options { handshake: Some("pass".into()), via: Some("eth0".into()), ..Options::default() };
788
832
  assert_eq!(
789
833
  rules("rst", peer, &via).unwrap(),
790
- "-I FORWARD -i eth0 -s 10.0.0.2/32 -p tcp ! --syn -j REJECT --reject-with tcp-reset\n"
834
+ format!("-I FORWARD -i eth0 -s 10.0.0.2/32 -p tcp ! --syn -m u32 --u32 {DATA} -j REJECT --reject-with tcp-reset\n")
791
835
  );
792
836
  // the one value is pass, and only a reset takes it
793
837
  assert!(options(&["--handshake".into(), "drop".into()]).is_err());
@@ -798,6 +842,93 @@ mod tests {
798
842
  }
799
843
  }
800
844
 
845
+ /// The match of xt_u32 (net/netfilter/xt_u32.c, u32_match_it) on the bytes of one IP packet. A
846
+ /// read of 4 bytes past the end of the packet fails the match, as in the kernel.
847
+ fn u32_matches(expression: &str, packet: &[u8]) -> bool {
848
+ let len = packet.len() as u64;
849
+ let word = |at: u64| u32::from_be_bytes(packet[at as usize..at as usize + 4].try_into().unwrap());
850
+ let number = |text: &str| match text.strip_prefix("0x") {
851
+ Some(hex) => u32::from_str_radix(hex, 16).unwrap(),
852
+ None => text.parse().unwrap(),
853
+ };
854
+ expression.split("&&").all(|test| {
855
+ let (location, values) = test.split_once('=').unwrap();
856
+ // the numbers of the location, each after its operator: the first one has none
857
+ let mut steps: Vec<(&str, u32)> = Vec::new();
858
+ let mut rest = location;
859
+ let mut op = "";
860
+ while !rest.is_empty() {
861
+ let end = rest.find(|c: char| "&@<>".contains(c)).unwrap_or(rest.len());
862
+ steps.push((op, number(&rest[..end])));
863
+ rest = &rest[end..];
864
+ op = ["<<", ">>", "&", "@"].into_iter().find(|each| rest.starts_with(each)).unwrap_or("");
865
+ rest = &rest[op.len()..];
866
+ }
867
+ let first = u64::from(steps[0].1);
868
+ if len < 4 || first > len - 4 {
869
+ return false;
870
+ }
871
+ let mut at = 0u64;
872
+ let mut val = word(first);
873
+ for &(op, n) in &steps[1..] {
874
+ match op {
875
+ "&" => val &= n,
876
+ "<<" => val <<= n,
877
+ ">>" => val >>= n,
878
+ _ => {
879
+ at += u64::from(val);
880
+ if at + 4 > len || u64::from(n) > len - at - 4 {
881
+ return false;
882
+ }
883
+ val = word(at + u64::from(n));
884
+ }
885
+ }
886
+ }
887
+ values.split(',').any(|range| {
888
+ let (low, high) = range.split_once(':').unwrap_or((range, range));
889
+ number(low) <= val && val <= number(high)
890
+ })
891
+ })
892
+ }
893
+
894
+ /// An IPv4 packet of TCP: `ihl` and `doff` are the lengths of its headers in words of 4 bytes,
895
+ /// and `data` bytes follow them.
896
+ fn segment(ihl: usize, doff: usize, data: usize) -> Vec<u8> {
897
+ let len = 4 * ihl + 4 * doff + data;
898
+ let mut bytes = vec![0xA5u8; len];
899
+ bytes[0] = 0x40 | ihl as u8;
900
+ // a TOS with each bit set: its 2 high bits are in the word of the IP length, and the masks drop them
901
+ bytes[1] = 0xFF;
902
+ bytes[2..4].copy_from_slice(&(len as u16).to_be_bytes());
903
+ bytes[9] = 6;
904
+ // the reserved bits and AE after the data offset, each set: the mask drops them
905
+ bytes[4 * ihl + 12] = (doff as u8) << 4 | 0x0F;
906
+ bytes
907
+ }
908
+
909
+ #[test]
910
+ fn the_test_of_data_needs_one_byte_after_the_tcp_header() {
911
+ // the model agrees with the rule of the MTU drop, a test that the kernel also applies
912
+ assert!(u32_matches("0&0xFFFF=1201:65535", &segment(5, 8, 1149)));
913
+ assert!(!u32_matches("0&0xFFFF=1201:65535", &segment(5, 8, 1148)));
914
+ // a header with no options (5 words), with timestamps (8), with each option (15), and an IP
915
+ // header with options (7 and 15 words)
916
+ for (ihl, doff) in [(5, 5), (5, 8), (5, 15), (7, 8), (15, 15)] {
917
+ assert!(!u32_matches(DATA, &segment(ihl, doff, 0)), "{ihl} {doff}, with no data");
918
+ for data in [1, 2, 3, 4, 5, 1448] {
919
+ assert!(u32_matches(DATA, &segment(ihl, doff, data)), "{ihl} {doff}, with {data} bytes");
920
+ }
921
+ }
922
+ // an IP header of an even number of words does not match, with data or with none
923
+ for data in [0, 1, 100] {
924
+ assert!(!u32_matches(DATA, &segment(6, 8, data)), "6 8, with {data} bytes");
925
+ }
926
+ // a packet of IPv6 does not match
927
+ let mut six = segment(5, 8, 10);
928
+ six[0] = 0x65;
929
+ assert!(!u32_matches(DATA, &six));
930
+ }
931
+
801
932
  #[test]
802
933
  fn a_fin_takes_one_step_of_the_mark_and_only_the_first_ack_drops() {
803
934
  let peer: Ipv4Addr = "10.0.0.2".parse().unwrap();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/harness",
4
- "version": "0.16.2",
4
+ "version": "0.16.4",
5
5
  "description": "Network labs in Docker, declared as data. A cell builds a topology of networks, routers and proxies around a stock target. It injects a fault at layer 3 or 4 from a NET_ADMIN sidecar, measures the records of the kernel and judges a prediction. The faults are black holes, resets, ICMP unreachable, one-way and MTU drops, tc netem, the toxics of Toxiproxy and frozen processes. Its replicated groups are Redis with Sentinels, MongoDB replica sets, PostgreSQL standbys, Kafka, RabbitMQ and BGP fabrics with BFD. A lab can also operate in a QEMU guest. Its first use is connection timers: keep-alive, TCP retransmission, heartbeats and reconnects.",
6
6
  "keywords": [
7
7
  "fault-injection",