aboutsummaryrefslogtreecommitdiff
path: root/tests/iketests/src/java/com/android/internal/net/ipsec/ike/IkeSocketTest.java
blob: 1b8761f749a574d850dcea3123abc9b52faaacc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * 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.internal.net.ipsec.ike;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import android.content.Context;
import android.net.IpSecManager;
import android.net.IpSecManager.UdpEncapsulationSocket;
import android.os.HandlerThread;
import android.os.Looper;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import android.util.Log;
import android.util.LongSparseArray;

import androidx.test.InstrumentationRegistry;

import com.android.internal.net.TestUtils;
import com.android.internal.net.ipsec.ike.IkeSocket.PacketReceiver;
import com.android.internal.net.ipsec.ike.message.IkeHeader;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

import java.io.FileDescriptor;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public final class IkeSocketTest {
    private static final int REMOTE_RECV_BUFF_SIZE = 2048;
    private static final int TIMEOUT = 1000;

    private static final String NON_ESP_MARKER_HEX_STRING = "00000000";
    private static final String IKE_REQ_MESSAGE_HEX_STRING =
            "5f54bf6d8b48e6e100000000000000002120220800000000"
                    + "00000150220000300000002c010100040300000c0100000c"
                    + "800e00800300000803000002030000080400000200000008"
                    + "020000022800008800020000b4a2faf4bb54878ae21d6385"
                    + "12ece55d9236fc5046ab6cef82220f421f3ce6361faf3656"
                    + "4ecb6d28798a94aad7b2b4b603ddeaaa5630adb9ece8ac37"
                    + "534036040610ebdd92f46bef84f0be7db860351843858f8a"
                    + "cf87056e272377f70c9f2d81e29c7b0ce4f291a3a72476bb"
                    + "0b278fd4b7b0a4c26bbeb08214c707137607958729000024"
                    + "c39b7f368f4681b89fa9b7be6465abd7c5f68b6ed5d3b4c7"
                    + "2cb4240eb5c464122900001c00004004e54f73b7d83f6beb"
                    + "881eab2051d8663f421d10b02b00001c00004005d915368c"
                    + "a036004cb578ae3e3fb268509aeab1900000002069936922"
                    + "8741c6d4ca094c93e242c9de19e7b7c60000000500000500";

    private static final String LOCAL_SPI = "0000000000000000";
    private static final String REMOTE_SPI = "5f54bf6d8b48e6e1";

    private static final String DATA_ONE = "one 1";
    private static final String DATA_TWO = "two 2";

    private static final String IPV4_LOOPBACK = "127.0.0.1";

    private byte[] mDataOne;
    private byte[] mDataTwo;

    private long mLocalSpi;
    private long mRemoteSpi;

    private LongSparseArray mSpiToIkeStateMachineMap;
    private PacketReceiver mPacketReceiver;

    private UdpEncapsulationSocket mClientUdpEncapSocket;
    private InetAddress mLocalAddress;
    private FileDescriptor mDummyRemoteServerFd;

    private IkeSessionStateMachine mMockIkeSessionStateMachine;

    @Before
    public void setUp() throws Exception {
        Context context = InstrumentationRegistry.getContext();
        IpSecManager ipSecManager = (IpSecManager) context.getSystemService(Context.IPSEC_SERVICE);
        mClientUdpEncapSocket = ipSecManager.openUdpEncapsulationSocket();

        mLocalAddress = InetAddress.getByName(IPV4_LOOPBACK);
        mDummyRemoteServerFd = getBoundUdpSocket(mLocalAddress);

        mDataOne = DATA_ONE.getBytes("UTF-8");
        mDataTwo = DATA_TWO.getBytes("UTF-8");

        ByteBuffer localSpiBuffer = ByteBuffer.wrap(TestUtils.hexStringToByteArray(LOCAL_SPI));
        mLocalSpi = localSpiBuffer.getLong();
        ByteBuffer remoteSpiBuffer = ByteBuffer.wrap(TestUtils.hexStringToByteArray(REMOTE_SPI));
        mRemoteSpi = remoteSpiBuffer.getLong();

        mMockIkeSessionStateMachine = mock(IkeSessionStateMachine.class);

        mSpiToIkeStateMachineMap = new LongSparseArray<IkeSessionStateMachine>();
        mSpiToIkeStateMachineMap.put(mLocalSpi, mMockIkeSessionStateMachine);

        mPacketReceiver = new IkeSocket.PacketReceiver();
    }

    @After
    public void tearDown() throws Exception {
        mClientUdpEncapSocket.close();
        IkeSocket.setPacketReceiver(mPacketReceiver);
        Os.close(mDummyRemoteServerFd);
    }

    private static FileDescriptor getBoundUdpSocket(InetAddress address) throws Exception {
        FileDescriptor sock =
                Os.socket(OsConstants.AF_INET, OsConstants.SOCK_DGRAM, OsConstants.IPPROTO_UDP);
        Os.bind(sock, address, IkeSocket.IKE_SERVER_PORT);
        return sock;
    }

    @Test
    public void testGetAndCloseIkeSocket() throws Exception {
        // Must be prepared here; AndroidJUnitRunner runs tests on different threads from the
        // setUp() call. Since the new Handler() call is run in getIkeSocket, the Looper must be
        // prepared here.
        if (Looper.myLooper() == null) Looper.prepare();

        IkeSessionStateMachine mMockIkeSessionOne = mock(IkeSessionStateMachine.class);
        IkeSessionStateMachine mMockIkeSessionTwo = mock(IkeSessionStateMachine.class);

        IkeSocket ikeSocketOne = IkeSocket.getIkeSocket(mClientUdpEncapSocket, mMockIkeSessionOne);
        assertEquals(1, ikeSocketOne.mAliveIkeSessions.size());

        IkeSocket ikeSocketTwo = IkeSocket.getIkeSocket(mClientUdpEncapSocket, mMockIkeSessionTwo);
        assertEquals(ikeSocketOne, ikeSocketTwo);
        assertEquals(2, ikeSocketTwo.mAliveIkeSessions.size());

        ikeSocketOne.releaseReference(mMockIkeSessionOne);
        assertEquals(1, ikeSocketOne.mAliveIkeSessions.size());

        ikeSocketTwo.releaseReference(mMockIkeSessionTwo);
        assertEquals(0, ikeSocketTwo.mAliveIkeSessions.size());
    }

    @Test
    public void testSendIkePacket() throws Exception {
        if (Looper.myLooper() == null) Looper.prepare();

        // Send IKE packet
        IkeSocket ikeSocket =
                IkeSocket.getIkeSocket(mClientUdpEncapSocket, mMockIkeSessionStateMachine);
        ikeSocket.sendIkePacket(mDataOne, mLocalAddress);

        byte[] receivedData = receive(mDummyRemoteServerFd);

        // Verify received data
        ByteBuffer expectedBuffer =
                ByteBuffer.allocate(IkeSocket.NON_ESP_MARKER_LEN + mDataOne.length);
        expectedBuffer.put(IkeSocket.NON_ESP_MARKER).put(mDataOne);

        assertArrayEquals(expectedBuffer.array(), receivedData);

        ikeSocket.releaseReference(mMockIkeSessionStateMachine);
    }

    @Test
    public void testReceiveIkePacket() throws Exception {
        // Create working thread.
        HandlerThread mIkeThread = new HandlerThread("IkeSocketTest");
        mIkeThread.start();

        // Create IkeSocket on working thread.
        IkeSocketReceiver socketReceiver = new IkeSocketReceiver();
        TestCountDownLatch createLatch = new TestCountDownLatch();
        mIkeThread
                .getThreadHandler()
                .post(
                        () -> {
                            try {
                                socketReceiver.setIkeSocket(
                                        IkeSocket.getIkeSocket(
                                                mClientUdpEncapSocket,
                                                mMockIkeSessionStateMachine));
                                createLatch.countDown();
                                Log.d("IkeSocketTest", "IkeSocket created.");
                            } catch (ErrnoException e) {
                                Log.e("IkeSocketTest", "error encountered creating IkeSocket ", e);
                            }
                        });
        createLatch.await();

        IkeSocket ikeSocket = socketReceiver.getIkeSocket();
        assertNotNull(ikeSocket);

        // Configure IkeSocket
        TestCountDownLatch receiveLatch = new TestCountDownLatch();
        DummyPacketReceiver packetReceiver = new DummyPacketReceiver(receiveLatch);
        IkeSocket.setPacketReceiver(packetReceiver);

        // Send first packet.
        sendToIkeSocket(mDummyRemoteServerFd, mDataOne, mLocalAddress);
        receiveLatch.await();

        assertEquals(1, ikeSocket.numPacketsReceived());
        assertArrayEquals(mDataOne, packetReceiver.mReceivedData);

        // Send second packet.
        sendToIkeSocket(mDummyRemoteServerFd, mDataTwo, mLocalAddress);
        receiveLatch.await();

        assertEquals(2, ikeSocket.numPacketsReceived());
        assertArrayEquals(mDataTwo, packetReceiver.mReceivedData);

        // Close IkeSocket.
        TestCountDownLatch closeLatch = new TestCountDownLatch();
        ikeSocket
                .getHandler()
                .post(
                        () -> {
                            ikeSocket.releaseReference(mMockIkeSessionStateMachine);
                            closeLatch.countDown();
                        });
        closeLatch.await();

        mIkeThread.quitSafely();
    }

    @Test
    public void testHandlePacket() throws Exception {
        byte[] recvBuf =
                TestUtils.hexStringToByteArray(
                        NON_ESP_MARKER_HEX_STRING + IKE_REQ_MESSAGE_HEX_STRING);

        mPacketReceiver.handlePacket(recvBuf, mSpiToIkeStateMachineMap);

        byte[] expectedIkePacketBytes = TestUtils.hexStringToByteArray(IKE_REQ_MESSAGE_HEX_STRING);
        ArgumentCaptor<IkeHeader> ikeHeaderCaptor = ArgumentCaptor.forClass(IkeHeader.class);
        verify(mMockIkeSessionStateMachine)
                .receiveIkePacket(ikeHeaderCaptor.capture(), eq(expectedIkePacketBytes));

        IkeHeader capturedIkeHeader = ikeHeaderCaptor.getValue();
        assertEquals(mRemoteSpi, capturedIkeHeader.ikeInitiatorSpi);
        assertEquals(mLocalSpi, capturedIkeHeader.ikeResponderSpi);
    }

    @Test
    public void testHandleEspPacket() throws Exception {
        byte[] recvBuf =
                TestUtils.hexStringToByteArray(
                        NON_ESP_MARKER_HEX_STRING + IKE_REQ_MESSAGE_HEX_STRING);
        // Modify Non-ESP Marker
        recvBuf[0] = 1;

        mPacketReceiver.handlePacket(recvBuf, mSpiToIkeStateMachineMap);

        verify(mMockIkeSessionStateMachine, never()).receiveIkePacket(any(), any());
    }

    @Test
    public void testHandlePacketWithMalformedHeader() throws Exception {
        String malformedIkePacketHexString = "5f54bf6d8b48e6e100000000000000002120220800000000";
        byte[] recvBuf =
                TestUtils.hexStringToByteArray(
                        NON_ESP_MARKER_HEX_STRING + malformedIkePacketHexString);

        mPacketReceiver.handlePacket(recvBuf, mSpiToIkeStateMachineMap);

        verify(mMockIkeSessionStateMachine, never()).receiveIkePacket(any(), any());
    }

    private byte[] receive(FileDescriptor mfd) throws Exception {
        byte[] receiveBuffer = new byte[REMOTE_RECV_BUFF_SIZE];
        AtomicInteger bytesRead = new AtomicInteger(-1);
        Thread receiveThread =
                new Thread(
                        () -> {
                            while (bytesRead.get() < 0) {
                                try {
                                    bytesRead.set(
                                            Os.recvfrom(
                                                    mDummyRemoteServerFd,
                                                    receiveBuffer,
                                                    0,
                                                    REMOTE_RECV_BUFF_SIZE,
                                                    0,
                                                    null));
                                } catch (Exception e) {
                                    Log.e(
                                            "IkeSocketTest",
                                            "Error encountered reading from socket",
                                            e);
                                }
                            }
                            Log.d(
                                    "IkeSocketTest",
                                    "Packet received with size of " + bytesRead.get());
                        });

        receiveThread.start();
        receiveThread.join(TIMEOUT);

        return Arrays.copyOfRange(receiveBuffer, 0, bytesRead.get());
    }

    private void sendToIkeSocket(FileDescriptor fd, byte[] data, InetAddress destAddress)
            throws Exception {
        Os.sendto(fd, data, 0, data.length, 0, destAddress, mClientUdpEncapSocket.getPort());
    }

    private static class IkeSocketReceiver {
        private IkeSocket mIkeSocket;

        void setIkeSocket(IkeSocket ikeSocket) {
            mIkeSocket = ikeSocket;
        }

        IkeSocket getIkeSocket() {
            return mIkeSocket;
        }
    }

    private static class DummyPacketReceiver implements IkeSocket.IPacketReceiver {
        byte[] mReceivedData = null;
        final TestCountDownLatch mLatch;

        DummyPacketReceiver(TestCountDownLatch latch) {
            mLatch = latch;
        }

        public void handlePacket(
                byte[] revbuf, LongSparseArray<IkeSessionStateMachine> spiToIkeSession) {
            mReceivedData = Arrays.copyOfRange(revbuf, 0, revbuf.length);
            mLatch.countDown();
            Log.d("IkeSocketTest", "Packet received");
        }
    }

    private static class TestCountDownLatch {
        private CountDownLatch mLatch;

        TestCountDownLatch() {
            reset();
        }

        private void reset() {
            mLatch = new CountDownLatch(1);
        }

        void countDown() {
            mLatch.countDown();
        }

        void await() {
            try {
                if (!mLatch.await(TIMEOUT, TimeUnit.MILLISECONDS)) {
                    fail("Time out");
                }
            } catch (InterruptedException e) {
                fail(e.toString());
            }
            reset();
        }
    }
}