Merge "Support decoding inbound Delete Payload" am: 0bc49b110c
am: 4a996bc87f

Change-Id: I7abf94c9136a741c8a16b690ce4146a7bb433e40
diff --git a/src/java/com/android/ike/ikev2/message/IkeDeletePayload.java b/src/java/com/android/ike/ikev2/message/IkeDeletePayload.java
new file mode 100644
index 0000000..fd4f364
--- /dev/null
+++ b/src/java/com/android/ike/ikev2/message/IkeDeletePayload.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.ike.ikev2.message;
+
+import com.android.ike.ikev2.exceptions.IkeException;
+import com.android.ike.ikev2.exceptions.InvalidSyntaxException;
+
+import java.nio.ByteBuffer;
+
+/**
+ * IkeDeletePayload represents a Delete Payload.
+ *
+ * <p>As instructed in RFC 7296, deletion of the IKE SA is indicated by a protocol ID of 1 (IKE) but
+ * no SPIs. Deletion of a Child SA will contain the IPsec protocol ID and SPIs of inbound IPsec
+ * packets. Since IKE library only supports negotiating Child SA using ESP, only the protocol ID of
+ * 3 (ESP) is used for deleting Child SA.
+ *
+ * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.11">RFC 7296, Internet Key Exchange
+ *     Protocol Version 2 (IKEv2)</a>
+ */
+public final class IkeDeletePayload extends IkePayload {
+
+    @ProtocolId public final int protocolId;
+    public final byte spiSize;
+    public final int numSpi;
+    public final int[] spisToDelete;
+
+    /**
+     * Construct an instance of IkeDeletePayload from decoding inbound IKE packet.
+     *
+     * <p>NegativeArraySizeException and BufferUnderflowException will be caught in {@link
+     * IkeMessage}
+     *
+     * @param critical indicates if this payload is critical. Ignored in supported payload as
+     *     instructed by the RFC 7296.
+     * @param payloadBody payload body in byte array
+     * @throws IkeException if there is any error
+     */
+    IkeDeletePayload(boolean critical, byte[] payloadBody) throws IkeException {
+        super(PAYLOAD_TYPE_DELETE, critical);
+
+        ByteBuffer inputBuffer = ByteBuffer.wrap(payloadBody);
+
+        protocolId = Byte.toUnsignedInt(inputBuffer.get());
+        spiSize = inputBuffer.get();
+        numSpi = Short.toUnsignedInt(inputBuffer.getShort());
+        spisToDelete = new int[numSpi];
+
+        switch (protocolId) {
+            case PROTOCOL_ID_IKE:
+                // Delete payload for IKE SA must not include SPI.
+                if (spiSize != SPI_LEN_NOT_INCLUDED
+                        || numSpi != 0
+                        || inputBuffer.remaining() != 0) {
+                    throw new InvalidSyntaxException("Invalid Delete IKE Payload.");
+                }
+                break;
+            case PROTOCOL_ID_ESP:
+                // Delete payload for Child SA must include SPI
+                if (spiSize != SPI_LEN_IPSEC
+                        || numSpi == 0
+                        || inputBuffer.remaining() != SPI_LEN_IPSEC * numSpi) {
+                    throw new InvalidSyntaxException("Invalid Delete Child Payload.");
+                }
+
+                for (int i = 0; i < numSpi; i++) {
+                    spisToDelete[i] = inputBuffer.getInt();
+                }
+                break;
+            default:
+                throw new InvalidSyntaxException("Unrecognized protocol in Delete Payload.");
+        }
+    }
+
+    // TODO: Add a constructor for building outbound IKE message.
+
+    /**
+     * Encode Delete Payload to ByteBuffer.
+     *
+     * @param nextPayload type of payload that follows this payload.
+     * @param byteBuffer destination ByteBuffer that stores encoded payload.
+     */
+    @Override
+    protected void encodeToByteBuffer(@PayloadType int nextPayload, ByteBuffer byteBuffer) {
+        throw new UnsupportedOperationException("Operation not supported.");
+        // TODO: Implement it.
+    }
+
+    /**
+     * Get entire payload length.
+     *
+     * @return entire payload length.
+     */
+    @Override
+    protected int getPayloadLength() {
+        throw new UnsupportedOperationException("Operation not supported.");
+        // TODO: Implement it.
+    }
+
+    /**
+     * Return the payload type as a String.
+     *
+     * @return the payload type as a String.
+     */
+    @Override
+    public String getTypeString() {
+        return "Delete Payload";
+    }
+}
diff --git a/src/java/com/android/ike/ikev2/message/IkeNotifyPayload.java b/src/java/com/android/ike/ikev2/message/IkeNotifyPayload.java
index 4b581e0..ee6fe47 100644
--- a/src/java/com/android/ike/ikev2/message/IkeNotifyPayload.java
+++ b/src/java/com/android/ike/ikev2/message/IkeNotifyPayload.java
@@ -40,7 +40,7 @@
  * outbound packet.
  *
  * @see <a href="https://tools.ietf.org/html/rfc7296">RFC 7296, Internet Key Exchange Protocol
