summaryrefslogtreecommitdiffstats
path: root/tests/wifitests/src/com/android/server/wifi/hotspot2/OsuServerConnectionTest.java
blob: 843caf1a91915268fcde65dd90f5f41f7c8cae34 (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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/*
 * Copyright 2018 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.server.wifi.hotspot2;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.net.Network;
import android.os.test.TestLooper;
import android.util.Pair;

import androidx.test.filters.SmallTest;

import com.android.dx.mockito.inline.extended.ExtendedMockito;
import com.android.org.conscrypt.TrustManagerImpl;
import com.android.server.wifi.hotspot2.soap.HttpsServiceConnection;
import com.android.server.wifi.hotspot2.soap.HttpsTransport;
import com.android.server.wifi.hotspot2.soap.SoapParser;
import com.android.server.wifi.hotspot2.soap.SppResponseMessage;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Unit tests for {@link OsuServerConnection}.
 */
@SmallTest
public class OsuServerConnectionTest {
    private static final String TEST_VALID_URL = "https://www.google.com";
    private static final String TEST_INVALID_URL = "http://www.google.com";
    private static final String AUTH_TYPE = "ECDHE_RSA";
    private static final String PROVIDER_NAME_VALID = "Boingo";
    private static final String PROVIDER_NAME_INVALID = "Boingo1";
    private static final int ENABLE_VERBOSE_LOGGING = 1;
    private static final int TEST_SESSION_ID = 1;

    private TestLooper mLooper = new TestLooper();
    private OsuServerConnection mOsuServerConnection;
    private URL mServerUrl;
    private List<Pair<Locale, String>> mProviderIdentities = new ArrayList<>();
    private ArgumentCaptor<TrustManager[]> mTrustManagerCaptor =
            ArgumentCaptor.forClass(TrustManager[].class);
    private Map<Integer, Map<String, byte[]>> mTrustCertsInfo = new HashMap<>();

    @Mock PasspointProvisioner.OsuServerCallbacks mOsuServerCallbacks;
    @Mock Network mNetwork;
    @Mock HttpsURLConnection mUrlConnection;
    @Mock WfaKeyStore mWfaKeyStore;
    @Mock SSLContext mTlsContext;
    @Mock KeyStore mKeyStore;
    @Mock TrustManagerImpl mDelegate;
    @Mock HttpsTransport mHttpsTransport;
    @Mock HttpsServiceConnection mHttpsServiceConnection;
    @Mock SppResponseMessage mSppResponseMessage;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mOsuServerConnection = new OsuServerConnection(mLooper.getLooper());
        mOsuServerConnection.enableVerboseLogging(ENABLE_VERBOSE_LOGGING);
        mProviderIdentities.add(Pair.create(Locale.US, PROVIDER_NAME_VALID));
        mServerUrl = new URL(TEST_VALID_URL);
        when(mWfaKeyStore.get()).thenReturn(mKeyStore);
        when(mOsuServerCallbacks.getSessionId()).thenReturn(TEST_SESSION_ID);
        when(mNetwork.openConnection(any(URL.class))).thenReturn(mUrlConnection);
        when(mHttpsTransport.getServiceConnection()).thenReturn(mHttpsServiceConnection);
        when(mDelegate.getTrustedChainForServer(any(X509Certificate[].class), anyString(),
                (Socket) isNull()))
                .thenReturn(PasspointProvisioningTestUtil.getOsuCertsForTest());
    }

    /**
     * Verifies initialization and connecting to the OSU server
     */
    @Test
    public void verifyInitAndConnect() throws Exception {
        // static mocking
        MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
                ServiceProviderVerifier.class).startMocking();
        try {
            when(ServiceProviderVerifier.getProviderNames(any(X509Certificate.class))).thenReturn(
                    mProviderIdentities);

            establishServerConnection();

            TrustManager[] trustManagers = mTrustManagerCaptor.getValue();
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

            trustManager.checkServerTrusted(new X509Certificate[1], AUTH_TYPE);

            verify(mOsuServerCallbacks).onServerValidationStatus(anyInt(), eq(true));
            assertTrue(mOsuServerConnection.validateProvider(Locale.US, PROVIDER_NAME_VALID));
        } finally {
            session.finishMocking();
        }
    }

    /**
     * Verifies initialization of the HTTPS connection with invalid TLSContext
     */
    @Test
    public void verifyInvalidTlsContext() {
        mOsuServerConnection.init(null, mDelegate);
        mOsuServerConnection.setEventCallback(mOsuServerCallbacks);

        assertFalse(mOsuServerConnection.canValidateServer());
    }

    /**
     * Verifies initialization of the HTTPS connection when TlsContext init fails
     */
    @Test
    public void verifyTlsContextInitFailure() throws Exception {
        doThrow(new KeyManagementException()).when(mTlsContext).init(any(), any(), any());

        mOsuServerConnection.init(mTlsContext, mDelegate);
        mOsuServerConnection.setEventCallback(mOsuServerCallbacks);

        assertFalse(mOsuServerConnection.canValidateServer());
    }

    /**
     * Verifies initialization and opening URL connection failed on the network
     */
    @Test
    public void verifyInitAndNetworkOpenURLConnectionFailed() throws Exception {
        doThrow(new IOException()).when(mNetwork).openConnection(any(URL.class));

        mOsuServerConnection.init(mTlsContext, mDelegate);
        mOsuServerConnection.setEventCallback(mOsuServerCallbacks);

        assertTrue(mOsuServerConnection.canValidateServer());
        assertTrue(mOsuServerConnection.connect(mServerUrl, mNetwork));

        mLooper.dispatchAll();

        verify(mOsuServerCallbacks).onServerConnectionStatus(anyInt(), eq(false));
    }

    /**
     * Verifies initialization and connection failure to OSU server
     */
    @Test
    public void verifyInitAndServerConnectFailure() throws Exception {
        doThrow(new IOException()).when(mUrlConnection).connect();

        mOsuServerConnection.init(mTlsContext, mDelegate);
        mOsuServerConnection.setEventCallback(mOsuServerCallbacks);

        assertTrue(mOsuServerConnection.canValidateServer());
        assertTrue(mOsuServerConnection.connect(mServerUrl, mNetwork));

        mLooper.dispatchAll();

        verify(mOsuServerCallbacks).onServerConnectionStatus(anyInt(), eq(false));
    }

    /**
     * Verifies initialization and connecting to the OSU server, cert validation failure
     */
    @Test
    public void verifyInitAndConnectCertValidationFailure() throws Exception {
        establishServerConnection();
        List<X509Certificate> certificateList = PasspointProvisioningTestUtil.getOsuCertsForTest();
        X509Certificate[] certificates = new X509Certificate[1];
        certificates[0] = certificateList.get(0);
        TrustManager[] trustManagers = mTrustManagerCaptor.getValue();
        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
        doThrow(new CertificateException()).when(mDelegate)
                .getTrustedChainForServer(any(X509Certificate[].class), anyString(),
                        (Socket) isNull());

        trustManager.checkServerTrusted(certificates, AUTH_TYPE);

        verify(mOsuServerCallbacks).onServerValidationStatus(anyInt(), eq(false));
    }

    /**
     * Verifies initialization and connecting to the OSU server, friendly name mismatch
     */
    @Test
    public void verifyInitAndConnectInvalidProviderIdentity()throws Exception  {
        // static mocking
        MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
                ServiceProviderVerifier.class).startMocking();
        try {
            when(ServiceProviderVerifier.getProviderNames(any(X509Certificate.class))).thenReturn(
                    mProviderIdentities);

            establishServerConnection();

            TrustManager[] trustManagers = mTrustManagerCaptor.getValue();
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

            trustManager.checkServerTrusted(new X509Certificate[1], AUTH_TYPE);

            verify(mOsuServerCallbacks).onServerValidationStatus(anyInt(), eq(true));
            assertFalse(mOsuServerConnection.validateProvider(Locale.US, PROVIDER_NAME_INVALID));
        } finally {
            session.finishMocking();
        }
    }

    /**
     * Verifies {@code ExchangeSoapMessage} should return {@code false} if there is no connection.
     */
    @Test
    public void verifyExchangeSoapMessageWithoutConnection() {
        assertFalse(mOsuServerConnection.exchangeSoapMessage(
                new SoapSerializationEnvelope(SoapEnvelope.VER12)));
    }

    /**
     * Verifies {@code ExchangeSoapMessage} should return {@code false} if {@code soapEnvelope} is
     * {@code null}
     */
    @Test
    public void verifyExchangeSoapMessageWithInvalidArgument() throws Exception {
        establishServerConnection();
        assertFalse(mOsuServerConnection.exchangeSoapMessage(null));
    }

    /**
     * Verifies {@code ExchangeSoapMessage} should get {@code null} message if exception occurs
     * during soap exchange.
     */
    @Test
    public void verifyExchangeSoapMessageWithException() throws Exception {
        // static mocking
        MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
                HttpsTransport.class).startMocking();
        try {
            establishServerConnection();
            when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(
                    mHttpsTransport);
            doThrow(new IOException()).when(mHttpsTransport).call(any(String.class),
                    any(SoapSerializationEnvelope.class));

            assertTrue(mOsuServerConnection.exchangeSoapMessage(
                    new SoapSerializationEnvelope(SoapEnvelope.VER12)));

            mLooper.dispatchAll();

            verify(mOsuServerCallbacks).onReceivedSoapMessage(anyInt(), isNull());
        } finally {
            session.finishMocking();
        }
    }

    /**
     * Verifies {@code ExchangeSoapMessage} should return an instance of {@link SppResponseMessage}.
     */
    @Test
    public void verifyExchangeSoapMessage() throws Exception {
        // static mocking
        MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
                HttpsTransport.class).mockStatic(SoapParser.class).startMocking();
        try {
            establishServerConnection();

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
            envelope.bodyIn = new SoapObject();
            when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(
                    mHttpsTransport);
            when(SoapParser.getResponse(any(SoapObject.class))).thenReturn(mSppResponseMessage);

            assertTrue(mOsuServerConnection.exchangeSoapMessage(envelope));

            mLooper.dispatchAll();

            verify(mOsuServerCallbacks).onReceivedSoapMessage(anyInt(), eq(mSppResponseMessage));
        } finally {
            session.finishMocking();
        }
    }

    /**
     * Verifies {@code retrieveTrustRootCerts} should return {@code false} if there is no
     * connection.
     */
    @Test
    public void verifyRetrieveTrustRootCertsWithoutConnection() {
        assertFalse(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));
    }

    /**
     * Verifies {@code retrieveTrustRootCerts} should return {@code false} if {@code
     * mTrustCertsInfo} is empty.
     */
    @Test
    public void verifyRetrieveTrustRootCertsWithEmptyOfTrustCertsInfo() {
        mOsuServerConnection.init(mTlsContext, mDelegate);
        mOsuServerConnection.setEventCallback(mOsuServerCallbacks);
        assertFalse(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));
    }

    /**
     * Verifies it should return an empty collection of CA certificates if HTTPS response from
     * server to get root CA certificate is not HTTP OK.
     */
    @Test
    public void verifyRetrieveTrustRootCertsWithErrorInHTTPSResponse() throws Exception {
        // static mocking
        MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
                HttpsTransport.class).startMocking();
        try {
            when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(
                    mHttpsTransport);
            when(mHttpsServiceConnection.getResponseCode()).thenReturn(
                    HttpURLConnection.HTTP_NO_CONTENT);
            ArgumentCaptor<Map<Integer, List<X509Certificate>>> argumentCaptor =
                    ArgumentCaptor.forClass(Map.class);

            // Test Data
            Map<String, byte[]> certInfo = new HashMap<>();
            certInfo.put("https://test.com/trustroot", "testData".getBytes());
            certInfo.put("https://test2.com/trustroot", "testData2".getBytes());
            mTrustCertsInfo.put(OsuServerConnection.TRUST_CERT_TYPE_AAA, certInfo);

            establishServerConnection();

            assertTrue(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));

            mLooper.dispatchAll();

            verify(mOsuServerCallbacks).onReceivedTrustRootCertificates(anyInt(),
                    argumentCaptor.capture());
            assertTrue(argumentCaptor.getValue().isEmpty());
        } finally {
            session.finishMocking();
        }
    }

    /**
     * Verifies it should return a collection of CA certificates if there is no error while
     * downloading root CA certificate from each {@code URL} provided
     */
    @Test
    public void verifyRetrieveTrustRootCertsWithoutError() throws Exception {
        // static mocking
        MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
                HttpsTransport.class).mockStatic(CertificateFactory.class).mockStatic(
                ServiceProviderVerifier.class).startMocking();
        try {
            X509Certificate certificate = Mockito.mock(X509Certificate.class);
            InputStream inputStream = Mockito.mock(InputStream.class);

            // To avoid infinite loop in OsuServerConnection.getCert.
            when(inputStream.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1);

            CertificateFactory certificateFactory = Mockito.mock(CertificateFactory.class);
            when(certificateFactory.generateCertificate(any(InputStream.class))).thenReturn(
                    certificate);
            when(CertificateFactory.getInstance(anyString())).thenReturn(certificateFactory);
            when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(
                    mHttpsTransport);
            when(mHttpsServiceConnection.getResponseCode()).thenReturn(
                    HttpURLConnection.HTTP_OK);
            when(mHttpsServiceConnection.openInputStream()).thenReturn(inputStream);
            ArgumentCaptor<Map<Integer, List<X509Certificate>>> argumentCaptor =
                    ArgumentCaptor.forClass(Map.class);
            when(ServiceProviderVerifier.verifyCertFingerprint(any(X509Certificate.class),
                    any(byte[].class))).thenReturn(true);

            // Test Data
            Map<String, byte[]> certInfo = new HashMap<>();
            certInfo.put("https://test.com/trustroot", "testData".getBytes());
            mTrustCertsInfo.put(OsuServerConnection.TRUST_CERT_TYPE_AAA, certInfo);

            List<HeaderProperty> properties = new ArrayList<>();

            // Indicates that X.509 CA certificate is included.
            properties.add(new HeaderProperty("Content-Type", "application/x-x509-ca-cert"));
            when(mHttpsServiceConnection.getResponseProperties()).thenReturn(properties);

            establishServerConnection();

            assertTrue(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));

            mLooper.dispatchAll();

            verify(mOsuServerCallbacks).onReceivedTrustRootCertificates(anyInt(),
                    argumentCaptor.capture());
            Assert.assertEquals(1, argumentCaptor.getValue().size());
            Assert.assertEquals(certificate,
                    argumentCaptor.getValue().get(OsuServerConnection.TRUST_CERT_TYPE_AAA).get(0));
        } finally {
            session.finishMocking();
        }
    }

    /**
     * Verifies that cleanup is properly called on the OsuServerHandlerThread.
     */
    @Test
    public void verifyCleanup() throws Exception {
        // static mocking
        MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(
                HttpsTransport.class).mockStatic(SoapParser.class).startMocking();
        try {
            establishServerConnection();

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
            envelope.bodyIn = new SoapObject();
            when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(
                    mHttpsTransport);
            when(SoapParser.getResponse(any(SoapObject.class))).thenReturn(mSppResponseMessage);

            assertTrue(mOsuServerConnection.exchangeSoapMessage(envelope));

            mLooper.dispatchAll();

            verify(mHttpsServiceConnection).disconnect();
            reset(mHttpsServiceConnection);

            mOsuServerConnection.cleanup();
            mLooper.dispatchAll();

            verify(mUrlConnection).disconnect();
            verify(mHttpsServiceConnection, never()).disconnect();
        } finally {
            session.finishMocking();
        }
    }

    /**
     * Verifies initialization and opening URL connection failure for an HTTP URL (not HTTPS)
     */
    @Test
    public void verifyInitAndNetworkOpenURLConnectionFailedWithHttpUrl() throws Exception {
        mServerUrl = new URL(TEST_INVALID_URL);
        mOsuServerConnection.init(mTlsContext, mDelegate);
        mOsuServerConnection.setEventCallback(mOsuServerCallbacks);

        assertTrue(mOsuServerConnection.canValidateServer());
        assertFalse(mOsuServerConnection.connect(mServerUrl, mNetwork));
    }

    private void establishServerConnection() throws Exception {
        mOsuServerConnection.init(mTlsContext, mDelegate);
        mOsuServerConnection.setEventCallback(mOsuServerCallbacks);
        verify(mTlsContext).init(isNull(), mTrustManagerCaptor.capture(), isNull());

        assertTrue(mOsuServerConnection.canValidateServer());
        assertTrue(mOsuServerConnection.connect(mServerUrl, mNetwork));
        mLooper.dispatchAll();

        verify(mOsuServerCallbacks).onServerConnectionStatus(anyInt(), eq(true));
    }
}