ipsec: GCM, Anti-replay and ESN fixess

Type: fix

Several Fixes:
 1 - Anti-replay did not work with GCM becuase it overwrote the sequence
number in the ESP header. To fix i added the seq num to the per-packet
data so it is preserved
 2 - The high sequence number was not byte swapped during ESP encrypt.
 3 - openssl engine was the only one to return FAIL_DECRYPT for bad GCM
the others return BAD_HMAC. removed the former
 4 - improved tracing to show the low and high seq numbers
 5 - documented the anti-replay window checks
 6 - fixed scapy patch for ESN support for GCM
 7 - tests for anti-reply (w/ and w/o ESN) for each crypto algo

Change-Id: Id65d96b6d1d4dd821b2ab557e87468fff6d70e5b
Signed-off-by: Neale Ranns <nranns@cisco.com>
diff --git a/src/plugins/crypto_openssl/main.c b/src/plugins/crypto_openssl/main.c
index fd749d0..7362d6b 100644
--- a/src/plugins/crypto_openssl/main.c
+++ b/src/plugins/crypto_openssl/main.c
@@ -169,7 +169,7 @@
       else
 	{
 	  n_fail++;
-	  op->status = VNET_CRYPTO_OP_STATUS_FAIL_DECRYPT;
+	  op->status = VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC;
 	}
     }
   return n_ops - n_fail;
diff --git a/src/plugins/dpdk/ipsec/esp_decrypt.c b/src/plugins/dpdk/ipsec/esp_decrypt.c
index 4982db7..a82f63e 100644
--- a/src/plugins/dpdk/ipsec/esp_decrypt.c
+++ b/src/plugins/dpdk/ipsec/esp_decrypt.c
@@ -235,7 +235,8 @@
 	    }
 
 	  /* anti-replay check */
