@mark1russell7/harness 0.16.3 → 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,9 +13,10 @@
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
@@ -139,11 +140,25 @@ struct Options {
139
140
  via: Option<String>,
140
141
  }
141
142
 
142
- /// The match of the handshake in a reset: nothing, or ` ! --syn` when the SYN passes.
143
- 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>> {
144
159
  Ok(match handshake {
145
- None => "",
146
- Some("pass") => " ! --syn",
160
+ None => String::new(),
161
+ Some("pass") => format!(" ! --syn -m u32 --u32 {DATA}"),
147
162
  Some(other) => return Err(format!("unknown handshake {other}: say pass").into()),
148
163
  })
149
164
  }
@@ -217,8 +232,8 @@ fn rules(action: &str, peer: Ipv4Addr, opts: &Options) -> Result<String, Box<dyn
217
232
  format!("{op} {to}{p} -j DROP\n"),
218
233
  )?
219
234
  }
220
- // with the handshake that passes, a SYN goes through and the reset answers the segment
221
- // 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
222
237
  "rst" | "clear-rst" => {
223
238
  let op = op("rst");
224
239
  let syn = handshake_match(opts.handshake.as_deref())?;
@@ -798,7 +813,7 @@ mod tests {
798
813
  }
799
814
 
800
815
  #[test]
801
- fn a_reset_after_the_handshake_lets_each_syn_pass() {
816
+ fn a_reset_after_the_handshake_lets_each_syn_and_each_segment_with_no_data_pass() {
802
817
  let peer: Ipv4Addr = "10.0.0.2".parse().unwrap();
803
818
  let pass = Options { handshake: Some("pass".into()), ..Options::default() };
804
819
  // without the option, the rule is the one from before: the SYN gets the reset too
@@ -806,15 +821,17 @@ mod tests {
806
821
  rules("rst", peer, &Options::default()).unwrap(),
807
822
  "-I INPUT -s 10.0.0.2/32 -p tcp -j REJECT --reject-with tcp-reset\n"
808
823
  );
824
+ // one token for iptables-restore: the test has no space
825
+ assert!(!DATA.contains(' '));
809
826
  assert_eq!(
810
827
  rules("rst", peer, &pass).unwrap(),
811
- "-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")
812
829
  );
813
830
  assert_eq!(rules("clear-rst", peer, &pass).unwrap(), rules("rst", peer, &pass).unwrap().replace("-I ", "-D "));
814
831
  let via = Options { handshake: Some("pass".into()), via: Some("eth0".into()), ..Options::default() };
815
832
  assert_eq!(
816
833
  rules("rst", peer, &via).unwrap(),
817
- "-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")
818
835
  );
819
836
  // the one value is pass, and only a reset takes it
820
837
  assert!(options(&["--handshake".into(), "drop".into()]).is_err());
@@ -825,6 +842,93 @@ mod tests {
825
842
  }
826
843
  }
827
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
+
828
932
  #[test]
829
933
  fn a_fin_takes_one_step_of_the_mark_and_only_the_first_ack_drops() {
830
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.3",
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",