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