-	  if (ipsec_sa_anti_replay_check (sa0, &esp0->seq))
+	  if (ipsec_sa_anti_replay_check
+	      (sa0, clib_host_to_net_u32 (esp0->seq)))
 	    {
 	      clib_warning ("failed anti-replay check");
 	      if (is_ip6)
@@ -549,7 +550,8 @@
 
 	  iv_size = cipher_alg->iv_len;
 
-	  ipsec_sa_anti_replay_advance (sa0, esp0->seq);
+	  ipsec_sa_anti_replay_advance (sa0,
+					clib_host_to_net_u32 (esp0->seq));
 
 	  /* if UDP encapsulation is used adjust the address of the IP header */
 	  if (ipsec_sa_is_set_UDP_ENCAP (sa0)
diff --git a/src/vnet/crypto/crypto.h b/src/vnet/crypto/crypto.h
index 9c15d53..9326a07 100644
--- a/src/vnet/crypto/crypto.h
+++ b/src/vnet/crypto/crypto.h
@@ -65,8 +65,7 @@
   _(PENDING, "pending") \
   _(COMPLETED, "completed") \
   _(FAIL_NO_HANDLER, "no-handler") \
-  _(FAIL_BAD_HMAC, "bad-hmac") \
-  _(FAIL_DECRYPT, "decrypt-fail")
+  _(FAIL_BAD_HMAC, "bad-hmac")
 
 typedef enum
 {
diff --git a/src/vnet/ipsec/ah_decrypt.c b/src/vnet/ipsec/ah_decrypt.c
index 741fa91..bc6b5c4 100644
--- a/src/vnet/ipsec/ah_decrypt.c
+++ b/src/vnet/ipsec/ah_decrypt.c
@@ -203,7 +203,7 @@
       pd->seq = clib_host_to_net_u32 (ah0->seq_no);
 
       /* anti-replay check */
-      if (ipsec_sa_anti_replay_check (sa0, &ah0->seq_no))
+      if (ipsec_sa_anti_replay_check (sa0, pd->seq))
 	{
 	  b[0]->error = node->errors[AH_DECRYPT_ERROR_REPLAY];
 	  next[0] = AH_DECRYPT_NEXT_DROP;
@@ -303,7 +303,7 @@
 
       if (PREDICT_TRUE (sa0->integ_alg != IPSEC_INTEG_ALG_NONE))
 	{
-	  ipsec_sa_anti_replay_advance (sa0, clib_host_to_net_u32 (pd->seq));
+	  ipsec_sa_anti_replay_advance (sa0, pd->seq);
 	}
 
       u16 ah_hdr_len = sizeof (ah_header_t) + pd->icv_size
diff --git a/src/vnet/ipsec/esp_decrypt.c b/src/vnet/ipsec/esp_decrypt.c
index 48f08f4..c2b9bf4 100644
--- a/src/vnet/ipsec/esp_decrypt.c
+++ b/src/vnet/ipsec/esp_decrypt.c
@@ -67,6 +67,8 @@
 typedef struct
 {
   u32 seq;
+  u32 sa_seq;
+  u32 sa_seq_hi;
   ipsec_crypto_alg_t crypto_alg;
   ipsec_integ_alg_t integ_alg;
 } esp_decrypt_trace_t;
@@ -79,9 +81,11 @@
   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
   esp_decrypt_trace_t *t = va_arg (*args, esp_decrypt_trace_t *);
 
-  s = format (s, "esp: crypto %U integrity %U seq %u",
-	      format_ipsec_crypto_alg, t->crypto_alg,
-	      format_ipsec_integ_alg, t->integ_alg, t->seq);
+  s =
+    format (s,
+	    "esp: crypto %U integrity %U pkt-seq %d sa-seq %u sa-seq-hi %u",
+	    format_ipsec_crypto_alg, t->crypto_alg, format_ipsec_integ_alg,
+	    t->integ_alg, t->seq, t->sa_seq, t->sa_seq_hi);
   return s;
 }
 
@@ -99,12 +103,13 @@
     u64 sa_data;
   };
 
+  u32 seq;
   i16 current_data;
   i16 current_length;
   u16 hdr_sz;
 } esp_decrypt_packet_data_t;
 
-STATIC_ASSERT_SIZEOF (esp_decrypt_packet_data_t, 2 * sizeof (u64));
+STATIC_ASSERT_SIZEOF (esp_decrypt_packet_data_t, 3 * sizeof (u64));
 
 #define ESP_ENCRYPT_PD_F_FD_TRANSPORT (1 << 2)
 
@@ -177,6 +182,7 @@
       pd->current_length = b[0]->current_length;
       pd->hdr_sz = pd->current_data - vnet_buffer (b[0])->l3_hdr_offset;
       payload = b[0]->data + pd->current_data;
+      pd->seq = clib_host_to_net_u32 (((esp_header_t *) payload)->seq);
 
       /* we need 4 extra bytes for HMAC calculation when ESN are used */
       if (ipsec_sa_is_set_USE_ESN (sa0) && pd->icv_sz &&
@@ -188,7 +194,7 @@
 	}
 
       /* anti-reply check */
-      if (ipsec_sa_anti_replay_check (sa0, &((esp_header_t *) payload)->seq))
+      if (ipsec_sa_anti_replay_check (sa0, pd->seq))
 	{
 	  b[0]->error = node->errors[ESP_DECRYPT_ERROR_REPLAY];
 	  next[0] = ESP_DECRYPT_NEXT_DROP;
@@ -221,10 +227,11 @@
 	  op->len = len;
 	  if (ipsec_sa_is_set_USE_ESN (sa0))
 	    {
-	      /* shift ICV for 4 bytes to insert ESN */
+	      /* shift ICV by 4 bytes to insert ESN */
+	      u32 seq_hi = clib_host_to_net_u32 (sa0->seq_hi);
 	      u8 tmp[ESP_MAX_ICV_SIZE], sz = sizeof (sa0->seq_hi);
 	      clib_memcpy_fast (tmp, payload + len, ESP_MAX_ICV_SIZE);
-	      clib_memcpy_fast (payload + len, &sa0->seq_hi, sz);
+	      clib_memcpy_fast (payload + len, &seq_hi, sz);
 	      clib_memcpy_fast (payload + len + sz, tmp, ESP_MAX_ICV_SIZE);
 	      op->len += sz;
 	      op->digest += sz;
@@ -368,9 +375,8 @@
 	goto trace;
 
       sa0 = vec_elt_at_index (im->sad, pd->sa_index);
-      u8 *payload = b[0]->data + pd->current_data;
 
-      ipsec_sa_anti_replay_advance (sa0, ((esp_header_t *) payload)->seq);
+      ipsec_sa_anti_replay_advance (sa0, pd->seq);
 
       esp_footer_t *f = (esp_footer_t *) (b[0]->data + pd->current_data +
 					  pd->current_length - sizeof (*f) -
@@ -485,13 +491,14 @@
       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
 	{
 	  esp_decrypt_trace_t *tr;
-	  u8 *payload = b[0]->data + pd->current_data;
 	  tr = vlib_add_trace (vm, node, b[0], sizeof (*tr));
 	  sa0 = pool_elt_at_index (im->sad,
 				   vnet_buffer (b[0])->ipsec.sad_index);
 	  tr->crypto_alg = sa0->crypto_alg;
 	  tr->integ_alg = sa0->integ_alg;
-	  tr->seq = clib_host_to_net_u32 (((esp_header_t *) payload)->seq);
+	  tr->seq = pd->seq;
+	  tr->sa_seq = sa0->last_seq;
+	  tr->sa_seq_hi = sa0->seq_hi;
 	}
 
       /* next */
diff --git a/src/vnet/ipsec/esp_encrypt.c b/src/vnet/ipsec/esp_encrypt.c
index 041b268..47c079d 100644
--- a/src/vnet/ipsec/esp_encrypt.c
+++ b/src/vnet/ipsec/esp_encrypt.c
@@ -65,6 +65,7 @@
   u32 sa_index;
   u32 spi;
   u32 seq;
+  u32 sa_seq_hi;
   u8 udp_encap;
   ipsec_crypto_alg_t crypto_alg;
   ipsec_integ_alg_t integ_alg;
@@ -80,8 +81,9 @@
 
   s =
     format (s,
-	    "esp: sa-index %d spi %u (0x%08x) seq %u crypto %U integrity %U%s",
-	    t->sa_index, t->spi, t->spi, t->seq, format_ipsec_crypto_alg,
+	    "esp: sa-index %d spi %u (0x%08x) seq %u sa-seq-hi %u crypto %U integrity %U%s",
+	    t->sa_index, t->spi, t->spi, t->seq, t->sa_seq_hi,
+	    format_ipsec_crypto_alg,
 	    t->crypto_alg, format_ipsec_integ_alg, t->integ_alg,
 	    t->udp_encap ? " udp-encap-enabled" : "");
   return s;
@@ -521,7 +523,8 @@
 						    sizeof (*tr));
 	  tr->sa_index = sa_index0;
 	  tr->spi = sa0->spi;
-	  tr->seq = sa0->seq - 1;
+	  tr->seq = sa0->seq;
+	  tr->sa_seq_hi = sa0->seq_hi;
 	  tr->udp_encap = ipsec_sa_is_set_UDP_ENCAP (sa0);
 	  tr->crypto_alg = sa0->crypto_alg;
 	  tr->integ_alg = sa0->integ_alg;
diff --git a/src/vnet/ipsec/ipsec_sa.h b/src/vnet/ipsec/ipsec_sa.h
index 811f4ca..86d76b3 100644
--- a/src/vnet/ipsec/ipsec_sa.h
+++ b/src/vnet/ipsec/ipsec_sa.h
@@ -19,8 +19,6 @@
 #include <vnet/ip/ip.h>
 #include <vnet/fib/fib_node.h>
 
-#define IPSEC_SA_ANTI_REPLAY_WINDOW_SIZE (64)
-
 #define foreach_ipsec_crypto_alg    \
   _ (0, NONE, "none")               \
   _ (1, AES_CBC_128, "aes-cbc-128") \
@@ -232,18 +230,34 @@
 				       va_list * args);
 extern uword unformat_ipsec_key (unformat_input_t * input, va_list * args);
 
+/*
+ * Anti Replay definitions
+ */
+
+#define IPSEC_SA_ANTI_REPLAY_WINDOW_SIZE (64)
+#define IPSEC_SA_ANTI_REPLAY_WINDOW_MAX_INDEX (IPSEC_SA_ANTI_REPLAY_WINDOW_SIZE-1)
+
+/*
+ * sequence number less than the lower bound are outside of the window
+ * From RFC4303 Appendix A:
+ *  Bl = Tl - W + 1
+ */
+#define IPSEC_SA_ANTI_REPLAY_WINDOW_LOWER_BOUND(_tl) (_tl - IPSEC_SA_ANTI_REPLAY_WINDOW_SIZE + 1)
+
+/*
+ * Anti replay check.
+ *  inputs need to be in host byte order.
+ */
 always_inline int
-ipsec_sa_anti_replay_check (ipsec_sa_t * sa, u32 * seqp)
+ipsec_sa_anti_replay_check (ipsec_sa_t * sa, u32 seq)
 {
-  u32 seq, diff, tl, th;
+  u32 diff, tl, th;
+
   if ((sa->flags & IPSEC_SA_FLAG_USE_ANTI_REPLAY) == 0)
     return 0;
 
-  seq = clib_net_to_host_u32 (*seqp);
-
-  if ((sa->flags & IPSEC_SA_FLAG_USE_ESN) == 0)
+  if (!ipsec_sa_is_set_USE_ESN (sa))
     {
-
       if (PREDICT_TRUE (seq > sa->last_seq))
 	return 0;
 
@@ -261,50 +275,113 @@
   th = sa->last_seq_hi;
   diff = tl - seq;
 
-  if (PREDICT_TRUE (tl >= (IPSEC_SA_ANTI_REPLAY_WINDOW_SIZE - 1)))
+  if (PREDICT_TRUE (tl >= (IPSEC_SA_ANTI_REPLAY_WINDOW_MAX_INDEX)))
     {
-      if (seq >= (tl - IPSEC_SA_ANTI_REPLAY_WINDOW_SIZE + 1))
+      /*
+       * the last sequence number VPP recieved is more than one
+       * window size greater than zero.
+       * Case A from RFC4303 Appendix A.
+       */
+      if (seq < IPSEC_SA_ANTI_REPLAY_WINDOW_LOWER_BOUND (tl))
 	{
-	  sa->seq_hi = th;
-	  if (seq <= tl)
-	    return (sa->replay_window & (1ULL << diff)) ? 1 : 0;
-	  else
-	    return 0;
+	  /*
+	   * the received sequence number is lower than the lower bound
+	   * of the window, this could mean either a replay packet or that
+	   * the high sequence number has wrapped. if it decrypts corrently
+	   * then it's the latter.
+	   */
+	  sa->seq_hi = th + 1;
+	  return 0;
 	}
       else
 	{
-	  sa->seq_hi = th + 1;
-	  return 0;
+	  /*
+	   * the recieved sequence number greater than the low
+	   * end of the window.
+	   */
+	  sa->seq_hi = th;
+	  if (seq <= tl)
+	    /*
+	     * The recieved seq number is within bounds of the window
+	     * check if it's a duplicate
+	     */
+	    return (sa->replay_window & (1ULL << diff)) ? 1 : 0;
+	  else
+	    /*
+	     * The received sequence number is greater than the window
+	     * upper bound. this packet will move the window along, assuming
+	     * it decrypts correctly.
+	     */
+	    return 0;
 	}
     }
   else
     {
-      if (seq >= (tl - IPSEC_SA_ANTI_REPLAY_WINDOW_SIZE + 1))
+      /*
+       * the last sequence number VPP recieved is within one window
+       * size of zero, i.e. 0 < TL < WINDOW_SIZE, the lower bound is thus a
+       * large sequence number.
+       * Note that the check below uses unsiged integer arthimetic, so the
+       * RHS will be a larger number.
+       * Case B from RFC4303 Appendix A.
+       */
+      if (seq < IPSEC_SA_ANTI_REPLAY_WINDOW_LOWER_BOUND (tl))
 	{
-	  sa->seq_hi = th - 1;
-	  return (sa->replay_window & (1ULL << diff)) ? 1 : 0;
+	  /*
+	   * the sequence number is less than the lower bound.
+	   */
+	  if (seq <= tl)
+	    {
+	      /*
+	       * the packet is within the window upper bound.
+	       * check for duplicates.
+	       */
+	      sa->seq_hi = th;
+	      return (sa->replay_window & (1ULL << diff)) ? 1 : 0;
+	    }
+	  else
+	    {
+	      /*
+	       * the packet is less the window lower bound or greater than
+	       * the higher bound, depending on how you look at it...
+	       * We're assuming, given that the last sequence number received,
+	       * TL < WINDOW_SIZE, that a largeer seq num is more likely to be
+	       * a packet that moves the window forward, than a packet that has
+	       * wrapped the high sequence again. If it were the latter then
+	       * we've lost close to 2^32 packets.
+	       */
+	      sa->seq_hi = th;
+	      return 0;
+	    }
 	}
       else
 	{
-	  sa->seq_hi = th;
-	  if (seq <= tl)
-	    return (sa->replay_window & (1ULL << diff)) ? 1 : 0;
-	  else
-	    return 0;
+	  /*
+	   * the packet seq number is between the lower bound (a large nubmer)
+	   * and MAX_SEQ_NUM. This is in the window since the window upper bound
+	   * tl > 0.
+	   * However, since TL is the other side of 0 to the received
+	   * packet, the SA has moved on to a higher sequence number.
+	   */
+	  sa->seq_hi = th - 1;
+	  return (sa->replay_window & (1ULL << diff)) ? 1 : 0;
 	}
     }
 
   return 0;
 }
 
+/*
+ * Anti replay window advance
+ *  inputs need to be in host byte order.
+ */
 always_inline void
-ipsec_sa_anti_replay_advance (ipsec_sa_t * sa, u32 seqp)
+ipsec_sa_anti_replay_advance (ipsec_sa_t * sa, u32 seq)
 {
-  u32 pos, seq;
+  u32 pos;
   if (PREDICT_TRUE (sa->flags & IPSEC_SA_FLAG_USE_ANTI_REPLAY) == 0)
     return;
 
-  seq = clib_host_to_net_u32 (seqp);
   if (PREDICT_TRUE (sa->flags & IPSEC_SA_FLAG_USE_ESN))
     {
       int wrap = sa->seq_hi - sa->last_seq_hi;
diff --git a/test/patches/scapy-2.4/ipsec.patch b/test/patches/scapy-2.4/ipsec.patch
index 731fe3c..083b0b9 100644
--- a/test/patches/scapy-2.4/ipsec.patch
+++ b/test/patches/scapy-2.4/ipsec.patch
@@ -1,30 +1,30 @@
 diff --git a/scapy/layers/ipsec.py b/scapy/layers/ipsec.py
-index 69e7ae3b..0c69ba1a 100644
+index 69e7ae3b..3a1724b2 100644
 --- a/scapy/layers/ipsec.py
 +++ b/scapy/layers/ipsec.py
-@@ -344,7 +344,8 @@ class CryptAlgo(object):
+@@ -344,8 +344,7 @@ class CryptAlgo(object):
              encryptor = cipher.encryptor()
  
              if self.is_aead:
 -                aad = struct.pack('!LL', esp.spi, esp.seq)
-+                aad = struct.pack('!LQ' if sa.use_esn else '!LL',
-+                                  esp.spi, esp.seq)
-                 encryptor.authenticate_additional_data(aad)
+-                encryptor.authenticate_additional_data(aad)
++                encryptor.authenticate_additional_data(sa.build_aead(esp))
                  data = encryptor.update(data) + encryptor.finalize()
                  data += encryptor.tag[:self.icv_size]
-@@ -381,9 +382,9 @@ class CryptAlgo(object):
+             else:
+@@ -380,10 +379,7 @@ class CryptAlgo(object):
+ 
              if self.is_aead:
                  # Tag value check is done during the finalize method
-                 decryptor.authenticate_additional_data(
+-                decryptor.authenticate_additional_data(
 -                    struct.pack('!LL', esp.spi, esp.seq)
-+                    struct.pack('!LQ' if sa.use_esn else '!LL',
-+                                esp.spi, esp.seq)
-                 )
+-                )
 -
++                decryptor.authenticate_additional_data(sa.build_aead(esp))
              try:
                  data = decryptor.update(data) + decryptor.finalize()
              except InvalidTag as err:
-@@ -518,12 +519,16 @@ class AuthAlgo(object):
+@@ -518,12 +514,16 @@ class AuthAlgo(object):
          else:
              return self.mac(key, self.digestmod(), default_backend())
  
@@ -42,7 +42,7 @@
  
          @return: the signed packet
          """
-@@ -534,16 +539,20 @@ class AuthAlgo(object):
+@@ -534,16 +534,20 @@ class AuthAlgo(object):
  
          if pkt.haslayer(ESP):
              mac.update(raw(pkt[ESP]))
@@ -64,7 +64,7 @@
          """
          Check that the integrity check value (icv) of a packet is valid.
  
-@@ -574,6 +583,8 @@ class AuthAlgo(object):
+@@ -574,6 +578,8 @@ class AuthAlgo(object):
              clone = zero_mutable_fields(pkt.copy(), sending=False)
  
          mac.update(raw(clone))
@@ -73,7 +73,7 @@
          computed_icv = mac.finalize()[:self.icv_size]
  
          # XXX: Cannot use mac.verify because the ICV can be truncated
-@@ -757,7 +768,8 @@ class SecurityAssociation(object):
+@@ -757,7 +763,8 @@ class SecurityAssociation(object):
      SUPPORTED_PROTOS = (IP, IPv6)
  
      def __init__(self, proto, spi, seq_num=1, crypt_algo=None, crypt_key=None,
@@ -83,7 +83,7 @@
          """
          @param proto: the IPsec proto to use (ESP or AH)
          @param spi: the Security Parameters Index of this SA
-@@ -771,6 +783,7 @@ class SecurityAssociation(object):
+@@ -771,6 +778,7 @@ class SecurityAssociation(object):
                                to encapsulate the encrypted packets.
          @param nat_t_header: an instance of a UDP header that will be used
                               for NAT-Traversal.
@@ -91,7 +91,7 @@
          """
  
          if proto not in (ESP, AH, ESP.name, AH.name):
-@@ -782,6 +795,7 @@ class SecurityAssociation(object):
+@@ -782,6 +790,7 @@ class SecurityAssociation(object):
  
          self.spi = spi
          self.seq_num = seq_num
@@ -99,10 +99,16 @@
  
          if crypt_algo:
              if crypt_algo not in CRYPT_ALGOS:
-@@ -827,6 +841,17 @@ class SecurityAssociation(object):
+@@ -827,6 +836,23 @@ class SecurityAssociation(object):
              raise TypeError('packet spi=0x%x does not match the SA spi=0x%x' %
                              (pkt.spi, self.spi))
  
++    def build_aead(self, esp):
++        if self.use_esn:
++            return (struct.pack('!LLL', esp.spi, self.seq_num >> 32, esp.seq))
++        else:
++            return (struct.pack('!LL', esp.spi, esp.seq))
++
 +    def build_seq_num(self, num):
 +        # only lower order bits are  transmitted
 +        # higher order bits are used in the ICV
@@ -117,7 +123,7 @@
      def _encrypt_esp(self, pkt, seq_num=None, iv=None):
  
          if iv is None:
-@@ -835,7 +860,8 @@ class SecurityAssociation(object):
+@@ -835,7 +861,8 @@ class SecurityAssociation(object):
              if len(iv) != self.crypt_algo.iv_size:
                  raise TypeError('iv length must be %s' % self.crypt_algo.iv_size)
  
@@ -127,7 +133,7 @@
  
          if self.tunnel_header:
              tunnel = self.tunnel_header.copy()
-@@ -857,7 +883,7 @@ class SecurityAssociation(object):
+@@ -857,7 +884,7 @@ class SecurityAssociation(object):
          esp = self.crypt_algo.pad(esp)
          esp = self.crypt_algo.encrypt(self, esp, self.crypt_key)
  
@@ -136,7 +142,7 @@
  
          if self.nat_t_header:
              nat_t_header = self.nat_t_header.copy()
-@@ -884,7 +910,8 @@ class SecurityAssociation(object):
+@@ -884,7 +911,8 @@ class SecurityAssociation(object):
  
      def _encrypt_ah(self, pkt, seq_num=None):
  
@@ -146,7 +152,7 @@
                  icv = b"\x00" * self.auth_algo.icv_size)
  
          if self.tunnel_header:
-@@ -924,7 +951,8 @@ class SecurityAssociation(object):
+@@ -924,7 +952,8 @@ class SecurityAssociation(object):
          else:
              ip_header.plen = len(ip_header.payload) + len(ah) + len(payload)
  
@@ -156,7 +162,7 @@
  
          # sequence number must always change, unless specified by the user
          if seq_num is None:
-@@ -955,11 +983,12 @@ class SecurityAssociation(object):
+@@ -955,11 +984,12 @@ class SecurityAssociation(object):
  
      def _decrypt_esp(self, pkt, verify=True):
  
@@ -170,7 +176,7 @@
  
          esp = self.crypt_algo.decrypt(self, encrypted, self.crypt_key,
                                        self.crypt_algo.icv_size or
-@@ -998,9 +1027,11 @@ class SecurityAssociation(object):
+@@ -998,9 +1028,11 @@ class SecurityAssociation(object):
  
      def _decrypt_ah(self, pkt, verify=True):
  
diff --git a/test/template_ipsec.py b/test/template_ipsec.py
index e40fa56..25cff7f 100644
--- a/test/template_ipsec.py
+++ b/test/template_ipsec.py
@@ -84,14 +84,18 @@
         self.nat_header = None
 
 
+def mk_scapy_crpyt_key(p):
+    if p.crypt_algo == "AES-GCM":
+        return p.crypt_key + struct.pack("!I", p.salt)
+    else:
+        return p.crypt_key
+
+
 def config_tun_params(p, encryption_type, tun_if):
     ip_class_by_addr_type = {socket.AF_INET: IP, socket.AF_INET6: IPv6}
     use_esn = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.
                               IPSEC_API_SAD_FLAG_USE_ESN))
-    if p.crypt_algo == "AES-GCM":
-        crypt_key = p.crypt_key + struct.pack("!I", p.salt)
-    else:
-        crypt_key = p.crypt_key
+    crypt_key = mk_scapy_crpyt_key(p)
     p.scapy_tun_sa = SecurityAssociation(
         encryption_type, spi=p.vpp_tun_spi,
         crypt_algo=p.crypt_algo,
@@ -117,10 +121,7 @@
 def config_tra_params(p, encryption_type):
     use_esn = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.
                               IPSEC_API_SAD_FLAG_USE_ESN))
-    if p.crypt_algo == "AES-GCM":
-        crypt_key = p.crypt_key + struct.pack("!I", p.salt)
-    else:
-        crypt_key = p.crypt_key
+    crypt_key = mk_scapy_crpyt_key(p)
     p.scapy_tra_sa = SecurityAssociation(
         encryption_type,
         spi=p.vpp_tra_spi,
@@ -269,32 +270,68 @@
 
 class IpsecTra4(object):
     """ verify methods for Transport v4 """
-    def verify_tra_anti_replay(self, count=1):
+    def verify_tra_anti_replay(self):
         p = self.params[socket.AF_INET]
         use_esn = p.vpp_tra_sa.use_esn
 
-        # fire in a packet with seq number 1
-        pkt = (Ether(src=self.tra_if.remote_mac,
-                     dst=self.tra_if.local_mac) /
-               p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
-                                         dst=self.tra_if.local_ip4) /
-                                      ICMP(),
-                                      seq_num=1))
-        recv_pkts = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
+        seq_cycle_node_name = ('/err/%s/sequence number cycled' %
+                               self.tra4_encrypt_node_name)
+        replay_node_name = ('/err/%s/SA replayed packet' %
+                            self.tra4_decrypt_node_name)
+        if ESP == self.encryption_type and p.crypt_algo == "AES-GCM":
+            hash_failed_node_name = ('/err/%s/ESP decryption failed' %
+                                     self.tra4_decrypt_node_name)
+        else:
+            hash_failed_node_name = ('/err/%s/Integrity check failed' %
+                                     self.tra4_decrypt_node_name)
+        replay_count = self.statistics.get_err_counter(replay_node_name)
+        hash_failed_count = self.statistics.get_err_counter(
+            hash_failed_node_name)
+        seq_cycle_count = self.statistics.get_err_counter(seq_cycle_node_name)
 
-        # now move the window over to 235
+        if ESP == self.encryption_type:
+            undersize_node_name = ('/err/%s/undersized packet' %
+                                   self.tra4_decrypt_node_name)
+            undersize_count = self.statistics.get_err_counter(
+                undersize_node_name)
+
+        #
+        # send packets with seq numbers 1->34
+        # this means the window size is still in Case B (see RFC4303
+        # Appendix A)
+        #
+        # for reasons i haven't investigated Scapy won't create a packet with
+        # seq_num=0
+        #
+        pkts = [(Ether(src=self.tra_if.remote_mac,
+                       dst=self.tra_if.local_mac) /
+                 p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
+                                           dst=self.tra_if.local_ip4) /
+                                        ICMP(),
+                                        seq_num=seq))
+                for seq in range(1, 34)]
+        recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if)
+
+        # replayed packets are dropped
+        self.send_and_assert_no_replies(self.tra_if, pkts)
+        replay_count += len(pkts)
+        self.assert_error_counter_equal(replay_node_name, replay_count)
+
+        #
+        # now move the window over to 257 (more than one byte) and into Case A
+        #
         pkt = (Ether(src=self.tra_if.remote_mac,
                      dst=self.tra_if.local_mac) /
                p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
                                          dst=self.tra_if.local_ip4) /
                                       ICMP(),
