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.BackendBusyException; 22 import android.security.keystore.KeyGenParameterSpec; 23 import android.security.keystore.KeyProperties; 24 import android.util.Log; 25 26 import com.android.modules.utils.build.SdkLevel; 27 28 import java.nio.ByteBuffer; 29 import java.nio.charset.StandardCharsets; 30 import java.security.InvalidAlgorithmParameterException; 31 import java.security.InvalidKeyException; 32 import java.security.Key; 33 import java.security.KeyStore; 34 import java.security.KeyStoreException; 35 import java.security.NoSuchAlgorithmException; 36 import java.security.NoSuchProviderException; 37 import java.security.ProviderException; 38 import java.security.UnrecoverableKeyException; 39 import java.util.Arrays; 40 41 import javax.crypto.KeyGenerator; 42 import javax.crypto.Mac; 43 import javax.crypto.SecretKey; 44 45 /** 46 * Contains helper methods to support MAC randomization. 47 */ 48 public class MacAddressUtil { 49 private static final String TAG = "MacAddressUtil"; 50 private static final String MAC_RANDOMIZATION_ALIAS = "MacRandSecret"; 51 private static final String MAC_RANDOMIZATION_SAP_ALIAS = "MacRandSapSecret"; 52 private static final long MAC_ADDRESS_VALID_LONG_MASK = (1L << 48) - 1; 53 private static final long MAC_ADDRESS_LOCALLY_ASSIGNED_MASK = 1L << 41; 54 private static final long MAC_ADDRESS_MULTICAST_MASK = 1L << 40; 55 56 /** 57 * Computes the persistent randomized MAC using the given key and hash function. 58 * @param key the key to compute MAC address for 59 * @param hashFunction the hash function that will perform the MAC address computation. 60 * @return The persistent randomized MAC address or null if inputs are invalid. 61 */ calculatePersistentMac(String key, Mac hashFunction)62 public MacAddress calculatePersistentMac(String key, Mac hashFunction) { 63 if (key == null || hashFunction == null) { 64 return null; 65 } 66 byte[] hashedBytes; 67 try { 68 hashedBytes = hashFunction.doFinal(key.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 obtainMacRandHashFunctionInternal(int uid, String alias)91 private Mac obtainMacRandHashFunctionInternal(int uid, String alias) { 92 try { 93 KeyStore keyStore = AndroidKeyStoreProvider.getKeyStoreForUid(uid); 94 // tries to retrieve the secret, and generate a new one if it's unavailable. 95 Key key = keyStore.getKey(alias, null); 96 if (key == null) { 97 key = generateAndPersistNewMacRandomizationSecret(uid, alias); 98 } 99 if (key == null) { 100 Log.e(TAG, "Failed to generate secret for " + alias); 101 return null; 102 } 103 Mac result = Mac.getInstance("HmacSHA256"); 104 result.init(key); 105 return result; 106 } catch (KeyStoreException | NoSuchAlgorithmException | InvalidKeyException 107 | UnrecoverableKeyException | NoSuchProviderException e) { 108 Log.e(TAG, "Failure in obtainMacRandHashFunction", e); 109 return null; 110 } catch (Exception e) { 111 if (SdkLevel.isAtLeastS() && e instanceof BackendBusyException) { 112 Log.e(TAG, "Failure in obtainMacRandHashFunction", e); 113 return null; 114 } 115 Log.e(TAG, "Unexpected exception caught in obtainMacRandHashFunction", e); 116 throw e; 117 } 118 } 119 120 /** 121 * Retrieves a Hash function that could be used to calculate the persistent randomized MAC 122 * for a WifiConfiguration for client mode. 123 * @param uid the UID of the KeyStore to get the secret of the hash function from. 124 */ obtainMacRandHashFunction(int uid)125 public Mac obtainMacRandHashFunction(int uid) { 126 return obtainMacRandHashFunctionInternal(uid, MAC_RANDOMIZATION_ALIAS); 127 } 128 129 /** 130 * Retrieves a Hash function that could be used to calculate the persistent randomized MAC 131 * for a WifiConfiguration for Soft AP. 132 * @param uid the UID of the KeyStore to get the secret of the hash function from. 133 */ obtainMacRandHashFunctionForSap(int uid)134 public Mac obtainMacRandHashFunctionForSap(int uid) { 135 return obtainMacRandHashFunctionInternal(uid, MAC_RANDOMIZATION_SAP_ALIAS); 136 } 137 138 /** 139 * Generates and returns a secret key to use for Mac randomization. 140 * Will also persist the generated secret inside KeyStore, accessible in the 141 * future with KeyGenerator#getKey. 142 */ generateAndPersistNewMacRandomizationSecret(int uid, String alias)143 private SecretKey generateAndPersistNewMacRandomizationSecret(int uid, String alias) { 144 try { 145 KeyGenerator keyGenerator = KeyGenerator.getInstance( 146 KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore"); 147 keyGenerator.init( 148 new KeyGenParameterSpec.Builder(alias, 149 KeyProperties.PURPOSE_SIGN) 150 .setUid(uid) 151 .build()); 152 return keyGenerator.generateKey(); 153 } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException 154 | NoSuchProviderException | ProviderException e) { 155 Log.e(TAG, "Failure in generateMacRandomizationSecret", e); 156 return null; 157 } 158 } 159 } 160