- *     Version 2 (IKEv2).
+ *     Version 2 (IKEv2)</a>
  */
 public final class IkeNotifyPayload extends IkePayload {
 
diff --git a/src/java/com/android/ike/ikev2/message/IkePayload.java b/src/java/com/android/ike/ikev2/message/IkePayload.java
index 09daa17..2474bb6 100644
--- a/src/java/com/android/ike/ikev2/message/IkePayload.java
+++ b/src/java/com/android/ike/ikev2/message/IkePayload.java
@@ -53,6 +53,7 @@
         PAYLOAD_TYPE_ID_RESPONDER,
         PAYLOAD_TYPE_NONCE,
         PAYLOAD_TYPE_NOTIFY,
+        PAYLOAD_TYPE_DELETE,
         PAYLOAD_TYPE_VENDOR,
         PAYLOAD_TYPE_TS_INITIATOR,
         PAYLOAD_TYPE_TS_RESPONDER,
@@ -78,6 +79,8 @@
     public static final int PAYLOAD_TYPE_NONCE = 40;
     /** Notify Payload */
     public static final int PAYLOAD_TYPE_NOTIFY = 41;
+    /** Delete Payload */
+    public static final int PAYLOAD_TYPE_DELETE = 42;
     /** Vendor Payload */
     public static final int PAYLOAD_TYPE_VENDOR = 43;
     /** Traffic Selector Payload of Child SA Initiator */
diff --git a/src/java/com/android/ike/ikev2/message/IkePayloadFactory.java b/src/java/com/android/ike/ikev2/message/IkePayloadFactory.java
index a064b6f..bea87ca 100644
--- a/src/java/com/android/ike/ikev2/message/IkePayloadFactory.java
+++ b/src/java/com/android/ike/ikev2/message/IkePayloadFactory.java
@@ -78,6 +78,8 @@
                     return new IkeNoncePayload(isCritical, payloadBody);
                 case IkePayload.PAYLOAD_TYPE_NOTIFY:
                     return new IkeNotifyPayload(isCritical, payloadBody);
+                case IkePayload.PAYLOAD_TYPE_DELETE:
+                    return new IkeDeletePayload(isCritical, payloadBody);
                 case IkePayload.PAYLOAD_TYPE_VENDOR:
                     return new IkeVendorPayload(isCritical, payloadBody);
                 case IkePayload.PAYLOAD_TYPE_TS_INITIATOR:
diff --git a/tests/iketests/src/java/com/android/ike/ikev2/message/IkeDeletePayloadTest.java b/tests/iketests/src/java/com/android/ike/ikev2/message/IkeDeletePayloadTest.java
new file mode 100644
index 0000000..1a7b9a2
--- /dev/null
+++ b/tests/iketests/src/java/com/android/ike/ikev2/message/IkeDeletePayloadTest.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.ike.ikev2.message;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.android.ike.ikev2.exceptions.InvalidSyntaxException;
+
+import org.junit.Test;
+
+import java.nio.ByteBuffer;
+
+public final class IkeDeletePayloadTest {
+    private static final String DELETE_IKE_PAYLOAD_HEX_STRING = "0000000801000000";
+    private static final String DELETE_CHILD_PAYLOAD_HEX_STRING = "0000000c030400012ad4c0a2";
+    private static final String CHILD_SPI = "2ad4c0a2";
+
+    private static final int NUM_CHILD_SPI = 1;
+
+    private static final int PROTOCOL_ID_OFFSET = 4;
+    private static final int SPI_SIZE_OFFSET = 5;
+    private static final int NUM_OF_SPI_OFFSET = 6;
+
+    @Test
+    public void testDecodeDeleteIkePayload() throws Exception {
+        ByteBuffer inputBuffer =
+                ByteBuffer.wrap(TestUtils.hexStringToByteArray(DELETE_IKE_PAYLOAD_HEX_STRING));
+
+        IkePayload payload =
+                IkePayloadFactory.getIkePayload(
+                                IkePayload.PAYLOAD_TYPE_DELETE, false /*is request*/, inputBuffer)
+                        .first;
+
+        assertTrue(payload instanceof IkeDeletePayload);
+
+        IkeDeletePayload deletePayload = (IkeDeletePayload) payload;
+        assertEquals(IkePayload.PROTOCOL_ID_IKE, deletePayload.protocolId);
+        assertEquals(IkePayload.SPI_LEN_NOT_INCLUDED, deletePayload.spiSize);
+        assertEquals(0, deletePayload.numSpi);
+        assertArrayEquals(new int[0], deletePayload.spisToDelete);
+    }
+
+    @Test
+    public void testDecodeDeleteChildPayload() throws Exception {
+        ByteBuffer inputBuffer =
+                ByteBuffer.wrap(TestUtils.hexStringToByteArray(DELETE_CHILD_PAYLOAD_HEX_STRING));
+
+        IkePayload payload =
+                IkePayloadFactory.getIkePayload(
+                                IkePayload.PAYLOAD_TYPE_DELETE, false /*is request*/, inputBuffer)
+                        .first;
+
+        assertTrue(payload instanceof IkeDeletePayload);
+
+        IkeDeletePayload deletePayload = (IkeDeletePayload) payload;
+        assertEquals(IkePayload.PROTOCOL_ID_ESP, deletePayload.protocolId);
+        assertEquals(IkePayload.SPI_LEN_IPSEC, deletePayload.spiSize);
+        assertEquals(NUM_CHILD_SPI, deletePayload.numSpi);
+
+        byte[] childSpiBytes = TestUtils.hexStringToByteArray(CHILD_SPI);
+        ByteBuffer buffer = ByteBuffer.wrap(childSpiBytes);
+        int expectedChildSpi = buffer.getInt();
+
+        assertArrayEquals(new int[] {expectedChildSpi}, deletePayload.spisToDelete);
+    }
+
+    @Test
+    public void testDecodeWithInvalidProtocol() throws Exception {
+        byte[] deletePayloadBytes = TestUtils.hexStringToByteArray(DELETE_IKE_PAYLOAD_HEX_STRING);
+        deletePayloadBytes[PROTOCOL_ID_OFFSET] = -1;
+        ByteBuffer inputBuffer = ByteBuffer.wrap(deletePayloadBytes);
+
+        try {
+            IkePayloadFactory.getIkePayload(
+                    IkePayload.PAYLOAD_TYPE_DELETE, false /*is request*/, inputBuffer);
+            fail("Expected to fail due to unrecognized protocol ID.");
+        } catch (InvalidSyntaxException expected) {
+
+        }
+    }
+
+    @Test
+    public void testDecodeWithInvalidSpiSize() throws Exception {
+        byte[] deletePayloadBytes = TestUtils.hexStringToByteArray(DELETE_IKE_PAYLOAD_HEX_STRING);
+        deletePayloadBytes[SPI_SIZE_OFFSET] = IkePayload.SPI_LEN_IPSEC;
+        ByteBuffer inputBuffer = ByteBuffer.wrap(deletePayloadBytes);
+
+        try {
+            IkePayloadFactory.getIkePayload(
+                    IkePayload.PAYLOAD_TYPE_DELETE, false /*is request*/, inputBuffer);
+            fail("Expected to fail due to invalid SPI size in Delete IKE Payload.");
+        } catch (InvalidSyntaxException expected) {
+
+        }
+    }
+
+    @Test
+    public void testDecodeWithInvalidNumSpi() throws Exception {
+        byte[] deletePayloadBytes = TestUtils.hexStringToByteArray(DELETE_IKE_PAYLOAD_HEX_STRING);
+        deletePayloadBytes[NUM_OF_SPI_OFFSET] = 1;
+        ByteBuffer inputBuffer = ByteBuffer.wrap(deletePayloadBytes);
+
+        try {
+            IkePayloadFactory.getIkePayload(
+                    IkePayload.PAYLOAD_TYPE_DELETE, false /*is request*/, inputBuffer);
+            fail("Expected to fail because number of SPI is not zero in Delete IKE Payload.");
+        } catch (InvalidSyntaxException expected) {
+
+        }
+    }
+
+    @Test
+    public void testDecodeWithInvalidNumSpiAndSpiSize() throws Exception {
+        byte[] deletePayloadBytes = TestUtils.hexStringToByteArray(DELETE_IKE_PAYLOAD_HEX_STRING);
+        deletePayloadBytes[SPI_SIZE_OFFSET] = 1;
+        deletePayloadBytes[NUM_CHILD_SPI] = 4;
+        ByteBuffer inputBuffer = ByteBuffer.wrap(deletePayloadBytes);
+
+        try {
+            IkePayloadFactory.getIkePayload(
+                    IkePayload.PAYLOAD_TYPE_DELETE, false /*is request*/, inputBuffer);
+            fail("Expected to fail due to invalid SPI size in Delete IKE Payload.");
+        } catch (InvalidSyntaxException expected) {
+
+        }
+    }
+}