-                                      seq_num=235))
+                                      seq_num=257))
         recv_pkts = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
 
         # replayed packets are dropped
         self.send_and_assert_no_replies(self.tra_if, pkt * 3)
-        self.assert_error_counter_equal(
-            '/err/%s/SA replayed packet' % self.tra4_decrypt_node_name, 3)
+        replay_count += 3
+        self.assert_error_counter_equal(replay_node_name, replay_count)
 
         # the window size is 64 packets
         # in window are still accepted
@@ -303,14 +340,14 @@
                p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
                                          dst=self.tra_if.local_ip4) /
                                       ICMP(),
-                                      seq_num=172))
+                                      seq_num=200))
         recv_pkts = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
 
         # a packet that does not decrypt does not move the window forward
         bogus_sa = SecurityAssociation(self.encryption_type,
                                        p.vpp_tra_spi,
                                        crypt_algo=p.crypt_algo,
-                                       crypt_key=p.crypt_key[::-1],
+                                       crypt_key=mk_scapy_crpyt_key(p)[::-1],
                                        auth_algo=p.auth_algo,
                                        auth_key=p.auth_key[::-1])
         pkt = (Ether(src=self.tra_if.remote_mac,
@@ -321,8 +358,9 @@
                                 seq_num=350))
         self.send_and_assert_no_replies(self.tra_if, pkt * 17)
 
