1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.wifi;
18 
19 import static org.junit.Assert.*;
20 
21 import android.net.IpConfiguration;
22 import android.net.LinkAddress;
23 import android.net.NetworkUtils;
24 import android.net.ProxyInfo;
25 import android.net.StaticIpConfiguration;
26 import android.net.wifi.WifiConfiguration;
27 import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
28 import android.net.wifi.WifiEnterpriseConfig;
29 import android.net.wifi.WifiSsid;
30 import android.text.TextUtils;
31 
32 import java.net.InetAddress;
33 import java.security.cert.X509Certificate;
34 import java.util.Arrays;
35 import java.util.List;
36 
37 /**
38  * Helper for creating and populating WifiConfigurations in unit tests.
39  */
40 public class WifiConfigurationTestUtil {
41     /**
42      * These values are used to describe AP's security setting. One AP can support multiple of them,
43      * only if there is no conflict.
44      */
45     public static final int SECURITY_NONE = 0;
46     public static final int SECURITY_WEP =  1 << 0;
47     public static final int SECURITY_PSK =  1 << 1;
48     public static final int SECURITY_EAP =  1 << 2;
49     public static final int SECURITY_SAE =  1 << 3;
50     public static final int SECURITY_OWE =  1 << 4;
51     public static final int SECURITY_EAP_SUITE_B =  1 << 5;
52 
53     /**
54      * These values are used to describe ip configuration parameters for a network.
55      */
56     public static final int STATIC_IP_ASSIGNMENT = 0;
57     public static final int DHCP_IP_ASSIGNMENT = 1;
58     public static final int STATIC_PROXY_SETTING = 0;
59     public static final int PAC_PROXY_SETTING = 1;
60     public static final int NONE_PROXY_SETTING = 2;
61 
62     /**
63      * These are constants used to generate predefined WifiConfiguration objects.
64      */
65     public static final int TEST_NETWORK_ID = -1;
66     public static final int TEST_UID = 5;
67     public static final String TEST_SSID = "WifiConfigurationTestSSID";
68     public static final String TEST_PSK = "\"WifiConfigurationTestUtilPsk\"";
69     public static final String[] TEST_WEP_KEYS =
70             {"\"WifiConfigurationTestUtilWep1\"", "\"WifiConfigurationTestUtilWep2\"",
71                     "45342312ab", "45342312ab45342312ab34ac12"};
72     public static final String TEST_EAP_PASSWORD = "WifiConfigurationTestUtilEapPassword";
73     public static final int TEST_WEP_TX_KEY_INDEX = 1;
74     public static final String TEST_FQDN = "WifiConfigurationTestUtilFQDN";
75     public static final String TEST_PROVIDER_FRIENDLY_NAME =
76             "WifiConfigurationTestUtilFriendlyName";
77     public static final String TEST_STATIC_IP_LINK_ADDRESS = "192.168.48.2";
78     public static final int TEST_STATIC_IP_LINK_PREFIX_LENGTH = 8;
79     public static final String TEST_STATIC_IP_GATEWAY_ADDRESS = "192.168.48.1";
80     public static final String[] TEST_STATIC_IP_DNS_SERVER_ADDRESSES =
81             new String[]{"192.168.48.1", "192.168.48.10"};
82     public static final String TEST_STATIC_PROXY_HOST = "192.168.48.1";
83     public static final int TEST_STATIC_PROXY_PORT = 8000;
84     public static final String TEST_STATIC_PROXY_EXCLUSION_LIST = "";
85     public static final String TEST_PAC_PROXY_LOCATION = "http://";
86     public static final String TEST_CA_CERT_ALIAS = "WifiConfigurationTestUtilCaCertAlias";
87 
88     private static final int MAX_SSID_LENGTH = 32;
89     /**
90      * Index used to assign unique SSIDs for the generation of predefined WifiConfiguration objects.
91      */
92     private static int sNetworkIndex = 0;
93 
94     /**
95      * Construct a {@link android.net.wifi.WifiConfiguration}.
96      * @param networkId the configuration's networkId
97      * @param uid the configuration's creator uid
98      * @param ssid the configuration's ssid
99      * @param shared whether the configuration is shared with other users on the device
100      * @param enabled whether the configuration is enabled
101      * @param fqdn the configuration's FQDN (Hotspot 2.0 only)
102      * @param providerFriendlyName the configuration's provider's friendly name (Hotspot 2.0 only)
103      * @return the constructed {@link android.net.wifi.WifiConfiguration}
104      */
generateWifiConfig(int networkId, int uid, String ssid, boolean shared, boolean enabled, String fqdn, String providerFriendlyName)105     public static WifiConfiguration generateWifiConfig(int networkId, int uid, String ssid,
106             boolean shared, boolean enabled, String fqdn, String providerFriendlyName) {
107         final WifiConfiguration config = new WifiConfiguration();
108         config.SSID = ssid;
109         config.networkId = networkId;
110         config.creatorUid = uid;
111         config.shared = shared;
112         config.status = enabled ? WifiConfiguration.Status.ENABLED
113                 : WifiConfiguration.Status.DISABLED;
114         config.FQDN = fqdn;
115         config.providerFriendlyName = providerFriendlyName;
116         return config;
117     }
118 
119     /**
120      * Construct a {@link android.net.wifi.WifiConfiguration}.
121      * @param networkId the configuration's networkId
122      * @param uid the configuration's creator uid
123      * @param ssid the configuration's ssid
124      * @param shared whether the configuration is shared with other users on the device
125      * @param enabled whether the configuration is enabled
126      * @param fqdn the configuration's FQDN (Hotspot 2.0 only)
127      * @param providerFriendlyName the configuration's provider's friendly name (Hotspot 2.0 only)
128      * @param security the configuration's security type
129      * @return the constructed {@link android.net.wifi.WifiConfiguration}
130      */
generateWifiConfig(int networkId, int uid, String ssid, boolean shared, boolean enabled, String fqdn, String providerFriendlyName, int security)131     public static WifiConfiguration generateWifiConfig(int networkId, int uid, String ssid,
132             boolean shared, boolean enabled, String fqdn, String providerFriendlyName,
133             int security) {
134         WifiConfiguration config = generateWifiConfig(networkId, uid, ssid, shared, enabled, fqdn,
135                 providerFriendlyName);
136 
137         if ((security == SECURITY_NONE) || ((security & SECURITY_WEP) != 0)) {
138             config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
139         } else {
140             if ((security & SECURITY_PSK) != 0) {
141                 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
142             }
143 
144             if ((security & SECURITY_SAE) != 0) {
145                 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
146                 config.requirePMF = true;
147             }
148 
149             if ((security & SECURITY_OWE) != 0) {
150                 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
151                 config.requirePMF = true;
152             }
153 
154             if ((security & SECURITY_EAP) != 0) {
155                 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
156                 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
157                 config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TTLS);
158             }
159 
160             if ((security & SECURITY_EAP_SUITE_B) != 0) {
161                 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
162                 config.requirePMF = true;
163             }
164 
165         }
166         return config;
167     }
168 
169     /**
170      * Construct a {@link android.net.IpConfiguration }.
171      * @param ipAssignmentType One of {@link #STATIC_IP_ASSIGNMENT} or {@link #DHCP_IP_ASSIGNMENT}.
172      * @param proxySettingType One of {@link #STATIC_PROXY_SETTING} or {@link #PAC_PROXY_SETTING} or
173      *                        {@link #NONE_PROXY_SETTING}.
174      * @param linkAddress static ip address string.
175      * @param linkPrefixLength static ip address prefix length.
176      * @param gatewayAddress static gateway address.
177      * @param dnsServerAddresses list of dns servers for static ip configuration.
178      * @param proxyHost Static proxy server address.
179      * @param proxyPort Static proxy server port.
180      * @param proxyExclusionList Static proxy exclusion list.
181      * @param pacProxyPath Pac proxy server path.
182      * @return the constructed {@link android.net.IpConfiguration}
183      */
generateIpConfig( int ipAssignmentType, int proxySettingType, String linkAddress, int linkPrefixLength, String gatewayAddress, String[] dnsServerAddresses, String proxyHost, int proxyPort, String proxyExclusionList, String pacProxyPath)184     public static IpConfiguration generateIpConfig(
185             int ipAssignmentType, int proxySettingType, String linkAddress, int linkPrefixLength,
186             String gatewayAddress, String[] dnsServerAddresses, String proxyHost,
187             int proxyPort, String proxyExclusionList, String pacProxyPath) {
188         StaticIpConfiguration staticIpConfiguration = null;
189         ProxyInfo proxyInfo = null;
190         IpConfiguration.IpAssignment ipAssignment = IpConfiguration.IpAssignment.UNASSIGNED;
191         IpConfiguration.ProxySettings proxySettings = IpConfiguration.ProxySettings.UNASSIGNED;
192 
193         if (ipAssignmentType == STATIC_IP_ASSIGNMENT) {
194             staticIpConfiguration = new StaticIpConfiguration();
195             if (!TextUtils.isEmpty(linkAddress)) {
196                 LinkAddress linkAddr =
197                         new LinkAddress(
198                                 NetworkUtils.numericToInetAddress(linkAddress), linkPrefixLength);
199                 staticIpConfiguration.ipAddress = linkAddr;
200             }
201 
202             if (!TextUtils.isEmpty(gatewayAddress)) {
203                 InetAddress gatewayAddr =
204                         NetworkUtils.numericToInetAddress(gatewayAddress);
205                 staticIpConfiguration.gateway = gatewayAddr;
206             }
207             if (dnsServerAddresses != null) {
208                 for (String dnsServerAddress : dnsServerAddresses) {
209                     if (!TextUtils.isEmpty(dnsServerAddress)) {
210                         staticIpConfiguration.dnsServers.add(
211                                 NetworkUtils.numericToInetAddress(dnsServerAddress));
212                     }
213 
214                 }
215             }
216             ipAssignment = IpConfiguration.IpAssignment.STATIC;
217         } else if (ipAssignmentType == DHCP_IP_ASSIGNMENT) {
218             ipAssignment = IpConfiguration.IpAssignment.DHCP;
219         }
220 
221         if (proxySettingType == STATIC_PROXY_SETTING) {
222             proxyInfo = new ProxyInfo(proxyHost, proxyPort, proxyExclusionList);
223             proxySettings = IpConfiguration.ProxySettings.STATIC;
224         } else if (proxySettingType == PAC_PROXY_SETTING) {
225             proxyInfo = new ProxyInfo(pacProxyPath);
226             proxySettings = IpConfiguration.ProxySettings.PAC;
227         } else if (proxySettingType == NONE_PROXY_SETTING) {
228             proxySettings = IpConfiguration.ProxySettings.NONE;
229         }
230         return new IpConfiguration(ipAssignment, proxySettings, staticIpConfiguration, proxyInfo);
231     }
232 
233     /**
234      * Create a new SSID for the the network being created.
235      */
createNewSSID()236     private static String createNewSSID() {
237         String ssid = TEST_SSID + sNetworkIndex++;
238         assertTrue(ssid.length() <= MAX_SSID_LENGTH);
239         return "\"" + ssid + "\"";
240     }
241 
242     /**
243      * Helper methods to generate predefined WifiConfiguration objects of the required type. These
244      * use a static index to avoid duplicate configurations.
245      */
createOweNetwork()246     public static WifiConfiguration createOweNetwork() {
247         return createOweNetwork(createNewSSID());
248     }
249 
createOweNetwork(String ssid)250     public static WifiConfiguration createOweNetwork(String ssid) {
251         return generateWifiConfig(TEST_NETWORK_ID, TEST_UID, ssid, true, true, null,
252                 null, SECURITY_OWE);
253     }
254 
createOpenNetwork()255     public static WifiConfiguration createOpenNetwork() {
256         return createOpenNetwork(createNewSSID());
257     }
258 
createOpenNetwork(String ssid)259     public static WifiConfiguration createOpenNetwork(String ssid) {
260         return generateWifiConfig(TEST_NETWORK_ID, TEST_UID, ssid, true, true, null,
261                 null, SECURITY_NONE);
262     }
263 
createEphemeralNetwork()264     public static WifiConfiguration createEphemeralNetwork() {
265         WifiConfiguration configuration = createOpenNetwork();
266         configuration.ephemeral = true;
267         return configuration;
268     }
269 
createOpenHiddenNetwork()270     public static WifiConfiguration createOpenHiddenNetwork() {
271         WifiConfiguration configuration = createOpenNetwork();
272         configuration.hiddenSSID = true;
273         return configuration;
274     }
275 
createSaeNetwork()276     public static WifiConfiguration createSaeNetwork() {
277         WifiConfiguration configuration =
278                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true, null,
279                         null, SECURITY_SAE);
280 
281         // SAE password uses the same member.
282         configuration.preSharedKey = TEST_PSK;
283         configuration.requirePMF = true;
284         return configuration;
285     }
286 
createPskNetwork()287     public static WifiConfiguration createPskNetwork() {
288         WifiConfiguration configuration =
289                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true, null,
290                         null, SECURITY_PSK);
291         configuration.preSharedKey = TEST_PSK;
292         return configuration;
293     }
294 
createPskNetwork(String ssid)295     public static WifiConfiguration createPskNetwork(String ssid) {
296         WifiConfiguration configuration =
297                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, ssid, true, true, null,
298                         null, SECURITY_PSK);
299         configuration.preSharedKey = TEST_PSK;
300         return configuration;
301     }
302 
createSaeNetwork(String ssid)303     public static WifiConfiguration createSaeNetwork(String ssid) {
304         WifiConfiguration configuration =
305                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, ssid, true, true, null,
306                         null, SECURITY_SAE);
307         return configuration;
308     }
309 
createPskHiddenNetwork()310     public static WifiConfiguration createPskHiddenNetwork() {
311         WifiConfiguration configuration = createPskNetwork();
312         configuration.hiddenSSID = true;
313         return configuration;
314     }
315 
createWepNetwork()316     public static WifiConfiguration createWepNetwork() {
317         WifiConfiguration configuration =
318                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true, null,
319                         null, SECURITY_WEP);
320         configuration.wepKeys = TEST_WEP_KEYS;
321         configuration.wepTxKeyIndex = TEST_WEP_TX_KEY_INDEX;
322         return configuration;
323     }
324 
createWepHiddenNetwork()325     public static WifiConfiguration createWepHiddenNetwork() {
326         WifiConfiguration configuration = createWepNetwork();
327         configuration.hiddenSSID = true;
328         return configuration;
329     }
330 
createWepNetworkWithSingleKey()331     public static WifiConfiguration createWepNetworkWithSingleKey() {
332         WifiConfiguration configuration =
333                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true, null,
334                         null, SECURITY_WEP);
335         configuration.wepKeys[0] = TEST_WEP_KEYS[0];
336         configuration.wepTxKeyIndex = 0;
337         return configuration;
338     }
339 
340 
createEapNetwork()341     public static WifiConfiguration createEapNetwork() {
342         WifiConfiguration configuration =
343                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true,
344                         null, null, SECURITY_EAP);
345         return configuration;
346     }
347 
createEapNetwork(String ssid)348     public static WifiConfiguration createEapNetwork(String ssid) {
349         WifiConfiguration configuration =
350                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, ssid, true, true,
351                         null, null, SECURITY_EAP);
352         return configuration;
353     }
354 
355 
createEapNetwork(int eapMethod, int phase2Method)356     public static WifiConfiguration createEapNetwork(int eapMethod, int phase2Method) {
357         WifiConfiguration configuration =
358                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true,
359                         null, null, SECURITY_EAP);
360         configuration.enterpriseConfig.setEapMethod(eapMethod);
361         configuration.enterpriseConfig.setPhase2Method(phase2Method);
362         return configuration;
363     }
364 
createEapSuiteBNetwork()365     public static WifiConfiguration createEapSuiteBNetwork() {
366         WifiConfiguration configuration =
367                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true,
368                         null, null, SECURITY_EAP_SUITE_B);
369 
370         configuration.requirePMF = true;
371         configuration.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
372         configuration.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE);
373         return configuration;
374     }
375 
createPasspointNetwork()376     public static WifiConfiguration createPasspointNetwork() {
377         WifiConfiguration configuration =
378                 generateWifiConfig(TEST_NETWORK_ID, TEST_UID, createNewSSID(), true, true,
379                         TEST_FQDN, TEST_PROVIDER_FRIENDLY_NAME, SECURITY_EAP);
380         return configuration;
381     }
382 
createStaticIpConfigurationWithPacProxy()383     public static IpConfiguration createStaticIpConfigurationWithPacProxy() {
384         return generateIpConfig(
385                 STATIC_IP_ASSIGNMENT, PAC_PROXY_SETTING,
386                 TEST_STATIC_IP_LINK_ADDRESS, TEST_STATIC_IP_LINK_PREFIX_LENGTH,
387                 TEST_STATIC_IP_GATEWAY_ADDRESS, TEST_STATIC_IP_DNS_SERVER_ADDRESSES,
388                 TEST_STATIC_PROXY_HOST, TEST_STATIC_PROXY_PORT, TEST_STATIC_PROXY_EXCLUSION_LIST,
389                 TEST_PAC_PROXY_LOCATION);
390     }
391 
createStaticIpConfigurationWithStaticProxy()392     public static IpConfiguration createStaticIpConfigurationWithStaticProxy() {
393         return generateIpConfig(
394                 STATIC_IP_ASSIGNMENT, STATIC_PROXY_SETTING,
395                 TEST_STATIC_IP_LINK_ADDRESS, TEST_STATIC_IP_LINK_PREFIX_LENGTH,
396                 TEST_STATIC_IP_GATEWAY_ADDRESS, TEST_STATIC_IP_DNS_SERVER_ADDRESSES,
397                 TEST_STATIC_PROXY_HOST, TEST_STATIC_PROXY_PORT, TEST_STATIC_PROXY_EXCLUSION_LIST,
398                 TEST_PAC_PROXY_LOCATION);
399     }
400 
createPartialStaticIpConfigurationWithPacProxy()401     public static IpConfiguration createPartialStaticIpConfigurationWithPacProxy() {
402         return generateIpConfig(
403                 STATIC_IP_ASSIGNMENT, PAC_PROXY_SETTING,
404                 TEST_STATIC_IP_LINK_ADDRESS, TEST_STATIC_IP_LINK_PREFIX_LENGTH,
405                 null, null,
406                 TEST_STATIC_PROXY_HOST, TEST_STATIC_PROXY_PORT, TEST_STATIC_PROXY_EXCLUSION_LIST,
407                 TEST_PAC_PROXY_LOCATION);
408     }
409 
createDHCPIpConfigurationWithPacProxy()410     public static IpConfiguration createDHCPIpConfigurationWithPacProxy() {
411         return generateIpConfig(
412                 DHCP_IP_ASSIGNMENT, PAC_PROXY_SETTING,
413                 TEST_STATIC_IP_LINK_ADDRESS, TEST_STATIC_IP_LINK_PREFIX_LENGTH,
414                 TEST_STATIC_IP_GATEWAY_ADDRESS, TEST_STATIC_IP_DNS_SERVER_ADDRESSES,
415                 TEST_STATIC_PROXY_HOST, TEST_STATIC_PROXY_PORT, TEST_STATIC_PROXY_EXCLUSION_LIST,
416                 TEST_PAC_PROXY_LOCATION);
417     }
418 
createDHCPIpConfigurationWithStaticProxy()419     public static IpConfiguration createDHCPIpConfigurationWithStaticProxy() {
420         return generateIpConfig(
421                 DHCP_IP_ASSIGNMENT, STATIC_PROXY_SETTING,
422                 TEST_STATIC_IP_LINK_ADDRESS, TEST_STATIC_IP_LINK_PREFIX_LENGTH,
423                 TEST_STATIC_IP_GATEWAY_ADDRESS, TEST_STATIC_IP_DNS_SERVER_ADDRESSES,
424                 TEST_STATIC_PROXY_HOST, TEST_STATIC_PROXY_PORT, TEST_STATIC_PROXY_EXCLUSION_LIST,
425                 TEST_PAC_PROXY_LOCATION);
426     }
427 
createDHCPIpConfigurationWithNoProxy()428     public static IpConfiguration createDHCPIpConfigurationWithNoProxy() {
429         return generateIpConfig(
430                 DHCP_IP_ASSIGNMENT, NONE_PROXY_SETTING,
431                 TEST_STATIC_IP_LINK_ADDRESS, TEST_STATIC_IP_LINK_PREFIX_LENGTH,
432                 TEST_STATIC_IP_GATEWAY_ADDRESS, TEST_STATIC_IP_DNS_SERVER_ADDRESSES,
433                 TEST_STATIC_PROXY_HOST, TEST_STATIC_PROXY_PORT, TEST_STATIC_PROXY_EXCLUSION_LIST,
434                 TEST_PAC_PROXY_LOCATION);
435     }
436 
437     /**
438      * Creates an IP configuration with specific parameters.
439      * @param proxySetting Must be one of {@link WifiConfigurationTestUtil#STATIC_PROXY_SETTING},
440      * {@link WifiConfigurationTestUtil#PAC_PROXY_SETTING},
441      * {@link WifiConfigurationTestUtil#NONE_PROXY_SETTING}
442      */
createDHCPIpConfigurationWithSpecificProxy( int proxySetting, String staticProxyHost, int staticProxyPort, String staticProxyExclusionList, String pacProxyLocation)443     public static IpConfiguration createDHCPIpConfigurationWithSpecificProxy(
444             int proxySetting,
445             String staticProxyHost,
446             int staticProxyPort,
447             String staticProxyExclusionList,
448             String pacProxyLocation) {
449         return generateIpConfig(
450                 DHCP_IP_ASSIGNMENT, proxySetting,
451                 TEST_STATIC_IP_LINK_ADDRESS, TEST_STATIC_IP_LINK_PREFIX_LENGTH,
452                 TEST_STATIC_IP_GATEWAY_ADDRESS, TEST_STATIC_IP_DNS_SERVER_ADDRESSES,
453                 staticProxyHost, staticProxyPort, staticProxyExclusionList,
454                 pacProxyLocation);
455     }
456 
457     // TODO: These enterprise configurations may need more parameters set.
createPEAPWifiEnterpriseConfigWithGTCPhase2()458     public static WifiEnterpriseConfig createPEAPWifiEnterpriseConfigWithGTCPhase2() {
459         WifiEnterpriseConfig config = new WifiEnterpriseConfig();
460         config.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
461         config.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
462         config.setCaCertificateAliases(new String[] {TEST_CA_CERT_ALIAS + "PEAP"});
463         config.setCaCertificates(new X509Certificate[] {FakeKeys.CA_CERT0, FakeKeys.CA_CERT1});
464         return config;
465     }
466 
createTLSWifiEnterpriseConfigWithNonePhase2()467     public static WifiEnterpriseConfig createTLSWifiEnterpriseConfigWithNonePhase2() {
468         WifiEnterpriseConfig config = new WifiEnterpriseConfig();
469         config.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
470         config.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE);
471         config.setCaCertificateAliases(new String[] {TEST_CA_CERT_ALIAS + "TLS"});
472         config.setCaCertificates(new X509Certificate[] {FakeKeys.CA_CERT0, FakeKeys.CA_CERT1});
473         return config;
474     }
475 
createTLSWifiEnterpriseConfigWithAkaPhase2()476     public static WifiEnterpriseConfig createTLSWifiEnterpriseConfigWithAkaPhase2() {
477         WifiEnterpriseConfig config = new WifiEnterpriseConfig();
478         config.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
479         config.setPhase2Method(WifiEnterpriseConfig.Phase2.AKA);
480         return config;
481     }
482 
483     /**
484      * Gets scan result capabilities for a particular network configuration.
485      */
getScanResultCapsForNetwork(WifiConfiguration configuration)486     public static String getScanResultCapsForNetwork(WifiConfiguration configuration) {
487         String caps;
488         if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
489             caps = "[RSN-PSK-CCMP]";
490         } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)
491                 || configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
492             caps = "[RSN-EAP-CCMP]";
493         } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)
494                 && WifiConfigurationUtil.hasAnyValidWepKey(configuration.wepKeys)) {
495             caps = "[WEP]";
496         } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SAE)) {
497             caps = "[RSN-SAE-CCMP]";
498         } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.OWE)) {
499             caps = "[RSN-OWE-CCMP]";
500         } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SUITE_B_192)) {
501             caps = "[RSN-SUITE-B-192-CCMP]";
502         } else {
503             caps = "[]";
504         }
505         return caps;
506     }
507 
508     /**
509      * Gets scan result capabilities for a WPA2/WPA3-Transition mode network configuration
510      */
511     private static String
getScanResultCapsForWpa2Wpa3TransitionNetwork(WifiConfiguration configuration)512             getScanResultCapsForWpa2Wpa3TransitionNetwork(WifiConfiguration configuration) {
513         String caps = "[RSN-PSK+SAE-CCMP]";
514         return caps;
515     }
516 
517     /**
518      * Creates a scan detail corresponding to the provided network and given BSSID, etc.
519      */
createScanDetailForNetwork( WifiConfiguration configuration, String bssid, int level, int frequency, long tsf, long seen)520     public static ScanDetail createScanDetailForNetwork(
521             WifiConfiguration configuration, String bssid, int level, int frequency,
522             long tsf, long seen) {
523         String caps = getScanResultCapsForNetwork(configuration);
524         WifiSsid ssid = WifiSsid.createFromAsciiEncoded(configuration.getPrintableSsid());
525         return new ScanDetail(ssid, bssid, caps, level, frequency, tsf, seen);
526     }
527 
528     /**
529      * Creates a scan detail corresponding to the provided network and given BSSID, but sets
530      * the capabilities to WPA2/WPA3-Transition mode network.
531      */
createScanDetailForWpa2Wpa3TransitionModeNetwork( WifiConfiguration configuration, String bssid, int level, int frequency, long tsf, long seen)532     public static ScanDetail createScanDetailForWpa2Wpa3TransitionModeNetwork(
533             WifiConfiguration configuration, String bssid, int level, int frequency,
534             long tsf, long seen) {
535         String caps = getScanResultCapsForWpa2Wpa3TransitionNetwork(configuration);
536         WifiSsid ssid = WifiSsid.createFromAsciiEncoded(configuration.getPrintableSsid());
537         return new ScanDetail(ssid, bssid, caps, level, frequency, tsf, seen);
538     }
539 
540 
541     /**
542      * Asserts that the 2 WifiConfigurations are equal in the elements saved for both backup/restore
543      * and config store.
544      */
assertCommonConfigurationElementsEqual( WifiConfiguration expected, WifiConfiguration actual)545     private static void assertCommonConfigurationElementsEqual(
546             WifiConfiguration expected, WifiConfiguration actual) {
547         assertNotNull(expected);
548         assertNotNull(actual);
549         assertEquals(expected.SSID, actual.SSID);
550         assertEquals(expected.BSSID, actual.BSSID);
551         assertEquals(expected.preSharedKey, actual.preSharedKey);
552         assertEquals(expected.wepKeys, actual.wepKeys);
553         assertEquals(expected.wepTxKeyIndex, actual.wepTxKeyIndex);
554         assertEquals(expected.hiddenSSID, actual.hiddenSSID);
555         assertEquals(expected.requirePMF, actual.requirePMF);
556         assertEquals(expected.allowedKeyManagement, actual.allowedKeyManagement);
557         assertEquals(expected.allowedProtocols, actual.allowedProtocols);
558         assertEquals(expected.allowedAuthAlgorithms, actual.allowedAuthAlgorithms);
559         assertEquals(expected.allowedGroupCiphers, actual.allowedGroupCiphers);
560         assertEquals(expected.allowedPairwiseCiphers, actual.allowedPairwiseCiphers);
561         assertEquals(expected.shared, actual.shared);
562         assertEquals(expected.getIpConfiguration(), actual.getIpConfiguration());
563     }
564 
565     /**
566      * Asserts that the 2 WifiConfigurations are equal. This only compares the elements saved
567      * for backup/restore.
568      */
assertConfigurationEqualForBackup( WifiConfiguration expected, WifiConfiguration actual)569     public static void assertConfigurationEqualForBackup(
570             WifiConfiguration expected, WifiConfiguration actual) {
571         assertCommonConfigurationElementsEqual(expected, actual);
572         assertEquals(expected.meteredOverride, actual.meteredOverride);
573     }
574 
575     /**
576      * Asserts that the 2 WifiConfigurations are equal. This compares all the elements saved for
577      * config store.
578      */
assertConfigurationEqualForConfigStore( WifiConfiguration expected, WifiConfiguration actual)579     public static void assertConfigurationEqualForConfigStore(
580             WifiConfiguration expected, WifiConfiguration actual) {
581         assertCommonConfigurationElementsEqual(expected, actual);
582         assertEquals(expected.status, actual.status);
583         assertEquals(expected.FQDN, actual.FQDN);
584         assertEquals(expected.providerFriendlyName, actual.providerFriendlyName);
585         assertTrue(Arrays.equals(expected.roamingConsortiumIds, actual.roamingConsortiumIds));
586         assertEquals(expected.linkedConfigurations, actual.linkedConfigurations);
587         assertEquals(expected.defaultGwMacAddress, actual.defaultGwMacAddress);
588         assertEquals(expected.validatedInternetAccess, actual.validatedInternetAccess);
589         assertEquals(expected.noInternetAccessExpected, actual.noInternetAccessExpected);
590         assertEquals(expected.userApproved, actual.userApproved);
591         assertEquals(expected.meteredHint, actual.meteredHint);
592         assertEquals(expected.meteredOverride, actual.meteredOverride);
593         assertEquals(expected.useExternalScores, actual.useExternalScores);
594         assertEquals(expected.numAssociation, actual.numAssociation);
595         assertEquals(expected.creatorUid, actual.creatorUid);
596         assertEquals(expected.creatorName, actual.creatorName);
597         assertEquals(expected.creationTime, actual.creationTime);
598         assertEquals(expected.lastUpdateUid, actual.lastUpdateUid);
599         assertEquals(expected.lastUpdateName, actual.lastUpdateName);
600         assertEquals(expected.lastConnectUid, actual.lastConnectUid);
601         assertEquals(expected.updateTime, actual.updateTime);
602         assertEquals(expected.isLegacyPasspointConfig, actual.isLegacyPasspointConfig);
603         assertEquals(expected.getRandomizedMacAddress(), actual.getRandomizedMacAddress());
604         assertEquals(expected.macRandomizationSetting, actual.macRandomizationSetting);
605         assertNetworkSelectionStatusEqualForConfigStore(
606                 expected.getNetworkSelectionStatus(), actual.getNetworkSelectionStatus());
607         assertWifiEnterpriseConfigEqualForConfigStore(
608                 expected.enterpriseConfig, actual.enterpriseConfig);
609     }
610 
611     /**
612      * Asserts that the 2 WifiConfigurations are equal. This compares all the elements that are
613      * saved into internal database by WifiConfigurationManager for network additions/updates.
614      */
assertConfigurationEqualForConfigManagerAddOrUpdate( WifiConfiguration expected, WifiConfiguration actual)615     public static void assertConfigurationEqualForConfigManagerAddOrUpdate(
616             WifiConfiguration expected, WifiConfiguration actual) {
617         assertCommonConfigurationElementsEqual(expected, actual);
618         assertEquals(expected.FQDN, actual.FQDN);
619         assertEquals(expected.providerFriendlyName, actual.providerFriendlyName);
620         assertEquals(expected.noInternetAccessExpected, actual.noInternetAccessExpected);
621         assertEquals(expected.meteredHint, actual.meteredHint);
622         assertEquals(expected.meteredOverride, actual.meteredOverride);
623         assertEquals(expected.useExternalScores, actual.useExternalScores);
624         assertEquals(expected.ephemeral, actual.ephemeral);
625         assertEquals(expected.osu, actual.osu);
626         assertEquals(expected.trusted, actual.trusted);
627         assertEquals(expected.fromWifiNetworkSuggestion, actual.fromWifiNetworkSuggestion);
628         assertEquals(expected.fromWifiNetworkSpecifier, actual.fromWifiNetworkSpecifier);
629         assertEquals(expected.creatorUid, actual.creatorUid);
630         assertEquals(expected.creatorName, actual.creatorName);
631         assertEquals(expected.creationTime, actual.creationTime);
632         assertEquals(expected.lastUpdateUid, actual.lastUpdateUid);
633         assertEquals(expected.lastUpdateName, actual.lastUpdateName);
634         assertEquals(expected.updateTime, actual.updateTime);
635         assertNetworkSelectionStatusEqualForConfigStore(
636                 expected.getNetworkSelectionStatus(), actual.getNetworkSelectionStatus());
637         assertWifiEnterpriseConfigEqualForConfigStore(
638                 expected.enterpriseConfig, actual.enterpriseConfig);
639     }
640 
641     /**
642      * Asserts that the 2 WifiConfigurations are equal. This compares all the elements that are
643      * saved into wpa_supplicant by SupplicantStaNetwork.
644      */
assertConfigurationEqualForSupplicant( WifiConfiguration expected, WifiConfiguration actual)645     public static void assertConfigurationEqualForSupplicant(
646             WifiConfiguration expected, WifiConfiguration actual) {
647         assertNotNull(expected);
648         assertNotNull(actual);
649         assertEquals(expected.SSID, actual.SSID);
650         assertEquals(expected.getNetworkSelectionStatus().getNetworkSelectionBSSID(),
651                 actual.getNetworkSelectionStatus().getNetworkSelectionBSSID());
652         assertEquals(expected.preSharedKey, actual.preSharedKey);
653         assertEquals(expected.wepKeys, actual.wepKeys);
654         assertEquals(expected.wepTxKeyIndex, actual.wepTxKeyIndex);
655         assertEquals(expected.hiddenSSID, actual.hiddenSSID);
656         assertEquals(expected.requirePMF, actual.requirePMF);
657         assertEquals(expected.allowedKeyManagement, actual.allowedKeyManagement);
658         assertEquals(expected.allowedProtocols, actual.allowedProtocols);
659         assertEquals(expected.allowedAuthAlgorithms, actual.allowedAuthAlgorithms);
660         assertEquals(expected.allowedGroupCiphers, actual.allowedGroupCiphers);
661         assertEquals(expected.allowedPairwiseCiphers, actual.allowedPairwiseCiphers);
662         assertWifiEnterpriseConfigEqualForConfigStore(
663                 expected.enterpriseConfig, actual.enterpriseConfig);
664     }
665 
666     /**
667      * Asserts that the 2 WifiConfigurations are equal. This is a generic version of the comparator
668      * which is used in QNS tests for comparing the network selections.
669      * This importantly checks that the networkId's of the 2 configs are equal.
670      */
assertConfigurationEqual( WifiConfiguration expected, WifiConfiguration actual)671     public static void assertConfigurationEqual(
672             WifiConfiguration expected, WifiConfiguration actual) {
673         assertCommonConfigurationElementsEqual(expected, actual);
674         assertEquals(expected.networkId, actual.networkId);
675         assertEquals(expected.ephemeral, actual.ephemeral);
676         assertEquals(expected.fromWifiNetworkSuggestion, actual.fromWifiNetworkSuggestion);
677         assertEquals(expected.fromWifiNetworkSpecifier, actual.fromWifiNetworkSpecifier);
678         assertEquals(expected.trusted, actual.trusted);
679     }
680 
681     /**
682      * Assert that the 2 NetworkSelectionStatus's are equal. This compares all the elements saved
683      * for config store.
684      */
assertNetworkSelectionStatusEqualForConfigStore( NetworkSelectionStatus expected, NetworkSelectionStatus actual)685     public static void assertNetworkSelectionStatusEqualForConfigStore(
686             NetworkSelectionStatus expected, NetworkSelectionStatus actual) {
687         if (expected.isNetworkTemporaryDisabled()) {
688             // Temporarily disabled networks are enabled when persisted.
689             assertEquals(
690                     NetworkSelectionStatus.NETWORK_SELECTION_ENABLED,
691                     actual.getNetworkSelectionStatus());
692             assertEquals(
693                     NetworkSelectionStatus.NETWORK_SELECTION_ENABLE,
694                     actual.getNetworkSelectionDisableReason());
695         } else {
696             assertEquals(expected.getNetworkSelectionStatus(), actual.getNetworkSelectionStatus());
697             assertEquals(
698                     expected.getNetworkSelectionDisableReason(),
699                     actual.getNetworkSelectionDisableReason());
700         }
701         assertEquals(expected.getConnectChoice(), actual.getConnectChoice());
702         assertEquals(expected.getConnectChoiceTimestamp(), actual.getConnectChoiceTimestamp());
703         assertEquals(expected.getHasEverConnected(), actual.getHasEverConnected());
704     }
705 
706     /**
707      * Assert that the 2 WifiEnterpriseConfig's are equal. This compares all the elements saved
708      * for config store.
709      */
assertWifiEnterpriseConfigEqualForConfigStore( WifiEnterpriseConfig expected, WifiEnterpriseConfig actual)710     public static void assertWifiEnterpriseConfigEqualForConfigStore(
711             WifiEnterpriseConfig expected, WifiEnterpriseConfig actual) {
712         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.IDENTITY_KEY),
713                 actual.getFieldValue(WifiEnterpriseConfig.IDENTITY_KEY));
714         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.ANON_IDENTITY_KEY),
715                 actual.getFieldValue(WifiEnterpriseConfig.ANON_IDENTITY_KEY));
716         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.PASSWORD_KEY),
717                 actual.getFieldValue(WifiEnterpriseConfig.PASSWORD_KEY));
718         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.CLIENT_CERT_KEY),
719                 actual.getFieldValue(WifiEnterpriseConfig.CLIENT_CERT_KEY));
720         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.CA_CERT_KEY),
721                 actual.getFieldValue(WifiEnterpriseConfig.CA_CERT_KEY));
722         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.SUBJECT_MATCH_KEY),
723                 actual.getFieldValue(WifiEnterpriseConfig.SUBJECT_MATCH_KEY));
724         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.ENGINE_KEY),
725                 actual.getFieldValue(WifiEnterpriseConfig.ENGINE_KEY));
726         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY),
727                 actual.getFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY));
728         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY),
729                 actual.getFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY));
730         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.ALTSUBJECT_MATCH_KEY),
731                 actual.getFieldValue(WifiEnterpriseConfig.ALTSUBJECT_MATCH_KEY));
732         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.DOM_SUFFIX_MATCH_KEY),
733                 actual.getFieldValue(WifiEnterpriseConfig.DOM_SUFFIX_MATCH_KEY));
734         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.CA_PATH_KEY),
735                 actual.getFieldValue(WifiEnterpriseConfig.CA_PATH_KEY));
736         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.REALM_KEY),
737                 actual.getFieldValue(WifiEnterpriseConfig.REALM_KEY));
738         assertEquals(expected.getFieldValue(WifiEnterpriseConfig.PLMN_KEY),
739                 actual.getFieldValue(WifiEnterpriseConfig.PLMN_KEY));
740         assertEquals(expected.getEapMethod(), actual.getEapMethod());
741         assertEquals(expected.getPhase2Method(), actual.getPhase2Method());
742     }
743 
744     /**
745      * Asserts that the 2 lists of WifiConfigurations are equal. This compares all the elements
746      * saved for backup/restore.
747      */
assertConfigurationsEqualForBackup( List<WifiConfiguration> expected, List<WifiConfiguration> actual)748     public static void assertConfigurationsEqualForBackup(
749             List<WifiConfiguration> expected, List<WifiConfiguration> actual) {
750         assertEquals(expected.size(), actual.size());
751         for (WifiConfiguration expectedConfiguration : expected) {
752             String expectedConfigKey = expectedConfiguration.configKey();
753             boolean didCompare = false;
754             for (WifiConfiguration actualConfiguration : actual) {
755                 String actualConfigKey = actualConfiguration.configKey();
756                 if (actualConfigKey.equals(expectedConfigKey)) {
757                     assertConfigurationEqualForBackup(
758                             expectedConfiguration, actualConfiguration);
759                     didCompare = true;
760                 }
761             }
762             assertTrue(didCompare);
763         }
764     }
765 
766     /**
767      * Asserts that the 2 lists of WifiConfigurations are equal. This compares all the elements
768      * that are saved into internal database by WifiConfigurationManager for network
769      * additions/updates.
770      */
assertConfigurationsEqualForConfigManagerAddOrUpdate( List<WifiConfiguration> expected, List<WifiConfiguration> actual)771     public static void assertConfigurationsEqualForConfigManagerAddOrUpdate(
772             List<WifiConfiguration> expected, List<WifiConfiguration> actual) {
773         assertEquals(expected.size(), actual.size());
774         for (WifiConfiguration expectedConfiguration : expected) {
775             String expectedConfigKey = expectedConfiguration.configKey();
776             boolean didCompare = false;
777             for (WifiConfiguration actualConfiguration : actual) {
778                 String actualConfigKey = actualConfiguration.configKey();
779                 if (actualConfigKey.equals(expectedConfigKey)) {
780                     assertConfigurationEqualForConfigManagerAddOrUpdate(
781                             expectedConfiguration, actualConfiguration);
782                     didCompare = true;
783                 }
784             }
785             assertTrue(didCompare);
786         }
787     }
788 
789     /**
790      * Asserts that the 2 lists of WifiConfigurations are equal. This compares all the elements
791      * saved for config store.
792      */
assertConfigurationsEqualForConfigStore( List<WifiConfiguration> expected, List<WifiConfiguration> actual)793     public static void assertConfigurationsEqualForConfigStore(
794             List<WifiConfiguration> expected, List<WifiConfiguration> actual) {
795         assertEquals(expected.size(), actual.size());
796         for (WifiConfiguration expectedConfiguration : expected) {
797             String expectedConfigKey = expectedConfiguration.configKey();
798             boolean didCompare = false;
799             for (WifiConfiguration actualConfiguration : actual) {
800                 String actualConfigKey = actualConfiguration.configKey();
801                 if (actualConfigKey.equals(expectedConfigKey)) {
802                     assertConfigurationEqualForConfigStore(
803                             expectedConfiguration, actualConfiguration);
804                     didCompare = true;
805                 }
806             }
807             assertTrue(didCompare);
808         }
809     }
810 }
811