1 /*
2  * Copyright (C) 2019 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 android.net.MacAddress;
20 import android.net.wifi.WifiConfiguration;
21 import android.security.keystore.AndroidKeyStoreProvider;
22 import android.security.keystore.KeyGenParameterSpec;
23 import android.security.keystore.KeyProperties;
24 import android.util.Log;
25 
26 import java.nio.ByteBuffer;
27 import java.nio.charset.StandardCharsets;
28 import java.security.InvalidAlgorithmParameterException;
29 import java.security.InvalidKeyException;
30 import java.security.Key;
31 import java.security.KeyStore;
32 import java.security.KeyStoreException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.NoSuchProviderException;
35 import java.security.ProviderException;
36 import java.security.UnrecoverableKeyException;
37 import java.util.Arrays;
38 
39 import javax.crypto.KeyGenerator;
40 import javax.crypto.Mac;
41 import javax.crypto.SecretKey;
42 
43 /**
44  * Contains helper methods to support MAC randomization.
45  */
46 public class MacAddressUtil {
47     private static final String TAG = "MacAddressUtil";
48     private static final String MAC_RANDOMIZATION_ALIAS = "MacRandSecret";
49     private static final long MAC_ADDRESS_VALID_LONG_MASK = (1L << 48) - 1;
50     private static final long MAC_ADDRESS_LOCALLY_ASSIGNED_MASK = 1L << 41;
51     private static final long MAC_ADDRESS_MULTICAST_MASK = 1L << 40;
52 
53     /**
54      * Computes the persistent randomized MAC of the given configuration using the given
55      * hash function.
56      * @param config the WifiConfiguration to compute MAC address for
57      * @param hashFunction the hash function that will perform the MAC address computation.
58      * @return The persistent randomized MAC address or null if inputs are invalid.
59      */
calculatePersistentMacForConfiguration(WifiConfiguration config, Mac hashFunction)60     public MacAddress calculatePersistentMacForConfiguration(WifiConfiguration config,
61             Mac hashFunction) {
62         if (config == null || hashFunction == null) {
63             return null;
64         }
65         byte[] hashedBytes;
66         try {
67             hashedBytes = hashFunction.doFinal(config.getSsidAndSecurityTypeString()
68                     .getBytes(StandardCharsets.UTF_8));
69         } catch (ProviderException | IllegalStateException e) {
70             Log.e(TAG, "Failure in calculatePersistentMac", e);
71             return null;
72         }
73         ByteBuffer bf = ByteBuffer.wrap(hashedBytes);
74         long longFromSsid = bf.getLong();
75         /**
76          * Masks the generated long so that it represents a valid randomized MAC address.
77          * Specifically, this sets the locally assigned bit to 1, multicast bit to 0
78          */
79         longFromSsid &= MAC_ADDRESS_VALID_LONG_MASK;
80         longFromSsid |= MAC_ADDRESS_LOCALLY_ASSIGNED_MASK;
81         longFromSsid &= ~MAC_ADDRESS_MULTICAST_MASK;
82         bf.clear();
83         bf.putLong(0, longFromSsid);
84 
85         // MacAddress.fromBytes requires input of length 6, which is obtained from the
86         // last 6 bytes from the generated long.
87         MacAddress macAddress = MacAddress.fromBytes(Arrays.copyOfRange(bf.array(), 2, 8));
88         return macAddress;
89     }
90 
91     /**
92      * Retrieves a Hash function that could be used to calculate the persistent randomized MAC
93      * for a WifiConfiguration.
94      * @param uid the UID of the KeyStore to get the secret of the hash function from.
95      */
obtainMacRandHashFunction(int uid)96     public Mac obtainMacRandHashFunction(int uid) {
97         try {
98             KeyStore keyStore = AndroidKeyStoreProvider.getKeyStoreForUid(uid);
99             // tries to retrieve the secret, and generate a new one if it's unavailable.
100             Key key = keyStore.getKey(MAC_RANDOMIZATION_ALIAS, null);
101             if (key == null) {
102                 key = generateAndPersistNewMacRandomizationSecret(uid);
103             }
104             if (key == null) {
105                 Log.e(TAG, "Failed to generate secret for " + MAC_RANDOMIZATION_ALIAS);
106                 return null;
107             }
108             Mac result = Mac.getInstance("HmacSHA256");
109             result.init(key);
110             return result;
111         } catch (KeyStoreException | NoSuchAlgorithmException | InvalidKeyException
112                 | UnrecoverableKeyException | NoSuchProviderException e) {
113             Log.e(TAG, "Failure in obtainMacRandHashFunction", e);
114             return null;
115         }
116     }
117 
118     /**
119      * Generates and returns a secret key to use for Mac randomization.
120      * Will also persist the generated secret inside KeyStore, accessible in the
121      * future with KeyGenerator#getKey.
122      */
generateAndPersistNewMacRandomizationSecret(int uid)123     private SecretKey generateAndPersistNewMacRandomizationSecret(int uid) {
124         try {
125             KeyGenerator keyGenerator = KeyGenerator.getInstance(
126                     KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
127             keyGenerator.init(
128                     new KeyGenParameterSpec.Builder(MAC_RANDOMIZATION_ALIAS,
129                             KeyProperties.PURPOSE_SIGN)
130                             .setUid(uid)
131                             .build());
132             return keyGenerator.generateKey();
133         } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
134                 | NoSuchProviderException | ProviderException e) {
135             Log.e(TAG, "Failure in generateMacRandomizationSecret", e);
136             return null;
137         }
138     }
139 }
140