-        self.assert_error_counter_equal(
-            '/err/%s/Integrity check failed' % self.tra4_decrypt_node_name, 17)
+        hash_failed_count += 17
+        self.assert_error_counter_equal(hash_failed_node_name,
+                                        hash_failed_count)
 
         # a malformed 'runt' packet
         #  created by a mis-constructed SA
@@ -337,8 +375,9 @@
                                     seq_num=350))
             self.send_and_assert_no_replies(self.tra_if, pkt * 17)
 
-            self.assert_error_counter_equal(
-                '/err/%s/undersized packet' % self.tra4_decrypt_node_name, 17)
+            undersize_count += 17
+            self.assert_error_counter_equal(undersize_node_name,
+                                            undersize_count)
 
         # which we can determine since this packet is still in the window
         pkt = (Ether(src=self.tra_if.remote_mac,
@@ -349,7 +388,11 @@
                                       seq_num=234))
         self.send_and_expect(self.tra_if, [pkt], self.tra_if)
 
+        #
         # out of window are dropped
+        #  this is Case B. So VPP will consider this to be a high seq num wrap
+        #  and so the decrypt attempt will fail
+        #
         pkt = (Ether(src=self.tra_if.remote_mac,
                      dst=self.tra_if.local_mac) /
                p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
@@ -361,44 +404,59 @@
         if use_esn:
             # an out of window error with ESN looks like a high sequence
             # wrap. but since it isn't then the verify will fail.
-            self.assert_error_counter_equal(
-                '/err/%s/Integrity check failed' %
-                self.tra4_decrypt_node_name, 34)
+            hash_failed_count += 17
+            self.assert_error_counter_equal(hash_failed_node_name,
+                                            hash_failed_count)
 
         else:
-            self.assert_error_counter_equal(
-                '/err/%s/SA replayed packet' %
-                self.tra4_decrypt_node_name, 20)
+            replay_count += 17
+            self.assert_error_counter_equal(replay_node_name,
+                                            replay_count)
 
-        # valid packet moves the window over to 236
+        # valid packet moves the window over to 258
         pkt = (Ether(src=self.tra_if.remote_mac,
                      dst=self.tra_if.local_mac) /
                p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
                                          dst=self.tra_if.local_ip4) /
                                       ICMP(),
-                                      seq_num=236))
+                                      seq_num=258))
         rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
         decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
 
