• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (C) 2014 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.nfc;
17 
18 
19 import android.app.ActivityManager;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.net.wifi.WifiConfiguration;
23 import android.nfc.NdefMessage;
24 import android.nfc.NdefRecord;
25 import android.nfc.tech.Ndef;
26 import android.os.UserHandle;
27 import android.os.UserManager;
28 
29 import java.nio.BufferUnderflowException;
30 import java.nio.ByteBuffer;
31 import java.util.BitSet;
32 
33 public final class NfcWifiProtectedSetup {
34 
35     public static final String NFC_TOKEN_MIME_TYPE = "application/vnd.wfa.wsc";
36 
37     public static final String EXTRA_WIFI_CONFIG = "com.android.nfc.WIFI_CONFIG_EXTRA";
38 
39     /*
40      * ID into configuration record for SSID and Network Key in hex.
41      * Obtained from WFA Wifi Simple Configuration Technical Specification v2.0.2.1.
42      */
43     private static final short CREDENTIAL_FIELD_ID = 0x100E;
44     private static final short SSID_FIELD_ID = 0x1045;
45     private static final short NETWORK_KEY_FIELD_ID = 0x1027;
46     private static final short AUTH_TYPE_FIELD_ID = 0x1003;
47 
48     private static final short AUTH_TYPE_EXPECTED_SIZE = 2;
49 
50     private static final short AUTH_TYPE_OPEN = 0x0001;
51     private static final short AUTH_TYPE_WPA_PSK = 0x0002;
52     private static final short AUTH_TYPE_WPA_EAP =  0x0008;
53     private static final short AUTH_TYPE_WPA2_EAP = 0x0010;
54     private static final short AUTH_TYPE_WPA2_PSK = 0x0020;
55     private static final short AUTH_TYPE_WPA_AND_WPA2_PSK = 0x0022;
56 
57     private static final int MAX_NETWORK_KEY_SIZE_BYTES = 64;
58 
NfcWifiProtectedSetup()59     private NfcWifiProtectedSetup() {}
60 
tryNfcWifiSetup(Ndef ndef, Context context)61     public static boolean tryNfcWifiSetup(Ndef ndef, Context context) {
62 
63         if (ndef == null || context == null) {
64             return false;
65         }
66 
67         NdefMessage cachedNdefMessage = ndef.getCachedNdefMessage();
68         if (cachedNdefMessage == null) {
69             return false;
70         }
71 
72         final WifiConfiguration wifiConfiguration;
73         try {
74             wifiConfiguration = parse(cachedNdefMessage);
75         } catch (BufferUnderflowException e) {
76             // malformed payload
77             return false;
78         }
79 
80         if (wifiConfiguration != null &&!UserManager.get(context).hasUserRestriction(
81                 UserManager.DISALLOW_CONFIG_WIFI,
82                 // hasUserRestriction does not support UserHandle.CURRENT.
83                 UserHandle.of(ActivityManager.getCurrentUser()))) {
84             Intent configureNetworkIntent = new Intent()
85                     .putExtra(EXTRA_WIFI_CONFIG, wifiConfiguration)
86                     .setClass(context, ConfirmConnectToWifiNetworkActivity.class)
87                     .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
88 
89             context.startActivityAsUser(configureNetworkIntent, UserHandle.CURRENT);
90             return true;
91         }
92 
93         return false;
94     }
95 
parse(NdefMessage message)96     private static WifiConfiguration parse(NdefMessage message) {
97         NdefRecord[] records = message.getRecords();
98 
99         for (NdefRecord record : records) {
100             if (new String(record.getType()).equals(NFC_TOKEN_MIME_TYPE)) {
101                 ByteBuffer payload = ByteBuffer.wrap(record.getPayload());
102                 while (payload.hasRemaining()) {
103                     short fieldId = payload.getShort();
104                     int fieldSize = payload.getShort() & 0xFFFF;
105                     if (fieldId == CREDENTIAL_FIELD_ID) {
106                         return parseCredential(payload, fieldSize);
107                     }
108                     payload.position(payload.position() + fieldSize);
109                 }
110             }
111         }
112         return null;
113     }
114 
parseCredential(ByteBuffer payload, int size)115     private static WifiConfiguration parseCredential(ByteBuffer payload, int size) {
116         int startPosition = payload.position();
117         WifiConfiguration result = new WifiConfiguration();
118         while (payload.position() < startPosition + size) {
119             short fieldId = payload.getShort();
120             int fieldSize = payload.getShort() & 0xFFFF;
121 
122             // Quick check
123             if (payload.position() + fieldSize > startPosition + size) {
124                 return null;
125             }
126 
127             switch (fieldId) {
128                 case SSID_FIELD_ID:
129                     byte[] ssid = new byte[fieldSize];
130                     payload.get(ssid);
131                     result.SSID = "\"" + new String(ssid) + "\"";
132                     break;
133                 case NETWORK_KEY_FIELD_ID:
134                     if (fieldSize > MAX_NETWORK_KEY_SIZE_BYTES) {
135                         return null;
136                     }
137                     byte[] networkKey = new byte[fieldSize];
138                     payload.get(networkKey);
139                     if (fieldSize > 0) {
140                         result.preSharedKey = getPskValidFormat(new String(networkKey));
141                     }
142                     break;
143                 case AUTH_TYPE_FIELD_ID:
144                     if (fieldSize != AUTH_TYPE_EXPECTED_SIZE) {
145                         // corrupt data
146                         return null;
147                     }
148 
149                     short authType = payload.getShort();
150                     populateAllowedKeyManagement(result.allowedKeyManagement, authType);
151                     break;
152                 default:
153                     // unknown / unparsed tag
154                     payload.position(payload.position() + fieldSize);
155                     break;
156             }
157         }
158 
159         if (result.SSID != null) {
160             if (result.getAuthType() == WifiConfiguration.KeyMgmt.NONE) {
161                 if (result.preSharedKey == null) {
162                     return result;
163                 }
164             } else {
165                 if (result.preSharedKey != null) {
166                     return result;
167                 }
168             }
169         }
170 
171         return null;
172     }
173 
populateAllowedKeyManagement(BitSet allowedKeyManagement, short authType)174     private static void populateAllowedKeyManagement(BitSet allowedKeyManagement, short authType) {
175         if (authType == AUTH_TYPE_WPA_PSK || authType == AUTH_TYPE_WPA2_PSK
176                 || authType == AUTH_TYPE_WPA_AND_WPA2_PSK) {
177             allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
178         } else if (authType == AUTH_TYPE_WPA_EAP || authType == AUTH_TYPE_WPA2_EAP) {
179             allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
180         } else if (authType == AUTH_TYPE_OPEN) {
181             allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
182         }
183     }
184 
getPskValidFormat(String data)185     private static String getPskValidFormat(String data) {
186         if (!data.matches("[0-9A-Fa-f]{64}")) { // if not HEX string
187             data = convertToQuotedString(data);
188         }
189         return data;
190     }
191 
convertToQuotedString(String str)192     private static String convertToQuotedString(String str) {
193         return '"' + str + '"';
194     }
195 }
196