SupplicantBridge.java revision 31891afce40b903ada9b24ec12e3648ae6aa27b2
1package com.android.server.wifi.hotspot2; 2 3import android.util.Log; 4 5import com.android.server.wifi.ScanDetail; 6import com.android.server.wifi.WifiConfigStore; 7import com.android.server.wifi.WifiNative; 8import com.android.server.wifi.anqp.ANQPElement; 9import com.android.server.wifi.anqp.ANQPFactory; 10import com.android.server.wifi.anqp.Constants; 11import com.android.server.wifi.anqp.eap.AuthParam; 12import com.android.server.wifi.anqp.eap.EAP; 13import com.android.server.wifi.anqp.eap.EAPMethod; 14import com.android.server.wifi.hotspot2.pps.Credential; 15 16import java.io.BufferedReader; 17import java.io.IOException; 18import java.io.StringReader; 19import java.net.ProtocolException; 20import java.nio.ByteBuffer; 21import java.nio.ByteOrder; 22import java.nio.CharBuffer; 23import java.nio.charset.CharacterCodingException; 24import java.nio.charset.StandardCharsets; 25import java.util.ArrayList; 26import java.util.HashMap; 27import java.util.List; 28import java.util.Map; 29 30public class SupplicantBridge { 31 private final WifiNative mSupplicantHook; 32 private final WifiConfigStore mConfigStore; 33 private final Map<Long, ScanDetail> mRequestMap = new HashMap<>(); 34 35 private static final Map<String, Constants.ANQPElementType> sWpsNames = new HashMap<>(); 36 37 static { 38 sWpsNames.put("anqp_venue_name", Constants.ANQPElementType.ANQPVenueName); 39 sWpsNames.put("anqp_network_auth_type", Constants.ANQPElementType.ANQPNwkAuthType); 40 sWpsNames.put("anqp_roaming_consortium", Constants.ANQPElementType.ANQPRoamingConsortium); 41 sWpsNames.put("anqp_ip_addr_type_availability", 42 Constants.ANQPElementType.ANQPIPAddrAvailability); 43 sWpsNames.put("anqp_nai_realm", Constants.ANQPElementType.ANQPNAIRealm); 44 sWpsNames.put("anqp_3gpp", Constants.ANQPElementType.ANQP3GPPNetwork); 45 sWpsNames.put("anqp_domain_name", Constants.ANQPElementType.ANQPDomName); 46 sWpsNames.put("hs20_operator_friendly_name", Constants.ANQPElementType.HSFriendlyName); 47 sWpsNames.put("hs20_wan_metrics", Constants.ANQPElementType.HSWANMetrics); 48 sWpsNames.put("hs20_connection_capability", Constants.ANQPElementType.HSConnCapability); 49 sWpsNames.put("hs20_operating_class", Constants.ANQPElementType.HSOperatingclass); 50 sWpsNames.put("hs20_osu_providers_list", Constants.ANQPElementType.HSOSUProviders); 51 } 52 53 public static boolean isAnqpAttribute(String line) { 54 int split = line.indexOf('='); 55 return split >= 0 && sWpsNames.containsKey(line.substring(0, split)); 56 } 57 58 public SupplicantBridge(WifiNative supplicantHook, WifiConfigStore configStore) { 59 mSupplicantHook = supplicantHook; 60 mConfigStore = configStore; 61 } 62 63 public static Map<Constants.ANQPElementType, ANQPElement> parseANQPLines(List<String> lines) { 64 if (lines == null) { 65 return null; 66 } 67 Map<Constants.ANQPElementType, ANQPElement> elements = new HashMap<>(lines.size()); 68 for (String line : lines) { 69 try { 70 ANQPElement element = buildElement(line); 71 if (element != null) { 72 elements.put(element.getID(), element); 73 } 74 } 75 catch (ProtocolException pe) { 76 Log.e(Utils.hs2LogTag(SupplicantBridge.class), "Failed to parse ANQP: " + pe); 77 } 78 } 79 return elements; 80 } 81 82 public void startANQP(ScanDetail scanDetail) { 83 String anqpGet = buildWPSQueryRequest(scanDetail.getNetworkDetail()); 84 synchronized (mRequestMap) { 85 mRequestMap.put(scanDetail.getNetworkDetail().getBSSID(), scanDetail); 86 } 87 String result = mSupplicantHook.doCustomCommand(anqpGet); 88 if (result.startsWith("OK")) { 89 Log.d(Utils.hs2LogTag(getClass()), "ANQP initiated on " + scanDetail.getSSID()); 90 } 91 else { 92 Log.d(Utils.hs2LogTag(getClass()), "ANQP failed on " + 93 scanDetail.getSSID() + ": " + result); 94 } 95 } 96 97 public void notifyANQPDone(Long bssid, boolean success) { 98 ScanDetail scanDetail; 99 synchronized (mRequestMap) { 100 scanDetail = mRequestMap.remove(bssid); 101 } 102 if (scanDetail == null) { 103 return; 104 } 105 106 String bssData = mSupplicantHook.scanResult(scanDetail.getBSSIDString()); 107 //Log.d("HS2J", "BSS data for " + scanDetail.getBSSIDString() + ": " + bssData); 108 try { 109 Map<Constants.ANQPElementType, ANQPElement> elements = parseWPSData(bssData); 110 if (!elements.isEmpty()) { 111 Log.d(Utils.hs2LogTag(getClass()), String.format("Parsed ANQP for %016x: %s", bssid, elements)); 112 mConfigStore.notifyANQPResponse(scanDetail, elements); 113 } 114 } 115 catch (IOException ioe) { 116 Log.e(Utils.hs2LogTag(getClass()), ioe.toString()); 117 } 118 mConfigStore.notifyANQPResponse(scanDetail, null); 119 } 120 121 /* 122 public boolean addCredential(HomeSP homeSP, NetworkDetail networkDetail) { 123 Credential credential = homeSP.getCredential(); 124 if (credential == null) 125 return false; 126 127 String nwkID = null; 128 if (mLastSSID != null) { 129 String nwkList = mSupplicantHook.doCustomCommand("LIST_NETWORKS"); 130 131 BufferedReader reader = new BufferedReader(new StringReader(nwkList)); 132 String line; 133 try { 134 while ((line = reader.readLine()) != null) { 135 String[] tokens = line.split("\\t"); 136 if (tokens.length < 2 || ! Utils.isDecimal(tokens[0])) { 137 continue; 138 } 139 if (unescapeSSID(tokens[1]).equals(mLastSSID)) { 140 nwkID = tokens[0]; 141 Log.d("HS2J", "Network " + tokens[0] + 142 " matches last SSID '" + mLastSSID + "'"); 143 break; 144 } 145 } 146 } 147 catch (IOException ioe) { 148 // 149 } 150 } 151 152 if (nwkID == null) { 153 nwkID = mSupplicantHook.doCustomCommand("ADD_NETWORK"); 154 Log.d("HS2J", "add_network: '" + nwkID + "'"); 155 if (! Utils.isDecimal(nwkID)) { 156 return false; 157 } 158 } 159 160 List<String> credCommand = getWPSNetCommands(nwkID, networkDetail, credential); 161 for (String command : credCommand) { 162 String status = mSupplicantHook.doCustomCommand(command); 163 Log.d("HS2J", "Status of '" + command + "': '" + status + "'"); 164 } 165 166 if (! networkDetail.getSSID().equals(mLastSSID)) { 167 mLastSSID = networkDetail.getSSID(); 168 PrintWriter out = null; 169 try { 170 out = new PrintWriter(new OutputStreamWriter( 171 new FileOutputStream(mLastSSIDFile, false), StandardCharsets.UTF_8)); 172 out.println(mLastSSID); 173 } catch (IOException ioe) { 174 // 175 } finally { 176 if (out != null) { 177 out.close(); 178 } 179 } 180 } 181 182 return true; 183 } 184 */ 185 186 private static String escapeSSID(NetworkDetail networkDetail) { 187 return escapeString(networkDetail.getSSID(), networkDetail.isSSID_UTF8()); 188 } 189 190 private static String escapeString(String s, boolean utf8) { 191 boolean asciiOnly = true; 192 for (int n = 0; n < s.length(); n++) { 193 char ch = s.charAt(n); 194 if (ch > 127) { 195 asciiOnly = false; 196 break; 197 } 198 } 199 200 if (asciiOnly) { 201 return '"' + s + '"'; 202 } 203 else { 204 byte[] octets = s.getBytes(utf8 ? StandardCharsets.UTF_8 : StandardCharsets.ISO_8859_1); 205 206 StringBuilder sb = new StringBuilder(); 207 for (byte octet : octets) { 208 sb.append(String.format("%02x", octet & Constants.BYTE_MASK)); 209 } 210 return sb.toString(); 211 } 212 } 213 214 private static String buildWPSQueryRequest(NetworkDetail networkDetail) { 215 StringBuilder sb = new StringBuilder(); 216 sb.append("ANQP_GET ").append(networkDetail.getBSSIDString()).append(' '); 217 218 boolean first = true; 219 for (Constants.ANQPElementType elementType : ANQPFactory.getBaseANQPSet()) { 220 if (networkDetail.getAnqpOICount() == 0 && 221 elementType == Constants.ANQPElementType.ANQPRoamingConsortium) { 222 continue; 223 } 224 if (first) { 225 first = false; 226 } 227 else { 228 sb.append(','); 229 } 230 sb.append(Constants.getANQPElementID(elementType)); 231 } 232 if (networkDetail.getHSRelease() != null) { 233 for (Constants.ANQPElementType elementType : ANQPFactory.getHS20ANQPSet()) { 234 sb.append(",hs20:").append(Constants.getHS20ElementID(elementType)); 235 } 236 } 237 return sb.toString(); 238 } 239 240 private static List<String> getWPSNetCommands(String netID, NetworkDetail networkDetail, 241 Credential credential) { 242 243 List<String> commands = new ArrayList<String>(); 244 245 EAPMethod eapMethod = credential.getEAPMethod(); 246 commands.add(String.format("SET_NETWORK %s key_mgmt WPA-EAP", netID)); 247 commands.add(String.format("SET_NETWORK %s ssid %s", netID, escapeSSID(networkDetail))); 248 commands.add(String.format("SET_NETWORK %s bssid %s", 249 netID, networkDetail.getBSSIDString())); 250 commands.add(String.format("SET_NETWORK %s eap %s", 251 netID, mapEAPMethodName(eapMethod.getEAPMethodID()))); 252 253 AuthParam authParam = credential.getEAPMethod().getAuthParam(); 254 if (authParam == null) { 255 return null; // TLS or SIM/AKA 256 } 257 switch (authParam.getAuthInfoID()) { 258 case NonEAPInnerAuthType: 259 case InnerAuthEAPMethodType: 260 commands.add(String.format("SET_NETWORK %s identity %s", 261 netID, escapeString(credential.getUserName(), true))); 262 commands.add(String.format("SET_NETWORK %s password %s", 263 netID, escapeString(credential.getPassword(), true))); 264 commands.add(String.format("SET_NETWORK %s anonymous_identity \"anonymous\"", 265 netID)); 266 break; 267 default: // !!! Needs work. 268 return null; 269 } 270 commands.add(String.format("SET_NETWORK %s priority 0", netID)); 271 commands.add(String.format("ENABLE_NETWORK %s", netID)); 272 commands.add(String.format("SAVE_CONFIG")); 273 return commands; 274 } 275 276 private static Map<Constants.ANQPElementType, ANQPElement> parseWPSData(String bssInfo) 277 throws IOException { 278 Map<Constants.ANQPElementType, ANQPElement> elements = new HashMap<>(); 279 if (bssInfo == null) { 280 return elements; 281 } 282 BufferedReader lineReader = new BufferedReader(new StringReader(bssInfo)); 283 String line; 284 while ((line=lineReader.readLine()) != null) { 285 ANQPElement element = buildElement(line); 286 if (element != null) { 287 elements.put(element.getID(), element); 288 } 289 } 290 return elements; 291 } 292 293 private static ANQPElement buildElement(String text) throws ProtocolException { 294 int separator = text.indexOf('='); 295 if (separator < 0) { 296 return null; 297 } 298 299 String elementName = text.substring(0, separator); 300 Constants.ANQPElementType elementType = sWpsNames.get(elementName); 301 if (elementType == null) { 302 return null; 303 } 304 305 byte[] payload; 306 try { 307 payload = Utils.hexToBytes(text.substring(separator + 1)); 308 } 309 catch (NumberFormatException nfe) { 310 Log.e(Utils.hs2LogTag(SupplicantBridge.class), "Failed to parse hex string"); 311 return null; 312 } 313 return Constants.getANQPElementID(elementType) != null ? 314 ANQPFactory.buildElement(ByteBuffer.wrap(payload), elementType, payload.length) : 315 ANQPFactory.buildHS20Element(elementType, 316 ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN)); 317 } 318 319 private static String mapEAPMethodName(EAP.EAPMethodID eapMethodID) { 320 switch (eapMethodID) { 321 case EAP_AKA: 322 return "AKA"; 323 case EAP_AKAPrim: 324 return "AKA'"; // eap.c:1514 325 case EAP_SIM: 326 return "SIM"; 327 case EAP_TLS: 328 return "TLS"; 329 case EAP_TTLS: 330 return "TTLS"; 331 default: 332 throw new IllegalArgumentException("No mapping for " + eapMethodID); 333 } 334 } 335 336 private static final Map<Character,Integer> sMappings = new HashMap<Character, Integer>(); 337 338 static { 339 sMappings.put('\\', (int)'\\'); 340 sMappings.put('"', (int)'"'); 341 sMappings.put('e', 0x1b); 342 sMappings.put('n', (int)'\n'); 343 sMappings.put('r', (int)'\n'); 344 sMappings.put('t', (int)'\t'); 345 } 346 347 public static String unescapeSSID(String ssid) { 348 349 CharIterator chars = new CharIterator(ssid); 350 byte[] octets = new byte[ssid.length()]; 351 int bo = 0; 352 353 while (chars.hasNext()) { 354 char ch = chars.next(); 355 if (ch != '\\' || ! chars.hasNext()) { 356 octets[bo++] = (byte)ch; 357 } 358 else { 359 char suffix = chars.next(); 360 Integer mapped = sMappings.get(suffix); 361 if (mapped != null) { 362 octets[bo++] = mapped.byteValue(); 363 } 364 else if (suffix == 'x' && chars.hasDoubleHex()) { 365 octets[bo++] = (byte)chars.nextDoubleHex(); 366 } 367 else { 368 octets[bo++] = '\\'; 369 octets[bo++] = (byte)suffix; 370 } 371 } 372 } 373 374 boolean asciiOnly = true; 375 for (byte b : octets) { 376 if ((b&0x80) != 0) { 377 asciiOnly = false; 378 break; 379 } 380 } 381 if (asciiOnly) { 382 return new String(octets, 0, bo, StandardCharsets.UTF_8); 383 } else { 384 try { 385 // If UTF-8 decoding is successful it is almost certainly UTF-8 386 CharBuffer cb = StandardCharsets.UTF_8.newDecoder().decode( 387 ByteBuffer.wrap(octets, 0, bo)); 388 return cb.toString(); 389 } catch (CharacterCodingException cce) { 390 return new String(octets, 0, bo, StandardCharsets.ISO_8859_1); 391 } 392 } 393 } 394 395 private static class CharIterator { 396 private final String mString; 397 private int mPosition; 398 private int mHex; 399 400 private CharIterator(String s) { 401 mString = s; 402 } 403 404 private boolean hasNext() { 405 return mPosition < mString.length(); 406 } 407 408 private char next() { 409 return mString.charAt(mPosition++); 410 } 411 412 private boolean hasDoubleHex() { 413 if (mString.length() - mPosition < 2) { 414 return false; 415 } 416 int nh = Utils.fromHex(mString.charAt(mPosition), true); 417 if (nh < 0) { 418 return false; 419 } 420 int nl = Utils.fromHex(mString.charAt(mPosition + 1), true); 421 if (nl < 0) { 422 return false; 423 } 424 mPosition += 2; 425 mHex = (nh << 4) | nl; 426 return true; 427 } 428 429 private int nextDoubleHex() { 430 return mHex; 431 } 432 } 433 434 private static final String[] TestStrings = { 435 "test-ssid", 436 "test\\nss\\tid", 437 "test\\x2d\\x5f\\nss\\tid", 438 "test\\x2d\\x5f\\nss\\tid\\\\", 439 "test\\x2d\\x5f\\nss\\tid\\n", 440 "test\\x2d\\x5f\\nss\\tid\\x4a", 441 "another\\", 442 "an\\other", 443 "another\\x2" 444 }; 445 446 public static void main(String[] args) { 447 for (String string : TestStrings) { 448 System.out.println(unescapeSSID(string)); 449 } 450 } 451} 452