-        # move VPP's SA to just before the seq-number wrap
+        #
+        # move VPP's SA TX seq-num to just before the seq-number wrap.
+        # then fire in a packet that VPP should drop on TX because it
+        # causes the TX seq number to wrap; unless we're using extened sequence
+        # numbers.
+        #
         self.vapi.cli("test ipsec sa %d seq 0xffffffff" % p.scapy_tra_sa_id)
+        self.logger.info(self.vapi.ppcli("show ipsec sa 0"))
+        self.logger.info(self.vapi.ppcli("show ipsec sa 1"))
 
-        # then fire in a packet that VPP should drop because it causes the
-        # seq number to wrap  unless we're using extended.
-        pkt = (Ether(src=self.tra_if.remote_mac,
-                     dst=self.tra_if.local_mac) /
-               p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
-                                         dst=self.tra_if.local_ip4) /
-                                      ICMP(),
-                                      seq_num=237))
+        pkts = [(Ether(src=self.tra_if.remote_mac,
+                       dst=self.tra_if.local_mac) /
+                 p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
+                                           dst=self.tra_if.local_ip4) /
+                                        ICMP(),
+                                        seq_num=seq))
+                for seq in range(259, 280)]
 
         if use_esn:
-            rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
-            # in order to decrpyt the high order number needs to wrap
-            p.vpp_tra_sa.seq_num = 0x100000000
-            decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
+            rxs = self.send_and_expect(self.tra_if, pkts, self.tra_if)
 
