summaryrefslogtreecommitdiffstats
path: root/service/java/com/android/server/wifi/CarrierNetworkConfig.java
blob: 20aac5bc113577c75551cbf216a39db999be4be5 (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
/*
 * Copyright (C) 2017 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;

import android.annotation.NonNull;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.net.wifi.EAPConstants;
import android.net.wifi.WifiEnterpriseConfig;
import android.os.Handler;
import android.os.Looper;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
import android.telephony.ImsiEncryptionInfo;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Class for maintaining/caching carrier Wi-Fi network configurations.
 */
public class CarrierNetworkConfig {
    private static final String TAG = "CarrierNetworkConfig";

    private static final String NETWORK_CONFIG_SEPARATOR = ",";
    private static final int ENCODED_SSID_INDEX = 0;
    private static final int EAP_TYPE_INDEX = 1;
    private static final int CONFIG_ELEMENT_SIZE = 2;

    private static final Uri CONTENT_URI = Uri.parse("content://carrier_information/carrier");

    private boolean mDbg = false;

    private final Map<String, NetworkInfo> mCarrierNetworkMap;
    private boolean mIsCarrierImsiEncryptionInfoAvailable = false;
    private int mBase64EncodingMethod = Base64.DEFAULT;
    private int mEapIdentitySequence = IDENTITY_SEQUENCE_IMSI_V1_0;
    private ImsiEncryptionInfo mLastImsiEncryptionInfo = null; // used for dumpsys only

    // RFC2045: adds Line Feed at each 76 chars and encode it.
    public static final int ENCODING_METHOD_RFC_2045 = 2045;

    // RFC4648: encodes whole data into one string.
    public static final int ENCODING_METHOD_RFC_4648 = 4648;

    // Send encrypted IMSI with the format of V1.0
    // V1.0 format: "\0"|<encrypted IMSI>|@NAIRealm
    // <encrypted IMSI>: Base64{RSA Public Key Encryption{<permanent ID>}}
    // <permanent ID>: One char ("0" for AKA, "1" for SIM, "6" for AKA')|IMSI
    public static final int IDENTITY_SEQUENCE_IMSI_V1_0 = 1;

    // Send anonymous identity and encrypted IMSI identity with the format of V1.0
    public static final int IDENTITY_SEQUENCE_ANONYMOUS_THEN_IMSI_V1_0 = 2;

    // Send anonymous identity and encrypted IMSI identity with the format of V1.6
    // V1.6 format: "\0"|<encrypted identity>
    // <encrypted identity>: Base64{RSA Public Key Encryption{<permanent ID>}}.
    // <permanent ID>: One char ("0" for AKA, "1" for SIM, "6" for AKA')|IMSI|@NAIRealm
    public static final int IDENTITY_SEQUENCE_ANONYMOUS_THEN_IMSI_V1_6 = 3;

    /**
     * Enable/disable verbose logging.
     */
    public void enableVerboseLogging(int verbose) {
        mDbg = verbose > 0;
    }

    public CarrierNetworkConfig(@NonNull Context context, @NonNull Looper looper,
            @NonNull FrameworkFacade framework) {
        mCarrierNetworkMap = new HashMap<>();
        updateNetworkConfig(context);

        // Monitor for carrier config changes.
        IntentFilter filter = new IntentFilter();
        filter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateNetworkConfig(context);
            }
        }, filter);

        framework.registerContentObserver(context, CONTENT_URI, false,
                new ContentObserver(new Handler(looper)) {
                @Override
                public void onChange(boolean selfChange) {
                    updateNetworkConfig(context);
                }
            });
    }

    /**
     * @return true if the given SSID is associated with a carrier network
     */
    public boolean isCarrierNetwork(String ssid) {
        return mCarrierNetworkMap.containsKey(ssid);
    }

    /**
     * @return the EAP type associated with a carrier AP, or -1 if the specified AP
     * is not associated with a carrier network
     */
    public int getNetworkEapType(String ssid) {
        NetworkInfo info = mCarrierNetworkMap.get(ssid);
        return info == null ? -1 : info.mEapType;
    }

    /**
     * @return the name of carrier associated with a carrier AP, or null if the specified AP
     * is not associated with a carrier network.
     */
    public String getCarrierName(String ssid) {
        NetworkInfo info = mCarrierNetworkMap.get(ssid);
        return info == null ? null : info.mCarrierName;
    }

    /**
     * @return the base64 encoding flag for current carrier.
     */
    public int getBase64EncodingFlag() {
        return mBase64EncodingMethod;
    }

    /**
     * @return the sequence of sending EAP-IDENTITY during EAP SIM/AKA authentication.
     */
    public int getEapIdentitySequence() {
        return mEapIdentitySequence;
    }

    /**
     * @return {@code true} if current carrier wifi network supports anonymous identity, {@code
     * false} otherwise.
     */
    public boolean isSupportAnonymousIdentity() {
        return mEapIdentitySequence == IDENTITY_SEQUENCE_ANONYMOUS_THEN_IMSI_V1_0
                || mEapIdentitySequence == IDENTITY_SEQUENCE_ANONYMOUS_THEN_IMSI_V1_6;
    }

    /**
     * @return True if carrier IMSI encryption info is available, False otherwise.
     */
    public boolean isCarrierEncryptionInfoAvailable() {
        return mIsCarrierImsiEncryptionInfoAvailable;
    }

    /**
     * Verify whether carrier IMSI encryption info is available.
     *
     * @param context Current application context
     *
     * @return True if carrier IMSI encryption info is available, False otherwise.
     */
    private boolean verifyCarrierImsiEncryptionInfoIsAvailable(Context context) {
        // TODO(b/132188983): Inject this using WifiInjector
        TelephonyManager telephonyManager =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager == null) {
            return false;
        }
        try {
            mLastImsiEncryptionInfo = telephonyManager
                    .createForSubscriptionId(SubscriptionManager.getDefaultDataSubscriptionId())
                    .getCarrierInfoForImsiEncryption(TelephonyManager.KEY_TYPE_WLAN);
            if (mLastImsiEncryptionInfo == null) {
                return false;
            }
        } catch (RuntimeException e) {
            Log.e(TAG, "Failed to get imsi encryption info: " + e.getMessage());
            return false;
        }

        return true;
    }

    /**
     * Utility class for storing carrier network information.
     */
    private static class NetworkInfo {
        final int mEapType;
        final String mCarrierName;

        NetworkInfo(int eapType, String carrierName) {
            mEapType = eapType;
            mCarrierName = carrierName;
        }

        @Override
        public String toString() {
            return new StringBuffer("NetworkInfo: eap=").append(mEapType).append(
                    ", carrier=").append(mCarrierName).toString();
        }
    }

    /**
     * Update the carrier network map based on the current carrier configuration of the active
     * subscriptions.
     *
     * @param context Current application context
     */
    private void updateNetworkConfig(Context context) {
        mIsCarrierImsiEncryptionInfoAvailable = verifyCarrierImsiEncryptionInfoIsAvailable(context);

        // Reset network map.
        mCarrierNetworkMap.clear();

        CarrierConfigManager carrierConfigManager =
                (CarrierConfigManager) context.getSystemService(Context.CARRIER_CONFIG_SERVICE);
        if (carrierConfigManager == null) {
            return;
        }

        SubscriptionManager subscriptionManager = (SubscriptionManager) context.getSystemService(
                Context.TELEPHONY_SUBSCRIPTION_SERVICE);
        if (subscriptionManager == null) {
            return;
        }
        List<SubscriptionInfo> subInfoList = subscriptionManager.getActiveSubscriptionInfoList();
        if (subInfoList == null) {
            return;
        }

        // Process the carrier config for each active subscription.
        for (SubscriptionInfo subInfo : subInfoList) {
            CharSequence displayNameCs = subInfo.getDisplayName();
            String displayNameStr = displayNameCs == null ? "" : displayNameCs.toString();
            PersistableBundle bundle = carrierConfigManager.getConfigForSubId(
                    subInfo.getSubscriptionId());
            processNetworkConfig(bundle, displayNameStr);
        }
    }

    /**
     * Process the carrier network config, the network config string is formatted as follow:
     *
     * "[Base64 Encoded SSID],[EAP Type]"
     * Where EAP Type is the standard EAP method number, refer to
     * http://www.iana.org/assignments/eap-numbers/eap-numbers.xhtml for more info.

     * @param carrierConfig The bundle containing the carrier configuration
     * @param carrierName The display name of the associated carrier
     */
    private void processNetworkConfig(PersistableBundle carrierConfig, String carrierName) {
        if (carrierConfig == null) {
            return;
        }
        String[] networkConfigs = carrierConfig.getStringArray(
                CarrierConfigManager.KEY_CARRIER_WIFI_STRING_ARRAY);
        if (mDbg) {
            Log.v(TAG, "processNetworkConfig: networkConfigs="
                    + Arrays.deepToString(networkConfigs));
        }
        if (networkConfigs == null) {
            return;
        }

        int encodeMethod = carrierConfig.getInt(
                CarrierConfigManager.KEY_IMSI_ENCODING_METHOD_INT, ENCODING_METHOD_RFC_2045);
        if (encodeMethod != ENCODING_METHOD_RFC_2045 && encodeMethod != ENCODING_METHOD_RFC_4648) {
            Log.e(TAG, "Invalid encoding method type: " + encodeMethod);
            return;
        }
        mBase64EncodingMethod = Base64.DEFAULT;
        if (encodeMethod == ENCODING_METHOD_RFC_4648) {
            mBase64EncodingMethod = Base64.NO_WRAP;
        }

        int sequence = carrierConfig.getInt(CarrierConfigManager.KEY_EAP_IDENTITY_SEQUENCE_INT,
                IDENTITY_SEQUENCE_IMSI_V1_0);
        if (sequence != IDENTITY_SEQUENCE_IMSI_V1_0
                && sequence != IDENTITY_SEQUENCE_ANONYMOUS_THEN_IMSI_V1_0
                && sequence != IDENTITY_SEQUENCE_ANONYMOUS_THEN_IMSI_V1_6) {
            Log.e(TAG, "Invalid eap identity sequence: " + sequence);
            return;
        }
        mEapIdentitySequence = sequence;

        for (String networkConfig : networkConfigs) {
            String[] configArr = networkConfig.split(NETWORK_CONFIG_SEPARATOR);
            if (configArr.length != CONFIG_ELEMENT_SIZE) {
                Log.e(TAG, "Ignore invalid config: " + networkConfig);
                continue;
            }
            try {

                String ssid = new String(Base64.decode(
                        configArr[ENCODED_SSID_INDEX], mBase64EncodingMethod));
                int eapType = parseEapType(Integer.parseInt(configArr[EAP_TYPE_INDEX]));

                // Verify EAP type, must be a SIM based EAP type.
                if (eapType == -1) {
                    Log.e(TAG, "Invalid EAP type: " + configArr[EAP_TYPE_INDEX]);
                    continue;
                }
                mCarrierNetworkMap.put(ssid, new NetworkInfo(eapType, carrierName));
            } catch (NumberFormatException e) {
                Log.e(TAG, "Failed to parse EAP type: '" + configArr[EAP_TYPE_INDEX] + "' "
                        + e.getMessage());
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "Failed to decode SSID: '" + configArr[ENCODED_SSID_INDEX] + "' "
                        + e.getMessage());
            }
        }
    }

    /**
     * Convert a standard SIM-based EAP type (SIM, AKA, AKA') to the internal EAP type as defined in
     * {@link WifiEnterpriseConfig.Eap}. -1 will be returned if the given EAP type is not
     * SIM-based.
     *
     * @return SIM-based EAP type as defined in {@link WifiEnterpriseConfig.Eap}, or -1 if not
     * SIM-based EAP type
     */
    private static int parseEapType(int eapType) {
        if (eapType == EAPConstants.EAP_SIM) {
            return WifiEnterpriseConfig.Eap.SIM;
        } else if (eapType == EAPConstants.EAP_AKA) {
            return WifiEnterpriseConfig.Eap.AKA;
        } else if (eapType == EAPConstants.EAP_AKA_PRIME) {
            return WifiEnterpriseConfig.Eap.AKA_PRIME;
        }
        return -1;
    }

    /** Dump state. */
    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println(TAG + ": ");
        pw.println("mCarrierNetworkMap=" + mCarrierNetworkMap);
        pw.println("mIsCarrierImsiEncryptionInfoAvailable="
                + mIsCarrierImsiEncryptionInfoAvailable);
        pw.println("mBase64EncodingMethod=" + mBase64EncodingMethod);
        pw.println("mEapIdentitySequence=" + mEapIdentitySequence);
        pw.println("mLastImsiEncryptionInfo=" + mLastImsiEncryptionInfo);
    }
}