PageRenderTime 81ms CodeModel.GetById 27ms RepoModel.GetById 2ms app.codeStats 0ms

/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/WifiConfigurationHelper.java

https://gitlab.com/AvayKumar/android_frameworks_base
Java | 364 lines | 223 code | 35 blank | 106 comment | 42 complexity | 7a474263937f506ff4e1e3379f75c758 MD5 | raw file
  1. /*
  2. * Copyright (C) 2010, 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. package com.android.connectivitymanagertest;
  17. import android.net.IpConfiguration.IpAssignment;
  18. import android.net.IpConfiguration.ProxySettings;
  19. import android.net.LinkAddress;
  20. import android.net.StaticIpConfiguration;
  21. import android.net.wifi.WifiConfiguration;
  22. import android.net.wifi.WifiConfiguration.AuthAlgorithm;
  23. import android.net.wifi.WifiConfiguration.KeyMgmt;
  24. import android.net.wifi.WifiEnterpriseConfig;
  25. import org.json.JSONArray;
  26. import org.json.JSONException;
  27. import org.json.JSONObject;
  28. import java.net.InetAddress;
  29. import java.net.UnknownHostException;
  30. import java.util.ArrayList;
  31. import java.util.List;
  32. /**
  33. * Helper for dealing with creating {@link WifiConfiguration} objects.
  34. */
  35. public class WifiConfigurationHelper {
  36. private static final int NONE = 0;
  37. private static final int WEP = 1;
  38. private static final int PSK = 2;
  39. private static final int EAP = 3;
  40. /**
  41. * Private constructor since this a static class.
  42. */
  43. private WifiConfigurationHelper() {}
  44. /**
  45. * Create a {@link WifiConfiguration} for an open network
  46. *
  47. * @param ssid The SSID of the wifi network
  48. * @return The {@link WifiConfiguration}
  49. */
  50. public static WifiConfiguration createOpenConfig(String ssid) {
  51. WifiConfiguration config = createGenericConfig(ssid);
  52. config.allowedKeyManagement.set(KeyMgmt.NONE);
  53. return config;
  54. }
  55. /**
  56. * Create a {@link WifiConfiguration} for a WEP secured network
  57. *
  58. * @param ssid The SSID of the wifi network
  59. * @param password Either a 10, 26, or 58 character hex string or the plain text password
  60. * @return The {@link WifiConfiguration}
  61. */
  62. public static WifiConfiguration createWepConfig(String ssid, String password) {
  63. WifiConfiguration config = createGenericConfig(ssid);
  64. if (isHex(password, 10) || isHex(password, 26) || isHex(password, 58)) {
  65. config.wepKeys[0] = password;
  66. } else {
  67. config.wepKeys[0] = quotedString(password);
  68. }
  69. config.allowedKeyManagement.set(KeyMgmt.NONE);
  70. config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
  71. config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
  72. return config;
  73. }
  74. /**
  75. * Create a {@link WifiConfiguration} for a PSK secured network
  76. *
  77. * @param ssid The SSID of the wifi network
  78. * @param password Either a 64 character hex string or the plain text password
  79. * @return The {@link WifiConfiguration}
  80. */
  81. public static WifiConfiguration createPskConfig(String ssid, String password) {
  82. WifiConfiguration config = createGenericConfig(ssid);
  83. if (isHex(password, 64)) {
  84. config.preSharedKey = password;
  85. } else {
  86. config.preSharedKey = quotedString(password);
  87. }
  88. config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
  89. return config;
  90. }
  91. /**
  92. * Create a {@link WifiConfiguration} for an EAP secured network
  93. *
  94. * @param ssid The SSID of the wifi network
  95. * @param password The password
  96. * @param eapMethod The EAP method
  97. * @param phase2 The phase 2 method or null
  98. * @param identity The identity or null
  99. * @param anonymousIdentity The anonymous identity or null
  100. * @param caCert The CA certificate or null
  101. * @param clientCert The client certificate or null
  102. * @return The {@link WifiConfiguration}
  103. */
  104. public static WifiConfiguration createEapConfig(String ssid, String password, int eapMethod,
  105. Integer phase2, String identity, String anonymousIdentity, String caCert,
  106. String clientCert) {
  107. WifiConfiguration config = new WifiConfiguration();
  108. config.SSID = quotedString(ssid);
  109. config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
  110. config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
  111. // Set defaults
  112. if (phase2 == null) phase2 = WifiEnterpriseConfig.Phase2.NONE;
  113. if (identity == null) identity = "";
  114. if (anonymousIdentity == null) anonymousIdentity = "";
  115. if (caCert == null) caCert = "";
  116. if (clientCert == null) clientCert = "";
  117. config.enterpriseConfig.setPassword(password);
  118. config.enterpriseConfig.setEapMethod(eapMethod);
  119. config.enterpriseConfig.setPhase2Method(phase2);
  120. config.enterpriseConfig.setIdentity(identity);
  121. config.enterpriseConfig.setAnonymousIdentity(anonymousIdentity);
  122. config.enterpriseConfig.setCaCertificateAlias(caCert);
  123. config.enterpriseConfig.setClientCertificateAlias(clientCert);
  124. return config;
  125. }
  126. /**
  127. * Create a generic {@link WifiConfiguration} used by the other create methods.
  128. */
  129. private static WifiConfiguration createGenericConfig(String ssid) {
  130. WifiConfiguration config = new WifiConfiguration();
  131. config.SSID = quotedString(ssid);
  132. config.setIpAssignment(IpAssignment.DHCP);
  133. config.setProxySettings(ProxySettings.NONE);
  134. return config;
  135. }
  136. /**
  137. * Parse a JSON string for WiFi configurations stored as a JSON string.
  138. * <p>
  139. * This json string should be a list of dictionaries, with each dictionary containing a single
  140. * wifi configuration. The wifi configuration requires the fields "ssid" and "security" with
  141. * security being one of NONE, WEP, PSK, or EAP. If WEP, PSK, or EAP are selected, the field
  142. * "password" must also be provided. If EAP is selected, then the fiels "eap", "phase2",
  143. * "identity", "ananymous_identity", "ca_cert", and "client_cert" are also required. Lastly,
  144. * static IP settings are also supported. If the field "ip" is set, then the fields "gateway",
  145. * "prefix_length", "dns1", and "dns2" are required.
  146. * </p>
  147. * @throws IllegalArgumentException if the input string was not valid JSON or if any mandatory
  148. * fields are missing.
  149. */
  150. public static List<WifiConfiguration> parseJson(String in) {
  151. try {
  152. JSONArray jsonConfigs = new JSONArray(in);
  153. List<WifiConfiguration> wifiConfigs = new ArrayList<>(jsonConfigs.length());
  154. for (int i = 0; i < jsonConfigs.length(); i++) {
  155. JSONObject jsonConfig = jsonConfigs.getJSONObject(i);
  156. wifiConfigs.add(getWifiConfiguration(jsonConfig));
  157. }
  158. return wifiConfigs;
  159. } catch (JSONException e) {
  160. throw new IllegalArgumentException(e);
  161. }
  162. }
  163. /**
  164. * Parse a {@link JSONObject} and return the wifi configuration.
  165. *
  166. * @throws IllegalArgumentException if any mandatory fields are missing.
  167. */
  168. private static WifiConfiguration getWifiConfiguration(JSONObject jsonConfig)
  169. throws JSONException {
  170. String ssid = jsonConfig.getString("ssid");
  171. String password = null;
  172. WifiConfiguration config;
  173. int securityType = getSecurityType(jsonConfig.getString("security"));
  174. switch (securityType) {
  175. case NONE:
  176. config = createOpenConfig(ssid);
  177. break;
  178. case WEP:
  179. password = jsonConfig.getString("password");
  180. config = createWepConfig(ssid, password);
  181. break;
  182. case PSK:
  183. password = jsonConfig.getString("password");
  184. config = createPskConfig(ssid, password);
  185. break;
  186. case EAP:
  187. password = jsonConfig.getString("password");
  188. int eapMethod = getEapMethod(jsonConfig.getString("eap"));
  189. Integer phase2 = null;
  190. if (jsonConfig.has("phase2")) {
  191. phase2 = getPhase2(jsonConfig.getString("phase2"));
  192. }
  193. String identity = null;
  194. if (jsonConfig.has("identity")) {
  195. identity = jsonConfig.getString("identity");
  196. }
  197. String anonymousIdentity = null;
  198. if (jsonConfig.has("anonymous_identity")) {
  199. anonymousIdentity = jsonConfig.getString("anonymous_identity");
  200. }
  201. String caCert = null;
  202. if (jsonConfig.has("ca_cert")) {
  203. caCert = (jsonConfig.getString("ca_cert"));
  204. }
  205. String clientCert = null;
  206. if (jsonConfig.has("client_cert")) {
  207. clientCert = jsonConfig.getString("client_cert");
  208. }
  209. config = createEapConfig(ssid, password, eapMethod, phase2, identity,
  210. anonymousIdentity, caCert, clientCert);
  211. break;
  212. default:
  213. // Should never reach here as getSecurityType will already throw an exception
  214. throw new IllegalArgumentException();
  215. }
  216. if (jsonConfig.has("ip")) {
  217. StaticIpConfiguration staticIpConfig = new StaticIpConfiguration();
  218. InetAddress ipAddress = getInetAddress(jsonConfig.getString("ip"));
  219. int prefixLength = getPrefixLength(jsonConfig.getInt("prefix_length"));
  220. staticIpConfig.ipAddress = new LinkAddress(ipAddress, prefixLength);
  221. staticIpConfig.gateway = getInetAddress(jsonConfig.getString("gateway"));
  222. staticIpConfig.dnsServers.add(getInetAddress(jsonConfig.getString("dns1")));
  223. staticIpConfig.dnsServers.add(getInetAddress(jsonConfig.getString("dns2")));
  224. config.setIpAssignment(IpAssignment.STATIC);
  225. config.setStaticIpConfiguration(staticIpConfig);
  226. } else {
  227. config.setIpAssignment(IpAssignment.DHCP);
  228. }
  229. config.setProxySettings(ProxySettings.NONE);
  230. return config;
  231. }
  232. private static String quotedString(String s) {
  233. return String.format("\"%s\"", s);
  234. }
  235. /**
  236. * Get the security type from a string.
  237. *
  238. * @throws IllegalArgumentException if the string is not a supported security type.
  239. */
  240. private static int getSecurityType(String security) {
  241. if ("NONE".equalsIgnoreCase(security)) {
  242. return NONE;
  243. }
  244. if ("WEP".equalsIgnoreCase(security)) {
  245. return WEP;
  246. }
  247. if ("PSK".equalsIgnoreCase(security)) {
  248. return PSK;
  249. }
  250. if ("EAP".equalsIgnoreCase(security)) {
  251. return EAP;
  252. }
  253. throw new IllegalArgumentException("Security type must be one of NONE, WEP, PSK, or EAP");
  254. }
  255. /**
  256. * Get the EAP method from a string.
  257. *
  258. * @throws IllegalArgumentException if the string is not a supported EAP method.
  259. */
  260. private static int getEapMethod(String eapMethod) {
  261. if ("TLS".equalsIgnoreCase(eapMethod)) {
  262. return WifiEnterpriseConfig.Eap.TLS;
  263. }
  264. if ("TTLS".equalsIgnoreCase(eapMethod)) {
  265. return WifiEnterpriseConfig.Eap.TTLS;
  266. }
  267. if ("PEAP".equalsIgnoreCase(eapMethod)) {
  268. return WifiEnterpriseConfig.Eap.PEAP;
  269. }
  270. throw new IllegalArgumentException("EAP method must be one of TLS, TTLS, or PEAP");
  271. }
  272. /**
  273. * Get the phase 2 method from a string.
  274. *
  275. * @throws IllegalArgumentException if the string is not a supported phase 2 method.
  276. */
  277. private static int getPhase2(String phase2) {
  278. if ("PAP".equalsIgnoreCase(phase2)) {
  279. return WifiEnterpriseConfig.Phase2.PAP;
  280. }
  281. if ("MSCHAP".equalsIgnoreCase(phase2)) {
  282. return WifiEnterpriseConfig.Phase2.MSCHAP;
  283. }
  284. if ("MSCHAPV2".equalsIgnoreCase(phase2)) {
  285. return WifiEnterpriseConfig.Phase2.MSCHAPV2;
  286. }
  287. if ("GTC".equalsIgnoreCase(phase2)) {
  288. return WifiEnterpriseConfig.Phase2.GTC;
  289. }
  290. throw new IllegalArgumentException("Phase2 must be one of PAP, MSCHAP, MSCHAPV2, or GTC");
  291. }
  292. /**
  293. * Get an {@link InetAddress} from a string
  294. *
  295. * @throws IllegalArgumentException if the string is not a valid IP address.
  296. */
  297. private static InetAddress getInetAddress(String ipAddress) {
  298. if (!InetAddress.isNumeric(ipAddress)) {
  299. throw new IllegalArgumentException(
  300. String.format("IP address %s is not numeric", ipAddress));
  301. }
  302. try {
  303. return InetAddress.getByName(ipAddress);
  304. } catch (UnknownHostException e) {
  305. throw new IllegalArgumentException(
  306. String.format("IP address %s could not be resolved", ipAddress));
  307. }
  308. }
  309. /**
  310. * Get the prefix length from an int.
  311. *
  312. * @throws IllegalArgumentException if the prefix length is less than 0 or greater than 32.
  313. */
  314. private static int getPrefixLength(int prefixLength) {
  315. if (prefixLength < 0 || prefixLength > 32) {
  316. throw new IllegalArgumentException("Prefix length cannot be less than 0 or more than 32");
  317. }
  318. return prefixLength;
  319. }
  320. /**
  321. * Utility method to check if a given string is a hexadecimal string of given length
  322. */
  323. public static boolean isHex(String input, int length) {
  324. if (input == null || length < 0) {
  325. return false;
  326. }
  327. return input.matches(String.format("[0-9A-Fa-f]{%d}", length));
  328. }
  329. }