-            # send packets with high bits set
+            #
+            # in order for scapy to decrypt its SA's high order number needs
+            # to wrap
+            #
+            p.vpp_tra_sa.seq_num = 0x100000000
+            for rx in rxs:
+                decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
+
+            #
+            # wrap scapy's TX high sequence number. VPP is in case B, so it
+            # will consider this a high seq wrap also.
+            # The low seq num we set it to will place VPP's RX window in Case A
+            #
             p.scapy_tra_sa.seq_num = 0x100000005
             pkt = (Ether(src=self.tra_if.remote_mac,
                          dst=self.tra_if.local_mac) /
@@ -407,13 +465,72 @@
                                           ICMP(),
                                           seq_num=0x100000005))
             rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
-            # in order to decrpyt the high order number needs to wrap
             decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
+
+            #
+            # A packet that has seq num between (2^32-64) and 5 is within
+            # the window
+            #
+            p.scapy_tra_sa.seq_num = 0xfffffffd
+            pkt = (Ether(src=self.tra_if.remote_mac,
+                         dst=self.tra_if.local_mac) /
+                   p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
+                                             dst=self.tra_if.local_ip4) /
+                                          ICMP(),
+                                          seq_num=0xfffffffd))
+            rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
+            decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
+
+            #
+            # While in case A we cannot wrap the high sequence number again
+            # becuase VPP will consider this packet to be one that moves the
+            # window forward
+            #
+            pkt = (Ether(src=self.tra_if.remote_mac,
+                         dst=self.tra_if.local_mac) /
+                   p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
+                                             dst=self.tra_if.local_ip4) /
+                                          ICMP(),
+                                          seq_num=0x200000999))
+            self.send_and_assert_no_replies(self.tra_if, [pkt], self.tra_if)
+
+            hash_failed_count += 1
+            self.assert_error_counter_equal(hash_failed_node_name,
+                                            hash_failed_count)
+
+            #
+            # but if we move the wondow forward to case B, then we can wrap
+            # again
+            #
+            p.scapy_tra_sa.seq_num = 0x100000555
+            pkt = (Ether(src=self.tra_if.remote_mac,
+                         dst=self.tra_if.local_mac) /
+                   p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
+                                             dst=self.tra_if.local_ip4) /
+                                          ICMP(),
+                                          seq_num=0x100000555))
+            rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
+            decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
+
+            p.scapy_tra_sa.seq_num = 0x200000444
+            pkt = (Ether(src=self.tra_if.remote_mac,
+                         dst=self.tra_if.local_mac) /
+                   p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
+                                             dst=self.tra_if.local_ip4) /
+                                          ICMP(),
+                                          seq_num=0x200000444))
+            rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
+            decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
+
         else:
-            self.send_and_assert_no_replies(self.tra_if, [pkt])
-            self.assert_error_counter_equal(
-                '/err/%s/sequence number cycled' %
-                self.tra4_encrypt_node_name, 1)
+            #
+            # without ESN TX sequence numbers can't wrap and packets are
+            # dropped from here on out.
+            #
+            self.send_and_assert_no_replies(self.tra_if, pkts)
+            seq_cycle_count += len(pkts)
+            self.assert_error_counter_equal(seq_cycle_node_name,
+                                            seq_cycle_count)
 
         # move the security-associations seq number on to the last we used
         self.vapi.cli("test ipsec sa %d seq 0x15f" % p.scapy_tra_sa_id)
@@ -423,6 +540,7 @@
     def verify_tra_basic4(self, count=1):
         """ ipsec v4 transport basic test """
         self.vapi.cli("clear errors")
+        self.vapi.cli("clear ipsec sa")
         try:
             p = self.params[socket.AF_INET]
             send_pkts = self.gen_encrypt_pkts(p.scapy_tra_sa, self.tra_if,
@@ -461,7 +579,7 @@
     """ UT test methods for Transport v4 """
     def test_tra_anti_replay(self):
         """ ipsec v4 transport anti-reply test """
-        self.verify_tra_anti_replay(count=1)
+        self.verify_tra_anti_replay()
 
     def test_tra_basic(self, count=1):
         """ ipsec v4 transport basic test """
diff --git a/test/test_ipsec_esp.py b/test/test_ipsec_esp.py
index 4da8891..f5bbc54 100644
--- a/test/test_ipsec_esp.py
+++ b/test/test_ipsec_esp.py
@@ -486,6 +486,14 @@
                     #
                     self.unconfig_network()
 
+                    #
+                    # reconfigure the network and SA to run the
+                    # anti replay tests
+                    #
+                    self.config_network(self.params.values())
+                    self.verify_tra_anti_replay()
+                    self.unconfig_network()
+
 
 if __name__ == '__main__':
     unittest.main(testRunner=VppTestRunner)