blob: 018e41b7bef13b956179aaa93fb9587df67e4d0f [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 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
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070025import android.accounts.AccountManagerInternal;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070027import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080028import android.accounts.GrantCredentialsPermissionActivity;
29import android.accounts.IAccountAuthenticator;
30import android.accounts.IAccountAuthenticatorResponse;
31import android.accounts.IAccountManager;
32import android.accounts.IAccountManagerResponse;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070033import android.annotation.IntRange;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070034import android.annotation.NonNull;
Svet Ganovf6d424f12016-09-20 20:18:53 -070035import android.annotation.Nullable;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080036import android.app.ActivityManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070037import android.app.ActivityThread;
Svetoslavf3f02ac2015-09-08 14:36:35 -070038import android.app.AppOpsManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070039import android.app.INotificationManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070040import android.app.Notification;
41import android.app.NotificationManager;
42import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000043import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010044import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000045import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070046import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070047import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070048import android.content.Context;
49import android.content.Intent;
50import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070051import android.content.IntentSender;
Fred Quintanab839afc2009-10-14 15:57:28 -070052import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080053import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070054import android.content.pm.ApplicationInfo;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070055import android.content.pm.IPackageManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070057import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070058import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070060import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070061import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070062import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070063import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070064import android.database.Cursor;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070065import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070066import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080068import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.IBinder;
71import android.os.Looper;
72import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070073import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070074import android.os.Process;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070075import android.os.RemoteCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -070076import android.os.RemoteException;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080077import android.os.StrictMode;
Fred Quintanaa698f422009-04-08 19:14:54 -070078import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070079import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070080import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import android.text.TextUtils;
82import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070083import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070084import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080085import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070086import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070087
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070088import com.android.internal.R;
Svet Ganov5d09c992016-09-07 09:57:41 -070089import com.android.internal.annotations.GuardedBy;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070090import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070091import com.android.internal.content.PackageMonitor;
Chris Wren282cfef2017-03-27 15:01:44 -040092import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050093import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani67df64b2012-12-14 12:09:36 -080094import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060095import com.android.internal.util.DumpUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080096import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -070097import com.android.internal.util.Preconditions;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000098import com.android.server.LocalServices;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -070099import com.android.server.ServiceThread;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600100import com.android.server.SystemService;
101
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700102import com.google.android.collect.Lists;
103import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700104
Oscar Montemayora8529f62009-11-18 10:14:20 -0800105import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700106import java.io.FileDescriptor;
107import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800108import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700109import java.security.MessageDigest;
110import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700111import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700112import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800113import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700114import java.util.Collection;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700115import java.util.Collections;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700116import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700117import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700118import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800119import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700120import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800121import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800122import java.util.Map.Entry;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700123import java.util.Objects;
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700124import java.util.Set;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700125import java.util.UUID;
Svet Ganovf6d424f12016-09-20 20:18:53 -0700126import java.util.concurrent.CopyOnWriteArrayList;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700127import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700128
Fred Quintana60307342009-03-24 22:48:12 -0700129/**
130 * A system service that provides account, password, and authtoken management for all
131 * accounts on the device. Some of these calls are implemented with the help of the corresponding
132 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
133 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700134 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700135 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700136 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700137public class AccountManagerService
138 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800139 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700140 private static final String TAG = "AccountManagerService";
141
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600142 public static class Lifecycle extends SystemService {
143 private AccountManagerService mService;
144
145 public Lifecycle(Context context) {
146 super(context);
147 }
148
149 @Override
150 public void onStart() {
Fyodor Kupolovda993802016-09-21 14:47:10 -0700151 mService = new AccountManagerService(new Injector(getContext()));
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600152 publishBinderService(Context.ACCOUNT_SERVICE, mService);
153 }
154
155 @Override
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600156 public void onUnlockUser(int userHandle) {
157 mService.onUnlockUser(userHandle);
158 }
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700159
160 @Override
161 public void onCleanupUser(int userHandle) {
162 mService.onCleanupUser(userHandle);
163 }
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600164 }
165
Svet Ganov5d09c992016-09-07 09:57:41 -0700166 final Context mContext;
Fred Quintana60307342009-03-24 22:48:12 -0700167
Fred Quintana56285a62010-12-02 14:20:51 -0800168 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700169 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700170 private UserManager mUserManager;
Fyodor Kupolovda993802016-09-21 14:47:10 -0700171 private final Injector mInjector;
Fred Quintana56285a62010-12-02 14:20:51 -0800172
Svet Ganov5d09c992016-09-07 09:57:41 -0700173 final MessageHandler mHandler;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700174
Fred Quintana60307342009-03-24 22:48:12 -0700175 // Messages that can be sent on mHandler
176 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700177 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700178
Fred Quintana56285a62010-12-02 14:20:51 -0800179 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700180 private static final String PRE_N_DATABASE_NAME = "accounts.db";
Fred Quintana7be59642009-08-24 18:29:25 -0700181 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800182
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800183 private static final int SIGNATURE_CHECK_MISMATCH = 0;
184 private static final int SIGNATURE_CHECK_MATCH = 1;
185 private static final int SIGNATURE_CHECK_UID_MATCH = 2;
186
Carlos Valdivia91979be2015-05-22 14:11:35 -0700187 static {
188 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Christopher Tatebded68f2017-02-21 11:41:55 -0800189 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
190 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700191 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700192
193 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700194
Amith Yamasani04e0d262012-02-14 11:50:53 -0800195 static class UserAccounts {
196 private final int userId;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700197 final AccountsDb accountsDb;
Chris Wren717a8812017-03-31 15:34:39 -0400198 private final HashMap<Pair<Pair<Account, String>, Integer>, NotificationId>
199 credentialsPermissionNotificationIds = new HashMap<>();
200 private final HashMap<Account, NotificationId> signinRequiredNotificationIds
201 = new HashMap<>();
Svet Ganov5d09c992016-09-07 09:57:41 -0700202 final Object cacheLock = new Object();
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700203 final Object dbLock = new Object(); // if needed, dbLock must be obtained before cacheLock
Amith Yamasani04e0d262012-02-14 11:50:53 -0800204 /** protected by the {@link #cacheLock} */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700205 final HashMap<String, Account[]> accountCache = new LinkedHashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800206 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700207 private final Map<Account, Map<String, String>> userDataCache = new HashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800208 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700209 private final Map<Account, Map<String, String>> authTokenCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700210 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700211 private final TokenCache accountTokenCaches = new TokenCache();
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700212 /** protected by the {@link #cacheLock} */
213 private final Map<Account, Map<String, Integer>> visibilityCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700214
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700215 /** protected by the {@link #mReceiversForType},
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700216 * type -> (packageName -> number of active receivers)
217 * type == null is used to get notifications about all account types
218 */
219 private final Map<String, Map<String, Integer>> mReceiversForType = new HashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800220
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700221 /**
222 * protected by the {@link #cacheLock}
223 *
224 * Caches the previous names associated with an account. Previous names
225 * should be cached because we expect that when an Account is renamed,
226 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
227 * want to know if the accounts they care about have been renamed.
228 *
229 * The previous names are wrapped in an {@link AtomicReference} so that
230 * we can distinguish between those accounts with no previous names and
231 * those whose previous names haven't been cached (yet).
232 */
233 private final HashMap<Account, AtomicReference<String>> previousNameCache =
234 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800235
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700236 private int debugDbInsertionPoint = -1;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700237 private SQLiteStatement statementForLogging; // TODO Move to AccountsDb
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700238
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700239 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800240 this.userId = userId;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700241 synchronized (dbLock) {
242 synchronized (cacheLock) {
243 accountsDb = AccountsDb.create(context, userId, preNDbFile, deDbFile);
244 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800245 }
246 }
247 }
248
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700249 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600250 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -0700251 // Not thread-safe. Only use in synchronized context
252 private final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Svet Ganovf6d424f12016-09-20 20:18:53 -0700253 private CopyOnWriteArrayList<AccountManagerInternal.OnAppPermissionChangeListener>
254 mAppPermissionChangeListeners = new CopyOnWriteArrayList<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800255
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700256 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700257 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700258
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700259 /**
260 * This should only be called by system code. One should only call this after the service
261 * has started.
262 * @return a reference to the AccountManagerService instance
263 * @hide
264 */
265 public static AccountManagerService getSingleton() {
266 return sThis.get();
267 }
Fred Quintana60307342009-03-24 22:48:12 -0700268
Fyodor Kupolovda993802016-09-21 14:47:10 -0700269 public AccountManagerService(Injector injector) {
270 mInjector = injector;
271 mContext = injector.getContext();
272 mPackageManager = mContext.getPackageManager();
Svetoslavf3f02ac2015-09-08 14:36:35 -0700273 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fyodor Kupolovda993802016-09-21 14:47:10 -0700274 mHandler = new MessageHandler(injector.getMessageHandlerLooper());
275 mAuthenticatorCache = mInjector.getAccountAuthenticatorCache();
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800276 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700277
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700278 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800279
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800280 IntentFilter intentFilter = new IntentFilter();
281 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
282 intentFilter.addDataScheme("package");
283 mContext.registerReceiver(new BroadcastReceiver() {
284 @Override
285 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700286 // Don't delete accounts when updating a authenticator's
287 // package.
288 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700289 /* Purging data requires file io, don't block the main thread. This is probably
290 * less than ideal because we are introducing a race condition where old grants
291 * could be exercised until they are purged. But that race condition existed
292 * anyway with the broadcast receiver.
293 *
294 * Ideally, we would completely clear the cache, purge data from the database,
295 * and then rebuild the cache. All under the cache lock. But that change is too
296 * large at this point.
297 */
Dmitry Dementyev0b676422017-03-09 11:51:26 -0800298 final String removedPackageName = intent.getData().getSchemeSpecificPart();
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700299 Runnable purgingRunnable = new Runnable() {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700300 @Override
301 public void run() {
302 purgeOldGrantsAll();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800303 // Notify authenticator about removed app?
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800304 removeVisibilityValuesForPackage(removedPackageName);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700305 }
306 };
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700307 mHandler.post(purgingRunnable);
Carlos Valdivia23f58262014-09-05 10:52:41 -0700308 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800309 }
310 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800311
Fyodor Kupolovda993802016-09-21 14:47:10 -0700312 injector.addLocalService(new AccountManagerInternalImpl());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700313
314 // Need to cancel account request notifications if the update/install can access the account
315 new PackageMonitor() {
316 @Override
317 public void onPackageAdded(String packageName, int uid) {
318 // Called on a handler, and running as the system
319 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
320 }
321
322 @Override
323 public void onPackageUpdateFinished(String packageName, int uid) {
324 // Called on a handler, and running as the system
325 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
326 }
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700327 }.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700328
329 // Cancel account request notification if an app op was preventing the account access
330 mAppOpsManager.startWatchingMode(AppOpsManager.OP_GET_ACCOUNTS, null,
331 new AppOpsManager.OnOpChangedInternalListener() {
332 @Override
333 public void onOpChanged(int op, String packageName) {
334 try {
335 final int userId = ActivityManager.getCurrentUser();
336 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
337 final int mode = mAppOpsManager.checkOpNoThrow(
338 AppOpsManager.OP_GET_ACCOUNTS, uid, packageName);
339 if (mode == AppOpsManager.MODE_ALLOWED) {
340 final long identity = Binder.clearCallingIdentity();
341 try {
342 cancelAccountAccessRequestNotificationIfNeeded(packageName, uid, true);
343 } finally {
344 Binder.restoreCallingIdentity(identity);
345 }
346 }
347 } catch (NameNotFoundException e) {
348 /* ignore */
349 }
350 }
351 });
352
353 // Cancel account request notification if a permission was preventing the account access
354 mPackageManager.addOnPermissionsChangeListener(
355 (int uid) -> {
356 Account[] accounts = null;
357 String[] packageNames = mPackageManager.getPackagesForUid(uid);
358 if (packageNames != null) {
359 final int userId = UserHandle.getUserId(uid);
360 final long identity = Binder.clearCallingIdentity();
361 try {
362 for (String packageName : packageNames) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800363 // if app asked for permission we need to cancel notification even
364 // for O+ applications.
365 if (mPackageManager.checkPermission(
366 Manifest.permission.GET_ACCOUNTS,
367 packageName) != PackageManager.PERMISSION_GRANTED) {
368 continue;
369 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700370
371 if (accounts == null) {
372 accounts = getAccountsAsUser(null, userId, "android");
373 if (ArrayUtils.isEmpty(accounts)) {
374 return;
375 }
376 }
377
378 for (Account account : accounts) {
379 cancelAccountAccessRequestNotificationIfNeeded(
380 account, uid, packageName, true);
381 }
382 }
383 } finally {
384 Binder.restoreCallingIdentity(identity);
385 }
386 }
387 });
388 }
389
390 private void cancelAccountAccessRequestNotificationIfNeeded(int uid,
391 boolean checkAccess) {
392 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
393 for (Account account : accounts) {
394 cancelAccountAccessRequestNotificationIfNeeded(account, uid, checkAccess);
395 }
396 }
397
398 private void cancelAccountAccessRequestNotificationIfNeeded(String packageName, int uid,
399 boolean checkAccess) {
400 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
401 for (Account account : accounts) {
402 cancelAccountAccessRequestNotificationIfNeeded(account, uid, packageName, checkAccess);
403 }
404 }
405
406 private void cancelAccountAccessRequestNotificationIfNeeded(Account account, int uid,
407 boolean checkAccess) {
408 String[] packageNames = mPackageManager.getPackagesForUid(uid);
409 if (packageNames != null) {
410 for (String packageName : packageNames) {
411 cancelAccountAccessRequestNotificationIfNeeded(account, uid,
412 packageName, checkAccess);
413 }
414 }
415 }
416
417 private void cancelAccountAccessRequestNotificationIfNeeded(Account account,
418 int uid, String packageName, boolean checkAccess) {
419 if (!checkAccess || hasAccountAccess(account, packageName,
420 UserHandle.getUserHandleForUid(uid))) {
421 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -0700422 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700423 UserHandle.getUserHandleForUid(uid));
424 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800425 }
426
Dianne Hackborn164371f2013-10-01 19:10:13 -0700427 @Override
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800428 public boolean addAccountExplicitlyWithVisibility(Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800429 Bundle extras, Map packageToVisibility) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800430 Bundle.setDefusable(extras, true);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700431 int callingUid = Binder.getCallingUid();
432 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800433 if (Log.isLoggable(TAG, Log.VERBOSE)) {
434 Log.v(TAG, "addAccountExplicitly: " + account + ", caller's uid " + callingUid
435 + ", pid " + Binder.getCallingPid());
436 }
437 Preconditions.checkNotNull(account, "account cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800438 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
439 String msg = String.format("uid %s cannot explicitly add accounts of type: %s",
440 callingUid, account.type);
441 throw new SecurityException(msg);
442 }
443 /*
444 * Child users are not allowed to add accounts. Only the accounts that are shared by the
445 * parent profile can be added to child profile.
446 *
447 * TODO: Only allow accounts that were shared to be added by a limited user.
448 */
449 // fails if the account already exists
450 long identityToken = clearCallingIdentity();
451 try {
452 UserAccounts accounts = getUserAccounts(userId);
453 return addAccountInternal(accounts, account, password, extras, callingUid,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800454 (Map<String, Integer>) packageToVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800455 } finally {
456 restoreCallingIdentity(identityToken);
457 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700458 }
459
460 @Override
Dmitry Dementyev52745472016-12-02 10:27:45 -0800461 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
462 String accountType) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800463 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700464 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800465 boolean isSystemUid = UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700466 List<String> managedTypes = getTypesForCaller(callingUid, userId, isSystemUid);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800467
468 if ((accountType != null && !managedTypes.contains(accountType))
469 || (accountType == null && !isSystemUid)) {
470 throw new SecurityException(
471 "getAccountsAndVisibilityForPackage() called from unauthorized uid "
472 + callingUid + " with packageName=" + packageName);
473 }
474 if (accountType != null) {
475 managedTypes = new ArrayList<String>();
476 managedTypes.add(accountType);
477 }
478
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800479 long identityToken = clearCallingIdentity();
480 try {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700481 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800482 return getAccountsAndVisibilityForPackage(packageName, managedTypes, callingUid,
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700483 accounts);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800484 } finally {
485 restoreCallingIdentity(identityToken);
486 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800487 }
488
489 /*
490 * accountTypes may not be null
491 */
492 private Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
493 List<String> accountTypes, Integer callingUid, UserAccounts accounts) {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700494 if (!packageExistsForUser(packageName, accounts.userId)) {
495 Log.d(TAG, "Package not found " + packageName);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800496 return new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800497 }
498
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800499 Map<Account, Integer> result = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800500 for (String accountType : accountTypes) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700501 synchronized (accounts.dbLock) {
502 synchronized (accounts.cacheLock) {
503 final Account[] accountsOfType = accounts.accountCache.get(accountType);
504 if (accountsOfType != null) {
505 for (Account account : accountsOfType) {
506 result.put(account,
507 resolveAccountVisibility(account, packageName, accounts));
508 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800509 }
510 }
511 }
512 }
513 return filterSharedAccounts(accounts, result, callingUid, packageName);
Dmitry Dementyev52745472016-12-02 10:27:45 -0800514 }
515
516 @Override
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800517 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700518 Preconditions.checkNotNull(account, "account cannot be null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700519 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700520 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800521 if (!isAccountManagedByCaller(account.type, callingUid, userId)
522 && !isSystemUid(callingUid)) {
523 String msg =
524 String.format("uid %s cannot get secrets for account %s", callingUid, account);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700525 throw new SecurityException(msg);
526 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700527
528 long identityToken = clearCallingIdentity();
529 try {
530 UserAccounts accounts = getUserAccounts(userId);
531 synchronized (accounts.dbLock) {
532 synchronized (accounts.cacheLock) {
533 return getPackagesAndVisibilityForAccountLocked(account, accounts);
534 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700535 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700536 } finally {
537 restoreCallingIdentity(identityToken);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700538 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700539
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800540 }
541
542 /**
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700543 * Returns Map with all package names and visibility values for given account.
544 * The method and returned map must be guarded by accounts.cacheLock
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800545 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800546 * @param account Account to get visibility values.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800547 * @param accounts UserAccount that currently hosts the account and application
548 *
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700549 * @return Map with cache for package names to visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800550 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700551 private @NonNull Map<String, Integer> getPackagesAndVisibilityForAccountLocked(Account account,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800552 UserAccounts accounts) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700553 Map<String, Integer> accountVisibility = accounts.visibilityCache.get(account);
554 if (accountVisibility == null) {
555 Log.d(TAG, "Visibility was not initialized");
556 accountVisibility = new HashMap<>();
557 accounts.visibilityCache.put(account, accountVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800558 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700559 return accountVisibility;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700560 }
561
562 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700563 public int getAccountVisibility(Account account, String packageName) {
564 Preconditions.checkNotNull(account, "account cannot be null");
565 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800566 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700567 int userId = UserHandle.getCallingUserId();
568 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800569 && !isSystemUid(callingUid)) {
570 String msg = String.format(
571 "uid %s cannot get secrets for accounts of type: %s",
572 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700573 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800574 throw new SecurityException(msg);
575 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700576 long identityToken = clearCallingIdentity();
577 try {
578 UserAccounts accounts = getUserAccounts(userId);
579 return resolveAccountVisibility(account, packageName, accounts);
580 } finally {
581 restoreCallingIdentity(identityToken);
582 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800583 }
584
585 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800586 * Method returns visibility for given account and package name.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800587 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800588 * @param account The account to check visibility.
589 * @param packageName Package name to check visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800590 * @param accounts UserAccount that currently hosts the account and application
591 *
592 * @return Visibility value, AccountManager.VISIBILITY_UNDEFINED if no value was stored.
593 *
594 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700595 private int getAccountVisibilityFromCache(Account account, String packageName,
596 UserAccounts accounts) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700597 synchronized (accounts.cacheLock) {
598 Map<String, Integer> accountVisibility =
599 getPackagesAndVisibilityForAccountLocked(account, accounts);
600 Integer visibility = accountVisibility.get(packageName);
601 return visibility != null ? visibility : AccountManager.VISIBILITY_UNDEFINED;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800602 }
603 }
604
605 /**
606 * Method which handles default values for Account visibility.
607 *
608 * @param account The account to check visibility.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800609 * @param packageName Package name to check visibility
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800610 * @param accounts UserAccount that currently hosts the account and application
611 *
612 * @return Visibility value, the method never returns AccountManager.VISIBILITY_UNDEFINED
613 *
614 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800615 private Integer resolveAccountVisibility(Account account, @NonNull String packageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800616 UserAccounts accounts) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800617 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800618 int uid = -1;
619 try {
620 long identityToken = clearCallingIdentity();
621 try {
622 uid = mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
623 } finally {
624 restoreCallingIdentity(identityToken);
625 }
626 } catch (NameNotFoundException e) {
627 Log.d(TAG, "Package not found " + e.getMessage());
628 return AccountManager.VISIBILITY_NOT_VISIBLE;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800629 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800630
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800631 // System visibility can not be restricted.
632 if (UserHandle.isSameApp(uid, Process.SYSTEM_UID)) {
633 return AccountManager.VISIBILITY_VISIBLE;
634 }
635
636 int signatureCheckResult =
637 checkPackageSignature(account.type, uid, accounts.userId);
638
639 // Authenticator can not restrict visibility to itself.
640 if (signatureCheckResult == SIGNATURE_CHECK_UID_MATCH) {
641 return AccountManager.VISIBILITY_VISIBLE; // Authenticator can always see the account
642 }
643
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800644 if (isSpecialPackageKey(packageName)) {
645 Log.d(TAG, "Package name is forbidden: " + packageName);
646 return AccountManager.VISIBILITY_NOT_VISIBLE;
647 }
648
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800649 // Return stored value if it was set.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700650 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800651
652 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
653 return visibility;
654 }
655
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700656 boolean isPrivileged = isPermittedForPackage(packageName, uid, accounts.userId,
Dmitry Dementyevf794c8d2017-02-03 18:17:59 -0800657 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
658
659 // Device/Profile owner gets visibility by default.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800660 if (isProfileOwner(uid)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800661 return AccountManager.VISIBILITY_VISIBLE;
662 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800663
664 boolean preO = isPreOApplication(packageName);
665 if ((signatureCheckResult != SIGNATURE_CHECK_MISMATCH)
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700666 || (preO && checkGetAccountsPermission(packageName, uid, accounts.userId))
667 || (checkReadContactsPermission(packageName, uid, accounts.userId)
668 && accountTypeManagesContacts(account.type, accounts.userId))
669 || isPrivileged) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800670 // Use legacy for preO apps with GET_ACCOUNTS permission or pre/postO with signature
671 // match.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700672 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800673 AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800674 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
675 visibility = AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
676 }
677 } else {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700678 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800679 AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800680 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
681 visibility = AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
682 }
683 }
684 return visibility;
685 }
686
687 /**
688 * Checks targetSdk for a package;
689 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800690 * @param packageName Package name
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800691 *
692 * @return True if package's target SDK is below {@link android.os.Build.VERSION_CODES#O}, or
693 * undefined
694 */
695 private boolean isPreOApplication(String packageName) {
696 try {
697 long identityToken = clearCallingIdentity();
698 ApplicationInfo applicationInfo;
699 try {
700 applicationInfo = mPackageManager.getApplicationInfo(packageName, 0);
701 } finally {
702 restoreCallingIdentity(identityToken);
703 }
704
705 if (applicationInfo != null) {
706 int version = applicationInfo.targetSdkVersion;
707 return version < android.os.Build.VERSION_CODES.O;
708 }
709 return true;
710 } catch (NameNotFoundException e) {
711 Log.d(TAG, "Package not found " + e.getMessage());
712 return true;
713 }
Dmitry Dementyev58fa83622016-12-20 18:08:51 -0800714 }
715
716 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700717 public boolean setAccountVisibility(Account account, String packageName, int newVisibility) {
718 Preconditions.checkNotNull(account, "account cannot be null");
719 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800720 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700721 int userId = UserHandle.getCallingUserId();
722 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800723 && !isSystemUid(callingUid)) {
724 String msg = String.format(
725 "uid %s cannot get secrets for accounts of type: %s",
726 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700727 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800728 throw new SecurityException(msg);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700729 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700730 long identityToken = clearCallingIdentity();
731 try {
732 UserAccounts accounts = getUserAccounts(userId);
733 return setAccountVisibility(account, packageName, newVisibility, true /* notify */,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700734 accounts);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700735 } finally {
736 restoreCallingIdentity(identityToken);
737 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700738 }
739
740 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800741 * Updates visibility for given account name and package.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700742 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800743 * @param account Account to update visibility.
744 * @param packageName Package name for which visibility is updated.
745 * @param newVisibility New visibility calue
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800746 * @param notify if the flag is set applications will get notification about visibility change
747 * @param accounts UserAccount that currently hosts the account and application
748 *
749 * @return True if account visibility was changed.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700750 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800751 private boolean setAccountVisibility(Account account, String packageName, int newVisibility,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800752 boolean notify, UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700753 synchronized (accounts.dbLock) {
754 synchronized (accounts.cacheLock) {
755 Map<String, Integer> packagesToVisibility;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700756 List<String> accountRemovedReceivers;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700757 if (notify) {
758 if (isSpecialPackageKey(packageName)) {
759 packagesToVisibility =
760 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700761 accountRemovedReceivers = getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700762 } else {
763 if (!packageExistsForUser(packageName, accounts.userId)) {
764 return false; // package is not installed.
765 }
766 packagesToVisibility = new HashMap<>();
767 packagesToVisibility.put(packageName,
768 resolveAccountVisibility(account, packageName, accounts));
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700769 accountRemovedReceivers = new ArrayList<>();
770 if (shouldNotifyPackageOnAccountRemoval(account, packageName, accounts)) {
771 accountRemovedReceivers.add(packageName);
772 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700773 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800774 } else {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700775 // Notifications will not be send - only used during add account.
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700776 if (!isSpecialPackageKey(packageName) &&
777 !packageExistsForUser(packageName, accounts.userId)) {
778 // package is not installed and not meta value.
779 return false;
Nicolas Prevotf7d8df12016-09-16 17:45:34 +0100780 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700781 packagesToVisibility = Collections.emptyMap();
782 accountRemovedReceivers = Collections.emptyList();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800783 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700784
785 if (!updateAccountVisibilityLocked(account, packageName, newVisibility, accounts)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800786 return false;
787 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800788
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700789 if (notify) {
790 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
791 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700792 if (shouldNotifyOnVisibilityChange(packageToVisibility.getValue(),
793 resolveAccountVisibility(account, packageName, accounts))) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700794 notifyPackage(packageToVisibility.getKey(), accounts);
795 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700796 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700797 for (String packageNameToNotify : accountRemovedReceivers) {
798 sendAccountRemovedBroadcast(account, packageNameToNotify, accounts.userId);
799 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700800 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700801 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700802 return true;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800803 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700804 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700805 }
806
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700807 // Update account visibility in cache and database.
808 private boolean updateAccountVisibilityLocked(Account account, String packageName,
809 int newVisibility, UserAccounts accounts) {
810 final long accountId = accounts.accountsDb.findDeAccountId(account);
811 if (accountId < 0) {
812 return false;
813 }
814
815 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
816 try {
817 if (!accounts.accountsDb.setAccountVisibility(accountId, packageName,
818 newVisibility)) {
819 return false;
820 }
821 } finally {
822 StrictMode.setThreadPolicy(oldPolicy);
823 }
824 Map<String, Integer> accountVisibility =
825 getPackagesAndVisibilityForAccountLocked(account, accounts);
826 accountVisibility.put(packageName, newVisibility);
827 return true;
828 }
829
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700830 @Override
831 public void registerAccountListener(String[] accountTypes, String opPackageName) {
832 int callingUid = Binder.getCallingUid();
833 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700834
835 int userId = UserHandle.getCallingUserId();
836 long identityToken = clearCallingIdentity();
837 try {
838 UserAccounts accounts = getUserAccounts(userId);
839 registerAccountListener(accountTypes, opPackageName, accounts);
840 } finally {
841 restoreCallingIdentity(identityToken);
842 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800843 }
844
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700845 private void registerAccountListener(String[] accountTypes, String opPackageName,
846 UserAccounts accounts) {
847 synchronized (accounts.mReceiversForType) {
848 if (accountTypes == null) {
849 // null for any type
850 accountTypes = new String[] {null};
851 }
852 for (String type : accountTypes) {
853 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
854 if (receivers == null) {
855 receivers = new HashMap<>();
856 accounts.mReceiversForType.put(type, receivers);
857 }
858 Integer cnt = receivers.get(opPackageName);
859 receivers.put(opPackageName, cnt != null ? cnt + 1 : 1);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800860 }
861 }
862 }
863
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700864 @Override
865 public void unregisterAccountListener(String[] accountTypes, String opPackageName) {
866 int callingUid = Binder.getCallingUid();
867 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700868 int userId = UserHandle.getCallingUserId();
869 long identityToken = clearCallingIdentity();
870 try {
871 UserAccounts accounts = getUserAccounts(userId);
872 unregisterAccountListener(accountTypes, opPackageName, accounts);
873 } finally {
874 restoreCallingIdentity(identityToken);
875 }
876 }
877
878 private void unregisterAccountListener(String[] accountTypes, String opPackageName,
879 UserAccounts accounts) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700880 synchronized (accounts.mReceiversForType) {
881 if (accountTypes == null) {
882 // null for any type
883 accountTypes = new String[] {null};
884 }
885 for (String type : accountTypes) {
886 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
887 if (receivers == null || receivers.get(opPackageName) == null) {
888 throw new IllegalArgumentException("attempt to unregister wrong receiver");
889 }
890 Integer cnt = receivers.get(opPackageName);
891 if (cnt == 1) {
892 receivers.remove(opPackageName);
893 } else {
894 receivers.put(opPackageName, cnt - 1);
895 }
896 }
897 }
898 }
899
900 // Send notification to all packages which can potentially see the account
901 private void sendNotificationAccountUpdated(Account account, UserAccounts accounts) {
902 Map<String, Integer> packagesToVisibility = getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700903
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700904 for (Entry<String, Integer> packageToVisibility : packagesToVisibility.entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700905 if ((packageToVisibility.getValue() != AccountManager.VISIBILITY_NOT_VISIBLE)
906 && (packageToVisibility.getValue()
907 != AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE)) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700908 notifyPackage(packageToVisibility.getKey(), accounts);
909 }
910 }
911 }
912
913 /**
914 * Sends a direct intent to a package, notifying it of account visibility change.
915 *
916 * @param packageName to send Account to
917 * @param accounts UserAccount that currently hosts the account
918 */
919 private void notifyPackage(String packageName, UserAccounts accounts) {
920 Intent intent = new Intent(AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED);
921 intent.setPackage(packageName);
922 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
923 mContext.sendBroadcastAsUser(intent, new UserHandle(accounts.userId));
924 }
925
926 // Returns a map from package name to visibility, for packages subscribed
927 // to notifications about any account type, or type of provided account
928 // account type or all types.
929 private Map<String, Integer> getRequestingPackages(Account account, UserAccounts accounts) {
930 Set<String> packages = new HashSet<>();
931 synchronized (accounts.mReceiversForType) {
932 for (String type : new String[] {account.type, null}) {
933 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
934 if (receivers != null) {
935 packages.addAll(receivers.keySet());
936 }
937 }
938 }
939 Map<String, Integer> result = new HashMap<>();
940 for (String packageName : packages) {
941 result.put(packageName, resolveAccountVisibility(account, packageName, accounts));
942 }
943 return result;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800944 }
945
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700946 // Returns a list of packages listening to ACTION_ACCOUNT_REMOVED able to see the account.
947 private List<String> getAccountRemovedReceivers(Account account, UserAccounts accounts) {
948 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
949 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
950 List<ResolveInfo> receivers =
951 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
952 List<String> result = new ArrayList<>();
953 if (receivers == null) {
954 return result;
955 }
956 for (ResolveInfo resolveInfo: receivers) {
957 String packageName = resolveInfo.activityInfo.applicationInfo.packageName;
958 int visibility = resolveAccountVisibility(account, packageName, accounts);
959 if (visibility == AccountManager.VISIBILITY_VISIBLE
960 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
961 result.add(packageName);
962 }
963 }
964 return result;
965 }
966
967 // Returns true if given package is listening to ACTION_ACCOUNT_REMOVED and can see the account.
968 private boolean shouldNotifyPackageOnAccountRemoval(Account account,
969 String packageName, UserAccounts accounts) {
970 int visibility = resolveAccountVisibility(account, packageName, accounts);
971 if (visibility != AccountManager.VISIBILITY_VISIBLE
972 && visibility != AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
973 return false;
974 }
975
976 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
977 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
978 intent.setPackage(packageName);
979 List<ResolveInfo> receivers =
980 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
981 return (receivers != null && receivers.size() > 0);
982 }
983
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800984 private boolean packageExistsForUser(String packageName, int userId) {
985 try {
986 long identityToken = clearCallingIdentity();
987 try {
988 mPackageManager.getPackageUidAsUser(packageName, userId);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700989 return true;
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800990 } finally {
991 restoreCallingIdentity(identityToken);
992 }
993 } catch (NameNotFoundException e) {
994 return false;
995 }
996 }
997
998 /**
999 * Returns true if packageName is one of special values.
1000 */
1001 private boolean isSpecialPackageKey(String packageName) {
1002 return (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)
1003 || AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName));
1004 }
1005
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001006 private void sendAccountsChangedBroadcast(int userId) {
1007 Log.i(TAG, "the accounts changed, sending broadcast of "
1008 + ACCOUNTS_CHANGED_INTENT.getAction());
1009 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001010 }
1011
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001012 private void sendAccountRemovedBroadcast(Account account, String packageName, int userId) {
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001013 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1014 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001015 intent.setPackage(packageName);
1016 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
1017 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001018 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
1019 }
1020
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001021 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -07001022 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1023 throws RemoteException {
1024 try {
1025 return super.onTransact(code, data, reply, flags);
1026 } catch (RuntimeException e) {
1027 // The account manager only throws security exceptions, so let's
1028 // log all others.
1029 if (!(e instanceof SecurityException)) {
1030 Slog.wtf(TAG, "Account Manager Crash", e);
1031 }
1032 throw e;
1033 }
1034 }
1035
Amith Yamasani258848d2012-08-10 17:06:33 -07001036 private UserManager getUserManager() {
1037 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001038 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -07001039 }
1040 return mUserManager;
1041 }
1042
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001043 /**
1044 * Validate internal set of accounts against installed authenticators for
1045 * given user. Clears cached authenticators before validating.
1046 */
1047 public void validateAccounts(int userId) {
1048 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001049 // Invalidate user-specific cache to make sure we catch any
1050 // removed authenticators.
1051 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
1052 }
1053
1054 /**
1055 * Validate internal set of accounts against installed authenticators for
1056 * given user. Clear cached authenticators before validating when requested.
1057 */
1058 private void validateAccountsInternal(
1059 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001060 if (Log.isLoggable(TAG, Log.DEBUG)) {
1061 Log.d(TAG, "validateAccountsInternal " + accounts.userId
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001062 + " isCeDatabaseAttached=" + accounts.accountsDb.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001063 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001064 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001065
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001066 if (invalidateAuthenticatorCache) {
1067 mAuthenticatorCache.invalidateCache(accounts.userId);
1068 }
1069
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001070 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
1071 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001072 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001073
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001074 synchronized (accounts.dbLock) {
1075 synchronized (accounts.cacheLock) {
1076 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001077
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001078 // Get a map of stored authenticator types to UID
1079 final AccountsDb accountsDb = accounts.accountsDb;
1080 Map<String, Integer> metaAuthUid = accountsDb.findMetaAuthUid();
1081 // Create a list of authenticator type whose previous uid no longer exists
1082 HashSet<String> obsoleteAuthType = Sets.newHashSet();
1083 SparseBooleanArray knownUids = null;
1084 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
1085 String type = authToUidEntry.getKey();
1086 int uid = authToUidEntry.getValue();
1087 Integer knownUid = knownAuth.get(type);
1088 if (knownUid != null && uid == knownUid) {
1089 // Remove it from the knownAuth list if it's unchanged.
1090 knownAuth.remove(type);
1091 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001092 /*
1093 * The authenticator is presently not cached and should only be triggered
1094 * when we think an authenticator has been removed (or is being updated).
1095 * But we still want to check if any data with the associated uid is
1096 * around. This is an (imperfect) signal that the package may be updating.
1097 *
1098 * A side effect of this is that an authenticator sharing a uid with
1099 * multiple apps won't get its credentials wiped as long as some app with
1100 * that uid is still on the device. But I suspect that this is a rare case.
1101 * And it isn't clear to me how an attacker could really exploit that
1102 * feature.
1103 *
1104 * The upshot is that we don't have to worry about accounts getting
1105 * uninstalled while the authenticator's package is being updated.
1106 *
1107 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001108 if (knownUids == null) {
1109 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
1110 }
1111 if (!knownUids.get(uid)) {
1112 // The authenticator is not presently available to the cache. And the
1113 // package no longer has a data directory (so we surmise it isn't
1114 // updating). So purge its data from the account databases.
1115 obsoleteAuthType.add(type);
1116 // And delete it from the TABLE_META
1117 accountsDb.deleteMetaByAuthTypeAndUid(type, uid);
1118 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001119 }
1120 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001121
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001122 // Add the newly registered authenticator to TABLE_META. If old authenticators have
1123 // been re-enabled (after being updated for example), then we just overwrite the old
1124 // values.
1125 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1126 accountsDb.insertOrReplaceMetaAuthTypeAndUid(entry.getKey(), entry.getValue());
1127 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001128
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001129 final Map<Long, Account> accountsMap = accountsDb.findAllDeAccounts();
1130 try {
1131 accounts.accountCache.clear();
1132 final HashMap<String, ArrayList<String>> accountNamesByType
1133 = new LinkedHashMap<>();
1134 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1135 final long accountId = accountEntry.getKey();
1136 final Account account = accountEntry.getValue();
1137 if (obsoleteAuthType.contains(account.type)) {
1138 Slog.w(TAG, "deleting account " + account.name + " because type "
1139 + account.type
1140 + "'s registered authenticator no longer exist.");
1141 Map<String, Integer> packagesToVisibility =
1142 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001143 List<String> accountRemovedReceivers =
1144 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001145 accountsDb.beginTransaction();
1146 try {
1147 accountsDb.deleteDeAccount(accountId);
1148 // Also delete from CE table if user is unlocked; if user is
1149 // currently locked the account will be removed later by
1150 // syncDeCeAccountsLocked
1151 if (userUnlocked) {
1152 accountsDb.deleteCeAccount(accountId);
1153 }
1154 accountsDb.setTransactionSuccessful();
1155 } finally {
1156 accountsDb.endTransaction();
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001157 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001158 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001159
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001160 logRecord(AccountsDb.DEBUG_ACTION_AUTHENTICATOR_REMOVE,
1161 AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001162
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001163 accounts.userDataCache.remove(account);
1164 accounts.authTokenCache.remove(account);
1165 accounts.accountTokenCaches.remove(account);
1166 accounts.visibilityCache.remove(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001167
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001168 for (Entry<String, Integer> packageToVisibility :
1169 packagesToVisibility.entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001170 if (shouldNotifyOnVisibilityChange(packageToVisibility.getValue(),
1171 AccountManager.VISIBILITY_NOT_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001172 notifyPackage(packageToVisibility.getKey(), accounts);
1173 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001174 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001175 for (String packageName : accountRemovedReceivers) {
1176 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
1177 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001178 } else {
1179 ArrayList<String> accountNames = accountNamesByType.get(account.type);
1180 if (accountNames == null) {
1181 accountNames = new ArrayList<>();
1182 accountNamesByType.put(account.type, accountNames);
1183 }
1184 accountNames.add(account.name);
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001185 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001186 }
1187 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
1188 final String accountType = cur.getKey();
1189 final ArrayList<String> accountNames = cur.getValue();
1190 final Account[] accountsForType = new Account[accountNames.size()];
1191 for (int i = 0; i < accountsForType.length; i++) {
1192 accountsForType[i] = new Account(accountNames.get(i), accountType,
1193 UUID.randomUUID().toString());
Fred Quintana56285a62010-12-02 14:20:51 -08001194 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001195 accounts.accountCache.put(accountType, accountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08001196 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001197 accounts.visibilityCache.putAll(accountsDb.findAllVisibilityValues());
1198 } finally {
1199 if (accountDeleted) {
1200 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintana56285a62010-12-02 14:20:51 -08001201 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001202 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001203 }
1204 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001205 }
1206
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001207 private boolean shouldNotifyOnVisibilityChange(int oldVisibility, int newVisibility) {
1208 boolean oldVisible = (oldVisibility == AccountManager.VISIBILITY_VISIBLE) ||
1209 (oldVisibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
1210 boolean newVisible = (newVisibility == AccountManager.VISIBILITY_VISIBLE) ||
1211 (newVisibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
1212 return oldVisible == newVisible;
1213 }
1214
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001215 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1216 // Get the UIDs of all apps that might have data on the device. We want
1217 // to preserve user data if the app might otherwise be storing data.
1218 List<PackageInfo> pkgsWithData =
1219 mPackageManager.getInstalledPackagesAsUser(
1220 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1221 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1222 for (PackageInfo pkgInfo : pkgsWithData) {
1223 if (pkgInfo.applicationInfo != null
1224 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1225 knownUids.put(pkgInfo.applicationInfo.uid, true);
1226 }
1227 }
1228 return knownUids;
1229 }
1230
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001231 static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001232 Context context,
1233 int userId) {
1234 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001235 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1236 }
1237
1238 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1239 IAccountAuthenticatorCache authCache,
1240 int userId) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08001241 HashMap<String, Integer> knownAuth = new LinkedHashMap<>();
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001242 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1243 .getAllServices(userId)) {
1244 knownAuth.put(service.type.type, service.uid);
1245 }
1246 return knownAuth;
1247 }
1248
Amith Yamasani04e0d262012-02-14 11:50:53 -08001249 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001250 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001251 }
1252
1253 protected UserAccounts getUserAccounts(int userId) {
1254 synchronized (mUsers) {
1255 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001256 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001257 if (accounts == null) {
Fyodor Kupolovda993802016-09-21 14:47:10 -07001258 File preNDbFile = new File(mInjector.getPreNDatabaseName(userId));
1259 File deDbFile = new File(mInjector.getDeDatabaseName(userId));
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001260 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001261 initializeDebugDbSizeAndCompileSqlStatementForLogging(accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001262 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001263 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001264 validateAccounts = true;
1265 }
1266 // open CE database if necessary
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001267 if (!accounts.accountsDb.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001268 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001269 synchronized (accounts.dbLock) {
1270 synchronized (accounts.cacheLock) {
1271 File ceDatabaseFile = new File(mInjector.getCeDatabaseName(userId));
1272 accounts.accountsDb.attachCeDatabase(ceDatabaseFile);
1273 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001274 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001275 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001276 }
1277 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001278 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001279 }
1280 return accounts;
1281 }
1282 }
1283
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001284 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1285 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001286 List<Account> accountsToRemove = accounts.accountsDb.findCeAccountsNotInDe();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001287 if (!accountsToRemove.isEmpty()) {
1288 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
1289 + accounts.userId + " was locked. Removing accounts from CE tables");
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001290 logRecord(accounts, AccountsDb.DEBUG_ACTION_SYNC_DE_CE_ACCOUNTS,
1291 AccountsDb.TABLE_ACCOUNTS);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001292
1293 for (Account account : accountsToRemove) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001294 removeAccountInternal(accounts, account, Process.SYSTEM_UID);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001295 }
1296 }
1297 }
1298
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001299 private void purgeOldGrantsAll() {
1300 synchronized (mUsers) {
1301 for (int i = 0; i < mUsers.size(); i++) {
1302 purgeOldGrants(mUsers.valueAt(i));
1303 }
1304 }
1305 }
1306
1307 private void purgeOldGrants(UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001308 synchronized (accounts.dbLock) {
1309 synchronized (accounts.cacheLock) {
1310 List<Integer> uids = accounts.accountsDb.findAllUidGrants();
1311 for (int uid : uids) {
1312 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1313 if (packageExists) {
1314 continue;
1315 }
1316 Log.d(TAG, "deleting grants for UID " + uid
1317 + " because its package is no longer installed");
1318 accounts.accountsDb.deleteGrantsByUid(uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001319 }
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001320 }
1321 }
1322 }
1323
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001324 private void removeVisibilityValuesForPackage(String packageName) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001325 if (isSpecialPackageKey(packageName)) {
1326 return;
1327 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001328 synchronized (mUsers) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001329 int numberOfUsers = mUsers.size();
1330 for (int i = 0; i < numberOfUsers; i++) {
1331 UserAccounts accounts = mUsers.valueAt(i);
1332 try {
1333 mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
1334 } catch (NameNotFoundException e) {
1335 // package does not exist - remove visibility values
1336 accounts.accountsDb.deleteAccountVisibilityForPackage(packageName);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001337 synchronized (accounts.dbLock) {
1338 synchronized (accounts.cacheLock) {
1339 for (Account account : accounts.visibilityCache.keySet()) {
1340 Map<String, Integer> accountVisibility =
1341 getPackagesAndVisibilityForAccountLocked(account, accounts);
1342 accountVisibility.remove(packageName);
1343 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001344 }
1345 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001346 }
1347 }
1348 }
1349 }
1350
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001351
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -07001352 private void onCleanupUser(int userId) {
1353 Log.i(TAG, "onCleanupUser " + userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001354 UserAccounts accounts;
1355 synchronized (mUsers) {
1356 accounts = mUsers.get(userId);
1357 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001358 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001359 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001360 if (accounts != null) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001361 synchronized (accounts.dbLock) {
1362 synchronized (accounts.cacheLock) {
1363 accounts.accountsDb.close();
1364 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001365 }
Amith Yamasani13593602012-03-22 16:16:17 -07001366 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001367 }
1368
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001369 @VisibleForTesting
1370 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001371 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1372 }
1373
1374 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001375 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1376 Log.v(TAG, "onUserUnlocked " + userId);
1377 }
1378 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001379 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001380 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001381 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001382 syncSharedAccounts(userId);
1383 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001384
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001385 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001386 // Check if there's a shared account that needs to be created as an account
1387 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1388 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001389 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001390 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001391 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001392 : UserHandle.USER_SYSTEM;
1393 if (parentUserId < 0) {
1394 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1395 return;
1396 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001397 for (Account sa : sharedAccounts) {
1398 if (ArrayUtils.contains(accounts, sa)) continue;
1399 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001400 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001401 }
1402 }
1403
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001404 @Override
1405 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001406 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001407 }
1408
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001409 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001410 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001411 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001412 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1413 Log.v(TAG, "getPassword: " + account
1414 + ", caller's uid " + Binder.getCallingUid()
1415 + ", pid " + Binder.getCallingPid());
1416 }
Fred Quintana382601f2010-03-25 12:25:10 -07001417 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001418 int userId = UserHandle.getCallingUserId();
1419 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001420 String msg = String.format(
1421 "uid %s cannot get secrets for accounts of type: %s",
1422 callingUid,
1423 account.type);
1424 throw new SecurityException(msg);
1425 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001426 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001427 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001428 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001429 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001430 } finally {
1431 restoreCallingIdentity(identityToken);
1432 }
1433 }
1434
Amith Yamasani04e0d262012-02-14 11:50:53 -08001435 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001436 if (account == null) {
1437 return null;
1438 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001439 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001440 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1441 return null;
1442 }
Fred Quintana31957f12009-10-21 13:43:10 -07001443
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001444 synchronized (accounts.dbLock) {
1445 synchronized (accounts.cacheLock) {
1446 return accounts.accountsDb
1447 .findAccountPasswordByNameAndType(account.name, account.type);
1448 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001449 }
1450 }
1451
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001452 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001453 public String getPreviousName(Account account) {
1454 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1455 Log.v(TAG, "getPreviousName: " + account
1456 + ", caller's uid " + Binder.getCallingUid()
1457 + ", pid " + Binder.getCallingPid());
1458 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001459 Preconditions.checkNotNull(account, "account cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001460 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001461 long identityToken = clearCallingIdentity();
1462 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001463 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001464 return readPreviousNameInternal(accounts, account);
1465 } finally {
1466 restoreCallingIdentity(identityToken);
1467 }
1468 }
1469
1470 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1471 if (account == null) {
1472 return null;
1473 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001474 synchronized (accounts.dbLock) {
1475 synchronized (accounts.cacheLock) {
1476 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1477 if (previousNameRef == null) {
1478 String previousName = accounts.accountsDb.findDeAccountPreviousName(account);
1479 previousNameRef = new AtomicReference<>(previousName);
1480 accounts.previousNameCache.put(account, previousNameRef);
1481 return previousName;
1482 } else {
1483 return previousNameRef.get();
1484 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001485 }
1486 }
1487 }
1488
1489 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001490 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001491 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001492 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001493 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1494 account, key, callingUid, Binder.getCallingPid());
1495 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001496 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001497 Preconditions.checkNotNull(account, "account cannot be null");
1498 Preconditions.checkNotNull(key, "key cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001499 int userId = UserHandle.getCallingUserId();
1500 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001501 String msg = String.format(
1502 "uid %s cannot get user data for accounts of type: %s",
1503 callingUid,
1504 account.type);
1505 throw new SecurityException(msg);
1506 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001507 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001508 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1509 return null;
1510 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001511 long identityToken = clearCallingIdentity();
1512 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001513 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001514 if (!accountExistsCache(accounts, account)) {
1515 return null;
Simranjit Kohli858511c2016-03-10 18:36:11 +00001516 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001517 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001518 } finally {
1519 restoreCallingIdentity(identityToken);
1520 }
1521 }
1522
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001523 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001524 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001525 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001526 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1527 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001528 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001529 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001530 + ", pid " + Binder.getCallingPid());
1531 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001532 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001533 if (isCrossUser(callingUid, userId)) {
1534 throw new SecurityException(
1535 String.format(
1536 "User %s tying to get authenticator types for %s" ,
1537 UserHandle.getCallingUserId(),
1538 userId));
1539 }
1540
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001541 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001542 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001543 return getAuthenticatorTypesInternal(userId);
1544
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001545 } finally {
1546 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001547 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001548 }
1549
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001550 /**
1551 * Should only be called inside of a clearCallingIdentity block.
1552 */
1553 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
Fyodor Kupolov81446482016-08-24 11:27:49 -07001554 mAuthenticatorCache.updateServices(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001555 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1556 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1557 AuthenticatorDescription[] types =
1558 new AuthenticatorDescription[authenticatorCollection.size()];
1559 int i = 0;
1560 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1561 : authenticatorCollection) {
1562 types[i] = authenticator.type;
1563 i++;
1564 }
1565 return types;
1566 }
1567
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001568 private boolean isCrossUser(int callingUid, int userId) {
1569 return (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001570 && callingUid != Process.SYSTEM_UID
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001571 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001572 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1573 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001574 }
1575
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001576 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001577 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001578 return addAccountExplicitlyWithVisibility(account, password, extras, null);
Fred Quintana60307342009-03-24 22:48:12 -07001579 }
1580
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001581 @Override
1582 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001583 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001584 int callingUid = Binder.getCallingUid();
1585 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1586 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001587 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001588 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001589 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1590 final UserAccounts toAccounts = getUserAccounts(userTo);
1591 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001592 if (response != null) {
1593 Bundle result = new Bundle();
1594 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1595 try {
1596 response.onResult(result);
1597 } catch (RemoteException e) {
1598 Slog.w(TAG, "Failed to report error back to the client." + e);
1599 }
1600 }
1601 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001602 }
1603
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001604 Slog.d(TAG, "Copying account " + account.name
1605 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001606 long identityToken = clearCallingIdentity();
1607 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001608 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001609 false /* stripAuthTokenFromResult */, account.name,
1610 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001611 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001612 protected String toDebugString(long now) {
1613 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1614 + ", " + account.type;
1615 }
1616
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001617 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001618 public void run() throws RemoteException {
1619 mAuthenticator.getAccountCredentialsForCloning(this, account);
1620 }
1621
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001622 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001623 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001624 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001625 if (result != null
1626 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1627 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001628 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001629 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001630 super.onResult(result);
1631 }
1632 }
1633 }.bind();
1634 } finally {
1635 restoreCallingIdentity(identityToken);
1636 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001637 }
1638
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001639 @Override
1640 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001641 final int callingUid = Binder.getCallingUid();
1642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1643 String msg = String.format(
1644 "accountAuthenticated( account: %s, callerUid: %s)",
1645 account,
1646 callingUid);
1647 Log.v(TAG, msg);
1648 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001649 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001650 int userId = UserHandle.getCallingUserId();
1651 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001652 String msg = String.format(
1653 "uid %s cannot notify authentication for accounts of type: %s",
1654 callingUid,
1655 account.type);
1656 throw new SecurityException(msg);
1657 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001658
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001659 if (!canUserModifyAccounts(userId, callingUid) ||
1660 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001661 return false;
1662 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001663
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001664 long identityToken = clearCallingIdentity();
1665 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001666 UserAccounts accounts = getUserAccounts(userId);
1667 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001668 } finally {
1669 restoreCallingIdentity(identityToken);
1670 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001671 }
1672
1673 private boolean updateLastAuthenticatedTime(Account account) {
1674 final UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001675 synchronized (accounts.dbLock) {
1676 synchronized (accounts.cacheLock) {
1677 return accounts.accountsDb.updateAccountLastAuthenticatedTime(account);
1678 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001679 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001680 }
1681
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001682 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001683 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1684 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001685 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001686 long id = clearCallingIdentity();
1687 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001688 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001689 false /* stripAuthTokenFromResult */, account.name,
1690 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001691 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001692 protected String toDebugString(long now) {
1693 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1694 + ", " + account.type;
1695 }
1696
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001697 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001698 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001699 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov16bedd42017-03-30 10:00:49 -07001700 for (Account acc : getAccounts(parentUserId, mContext.getOpPackageName())) {
1701 if (acc.equals(account)) {
1702 mAuthenticator.addAccountFromCredentials(
1703 this, account, accountCredentials);
1704 break;
Amith Yamasani5be347b2013-03-31 17:44:31 -07001705 }
1706 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001707 }
1708
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001709 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001710 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001711 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001712 // TODO: Anything to do if if succedded?
1713 // TODO: If it failed: Show error notification? Should we remove the shadow
1714 // account to avoid retries?
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001715 // TODO: what we do with the visibility?
1716
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001717 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001718 }
1719
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001720 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001721 public void onError(int errorCode, String errorMessage) {
1722 super.onError(errorCode, errorMessage);
1723 // TODO: Show error notification to user
1724 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1725 }
1726
1727 }.bind();
1728 } finally {
1729 restoreCallingIdentity(id);
1730 }
1731 }
1732
Amith Yamasani04e0d262012-02-14 11:50:53 -08001733 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001734 Bundle extras, int callingUid, Map<String, Integer> packageToVisibility) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001735 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001736 if (account == null) {
1737 return false;
1738 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001739 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001740 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1741 + " is locked. callingUid=" + callingUid);
1742 return false;
1743 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001744 synchronized (accounts.dbLock) {
1745 synchronized (accounts.cacheLock) {
1746 accounts.accountsDb.beginTransaction();
1747 try {
1748 if (accounts.accountsDb.findCeAccountId(account) >= 0) {
1749 Log.w(TAG, "insertAccountIntoDatabase: " + account
1750 + ", skipping since the account already exists");
1751 return false;
1752 }
1753 long accountId = accounts.accountsDb.insertCeAccount(account, password);
1754 if (accountId < 0) {
1755 Log.w(TAG, "insertAccountIntoDatabase: " + account
1756 + ", skipping the DB insert failed");
1757 return false;
1758 }
1759 // Insert into DE table
1760 if (accounts.accountsDb.insertDeAccount(account, accountId) < 0) {
1761 Log.w(TAG, "insertAccountIntoDatabase: " + account
1762 + ", skipping the DB insert failed");
1763 return false;
1764 }
1765 if (extras != null) {
1766 for (String key : extras.keySet()) {
1767 final String value = extras.getString(key);
1768 if (accounts.accountsDb.insertExtra(accountId, key, value) < 0) {
1769 Log.w(TAG, "insertAccountIntoDatabase: " + account
1770 + ", skipping since insertExtra failed for key " + key);
1771 return false;
1772 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001773 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001774 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001775
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001776 if (packageToVisibility != null) {
1777 for (Entry<String, Integer> entry : packageToVisibility.entrySet()) {
1778 setAccountVisibility(account, entry.getKey() /* package */,
1779 entry.getValue() /* visibility */, false /* notify */,
1780 accounts);
1781 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001782 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001783 accounts.accountsDb.setTransactionSuccessful();
1784
1785 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
1786 accountId,
1787 accounts, callingUid);
1788
1789 insertAccountIntoCacheLocked(accounts, account);
1790 } finally {
1791 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001792 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001793 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001794 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001795 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1796 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001797 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001798
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001799 sendNotificationAccountUpdated(account, accounts);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001800 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1801 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001802
Amith Yamasani5be347b2013-03-31 17:44:31 -07001803 return true;
1804 }
1805
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001806 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001807 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001808 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001809 }
1810 }
1811
Amith Yamasani5be347b2013-03-31 17:44:31 -07001812 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001813 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001814 * running, then clone the account too.
1815 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001816 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001817 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001818 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001819 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001820 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001821 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001822 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001823 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07001824 mHandler.sendMessage(mHandler.obtainMessage(
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001825 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001826 }
1827 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001828 }
1829 }
1830
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001831 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001832 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001833 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001834 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001835 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08001836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1837 Log.v(TAG, "hasFeatures: " + account
1838 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001839 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001840 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001841 + ", pid " + Binder.getCallingPid());
1842 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001843 Preconditions.checkArgument(account != null, "account cannot be null");
1844 Preconditions.checkArgument(response != null, "response cannot be null");
1845 Preconditions.checkArgument(features != null, "features cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001846 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001847 checkReadAccountsPermitted(callingUid, account.type, userId,
1848 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001849
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001850 long identityToken = clearCallingIdentity();
1851 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001852 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001853 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001854 } finally {
1855 restoreCallingIdentity(identityToken);
1856 }
1857 }
1858
1859 private class TestFeaturesSession extends Session {
1860 private final String[] mFeatures;
1861 private final Account mAccount;
1862
Amith Yamasani04e0d262012-02-14 11:50:53 -08001863 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001864 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001865 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001866 true /* stripAuthTokenFromResult */, account.name,
1867 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001868 mFeatures = features;
1869 mAccount = account;
1870 }
1871
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001872 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001873 public void run() throws RemoteException {
1874 try {
1875 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1876 } catch (RemoteException e) {
1877 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1878 }
1879 }
1880
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001881 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001882 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001883 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001884 IAccountManagerResponse response = getResponseAndClose();
1885 if (response != null) {
1886 try {
1887 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001888 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001889 return;
1890 }
Fred Quintana56285a62010-12-02 14:20:51 -08001891 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1892 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1893 + response);
1894 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001895 final Bundle newResult = new Bundle();
1896 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1897 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1898 response.onResult(newResult);
1899 } catch (RemoteException e) {
1900 // if the caller is dead then there is no one to care about remote exceptions
1901 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1902 Log.v(TAG, "failure while notifying response", e);
1903 }
1904 }
1905 }
1906 }
1907
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001908 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001909 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001910 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001911 + ", " + mAccount
1912 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1913 }
1914 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001915
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001916 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001917 public void renameAccount(
1918 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001919 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001920 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1921 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001922 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001923 + ", pid " + Binder.getCallingPid());
1924 }
1925 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001926 int userId = UserHandle.getCallingUserId();
1927 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001928 String msg = String.format(
1929 "uid %s cannot rename accounts of type: %s",
1930 callingUid,
1931 accountToRename.type);
1932 throw new SecurityException(msg);
1933 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001934 long identityToken = clearCallingIdentity();
1935 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001936 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001937 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001938 Bundle result = new Bundle();
1939 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1940 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001941 result.putString(AccountManager.KEY_ACCOUNT_ACCESS_ID,
1942 resultingAccount.getAccessId());
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001943 try {
1944 response.onResult(result);
1945 } catch (RemoteException e) {
1946 Log.w(TAG, e.getMessage());
1947 }
1948 } finally {
1949 restoreCallingIdentity(identityToken);
1950 }
1951 }
1952
1953 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001954 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001955 Account resultAccount = null;
1956 /*
1957 * Cancel existing notifications. Let authenticators
1958 * re-post notifications as required. But we don't know if
1959 * the authenticators have bound their notifications to
1960 * now stale account name data.
1961 *
1962 * With a rename api, we might not need to do this anymore but it
1963 * shouldn't hurt.
1964 */
1965 cancelNotification(
1966 getSigninRequiredNotificationId(accounts, accountToRename),
Chris Wren717a8812017-03-31 15:34:39 -04001967 new UserHandle(accounts.userId));
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001968 synchronized(accounts.credentialsPermissionNotificationIds) {
1969 for (Pair<Pair<Account, String>, Integer> pair:
1970 accounts.credentialsPermissionNotificationIds.keySet()) {
1971 if (accountToRename.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04001972 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001973 cancelNotification(id, new UserHandle(accounts.userId));
1974 }
1975 }
1976 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001977 synchronized (accounts.dbLock) {
1978 synchronized (accounts.cacheLock) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001979 List<String> accountRemovedReceivers =
1980 getAccountRemovedReceivers(accountToRename, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001981 accounts.accountsDb.beginTransaction();
1982 Account renamedAccount = new Account(newName, accountToRename.type);
1983 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
1984 Log.e(TAG, "renameAccount failed - account with new name already exists");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001985 return null;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001986 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001987 try {
1988 final long accountId = accounts.accountsDb.findDeAccountId(accountToRename);
1989 if (accountId >= 0) {
1990 accounts.accountsDb.renameCeAccount(accountId, newName);
1991 if (accounts.accountsDb.renameDeAccount(
1992 accountId, newName, accountToRename.name)) {
1993 accounts.accountsDb.setTransactionSuccessful();
1994 } else {
1995 Log.e(TAG, "renameAccount failed");
1996 return null;
1997 }
1998 } else {
1999 Log.e(TAG, "renameAccount failed - old account does not exist");
2000 return null;
2001 }
2002 } finally {
2003 accounts.accountsDb.endTransaction();
2004 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002005 /*
2006 * Database transaction was successful. Clean up cached
2007 * data associated with the account in the user profile.
2008 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002009 renamedAccount = insertAccountIntoCacheLocked(accounts, renamedAccount);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002010 /*
2011 * Extract the data and token caches before removing the
2012 * old account to preserve the user data associated with
2013 * the account.
2014 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002015 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
2016 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
2017 Map<String, Integer> tmpVisibility = accounts.visibilityCache.get(accountToRename);
2018 removeAccountFromCacheLocked(accounts, accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002019 /*
2020 * Update the cached data associated with the renamed
2021 * account.
2022 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002023 accounts.userDataCache.put(renamedAccount, tmpData);
2024 accounts.authTokenCache.put(renamedAccount, tmpTokens);
2025 accounts.visibilityCache.put(renamedAccount, tmpVisibility);
2026 accounts.previousNameCache.put(
2027 renamedAccount,
2028 new AtomicReference<>(accountToRename.name));
2029 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002030
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002031 int parentUserId = accounts.userId;
2032 if (canHaveProfile(parentUserId)) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002033 /*
2034 * Owner or system user account was renamed, rename the account for
2035 * those users with which the account was shared.
2036 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002037 List<UserInfo> users = getUserManager().getUsers(true);
2038 for (UserInfo user : users) {
2039 if (user.isRestricted()
2040 && (user.restrictedProfileParentId == parentUserId)) {
2041 renameSharedAccountAsUser(accountToRename, newName, user.id);
2042 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002043 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002044 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002045
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002046 sendNotificationAccountUpdated(resultAccount, accounts);
2047 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002048 for (String packageName : accountRemovedReceivers) {
2049 sendAccountRemovedBroadcast(accountToRename, packageName, accounts.userId);
2050 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002051 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002052 }
2053 return resultAccount;
2054 }
2055
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002056 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002057 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002058 return userInfo != null && userInfo.canHaveProfile();
2059 }
2060
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002061 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002062 public void removeAccount(IAccountManagerResponse response, Account account,
2063 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002064 removeAccountAsUser(
2065 response,
2066 account,
2067 expectActivityLaunch,
2068 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002069 }
2070
2071 @Override
2072 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002073 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002074 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002075 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2076 Log.v(TAG, "removeAccount: " + account
2077 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002078 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002079 + ", pid " + Binder.getCallingPid()
2080 + ", for user id " + userId);
2081 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002082 Preconditions.checkArgument(account != null, "account cannot be null");
2083 Preconditions.checkArgument(response != null, "response cannot be null");
2084
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002085 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002086 if (isCrossUser(callingUid, userId)) {
2087 throw new SecurityException(
2088 String.format(
2089 "User %s tying remove account for %s" ,
2090 UserHandle.getCallingUserId(),
2091 userId));
2092 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002093 /*
2094 * Only the system or authenticator should be allowed to remove accounts for that
2095 * authenticator. This will let users remove accounts (via Settings in the system) but not
2096 * arbitrary applications (like competing authenticators).
2097 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002098 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00002099 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
2100 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002101 String msg = String.format(
2102 "uid %s cannot remove accounts of type: %s",
2103 callingUid,
2104 account.type);
2105 throw new SecurityException(msg);
2106 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002107 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002108 try {
2109 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2110 "User cannot modify accounts");
2111 } catch (RemoteException re) {
2112 }
2113 return;
2114 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002115 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002116 try {
2117 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2118 "User cannot modify accounts of this type (policy).");
2119 } catch (RemoteException re) {
2120 }
2121 return;
2122 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002123 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002124 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002125 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002126 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002127 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002128 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002129 if (account.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002130 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002131 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002132 }
2133 }
2134 }
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002135 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002136 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002137 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2138 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002139 accountId,
2140 accounts,
2141 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002142 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002143 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2144 } finally {
2145 restoreCallingIdentity(identityToken);
2146 }
2147 }
2148
2149 @Override
2150 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002151 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002152 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2153 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002154 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002155 + ", pid " + Binder.getCallingPid());
2156 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002157 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002158 if (account == null) {
2159 /*
2160 * Null accounts should result in returning false, as per
2161 * AccountManage.addAccountExplicitly(...) java doc.
2162 */
2163 Log.e(TAG, "account is null");
2164 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002165 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002166 String msg = String.format(
2167 "uid %s cannot explicitly add accounts of type: %s",
2168 callingUid,
2169 account.type);
2170 throw new SecurityException(msg);
2171 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002172 UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002173 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002174 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002175 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2176 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002177 accountId,
2178 accounts,
2179 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002180 long identityToken = clearCallingIdentity();
2181 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002182 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002183 } finally {
2184 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002185 }
Fred Quintana60307342009-03-24 22:48:12 -07002186 }
2187
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002188 private class RemoveAccountSession extends Session {
2189 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002190 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002191 Account account, boolean expectActivityLaunch) {
2192 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002193 true /* stripAuthTokenFromResult */, account.name,
2194 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002195 mAccount = account;
2196 }
2197
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002198 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002199 protected String toDebugString(long now) {
2200 return super.toDebugString(now) + ", removeAccount"
2201 + ", account " + mAccount;
2202 }
2203
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002204 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002205 public void run() throws RemoteException {
2206 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2207 }
2208
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002209 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002210 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002211 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002212 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2213 && !result.containsKey(AccountManager.KEY_INTENT)) {
2214 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002215 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002216 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002217 }
2218 IAccountManagerResponse response = getResponseAndClose();
2219 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002220 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2221 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2222 + response);
2223 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002224 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002225 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002226 try {
2227 response.onResult(result2);
2228 } catch (RemoteException e) {
2229 // ignore
2230 }
2231 }
2232 }
2233 super.onResult(result);
2234 }
2235 }
2236
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002237 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002238 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002239 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002240 }
2241
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002242 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002243 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002244 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002245 if (!userUnlocked) {
2246 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2247 + " is still locked. CE data will be removed later");
2248 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002249 synchronized (accounts.dbLock) {
2250 synchronized (accounts.cacheLock) {
2251 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2252 accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002253 List<String> accountRemovedReceivers =
2254 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002255 accounts.accountsDb.beginTransaction();
2256 // Set to a dummy value, this will only be used if the database
2257 // transaction succeeds.
2258 long accountId = -1;
2259 try {
2260 accountId = accounts.accountsDb.findDeAccountId(account);
2261 if (accountId >= 0) {
2262 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002263 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002264 // always delete from CE table if CE storage is available
2265 // DE account could be removed while CE was locked
2266 if (userUnlocked) {
2267 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2268 if (ceAccountId >= 0) {
2269 accounts.accountsDb.deleteCeAccount(ceAccountId);
2270 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002271 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002272 accounts.accountsDb.setTransactionSuccessful();
2273 } finally {
2274 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002275 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002276 if (isChanged) {
2277 removeAccountFromCacheLocked(accounts, account);
2278 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2279 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002280 if ((packageToVisibility.getValue() == AccountManager.VISIBILITY_VISIBLE)
2281 || (packageToVisibility.getValue()
2282 == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002283 notifyPackage(packageToVisibility.getKey(), accounts);
2284 }
2285 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002286
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002287 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2288 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002289 for (String packageName : accountRemovedReceivers) {
2290 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
2291 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002292 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2293 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2294 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2295 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002296 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002297 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002298 long id = Binder.clearCallingIdentity();
2299 try {
2300 int parentUserId = accounts.userId;
2301 if (canHaveProfile(parentUserId)) {
2302 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002303 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002304 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002305 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002306 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002307 }
2308 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002309 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002310 } finally {
2311 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002312 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002313
2314 if (isChanged) {
2315 synchronized (accounts.credentialsPermissionNotificationIds) {
2316 for (Pair<Pair<Account, String>, Integer> key
2317 : accounts.credentialsPermissionNotificationIds.keySet()) {
2318 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002319 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002320 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002321 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002322 account, uid, false));
2323 }
2324 }
2325 }
2326 }
2327
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002328 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002329 }
2330
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002331 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002332 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002333 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002334 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2335 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002336 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2337 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002338 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002339 + ", pid " + Binder.getCallingPid());
2340 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002341 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002342 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002343 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002344 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002345 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002346 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002347 accounts.accountsDb.beginTransaction();
2348 try {
2349 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2350 accounts.accountsDb.setTransactionSuccessful();
2351 } finally {
2352 accounts.accountsDb.endTransaction();
2353 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002354 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002355 for (Pair<Account, String> tokenInfo : deletedTokens) {
2356 Account act = tokenInfo.first;
2357 String tokenType = tokenInfo.second;
2358 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002359 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002360 // wipe out cached token in memory.
2361 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002362 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002363 }
Fred Quintana60307342009-03-24 22:48:12 -07002364 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002365 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002366 }
2367 }
2368
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002369 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002370 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002371 // TODO Move to AccountsDB
2372 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002373 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002374
Fred Quintana33269202009-04-20 16:05:10 -07002375 try {
2376 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002377 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002378 String accountName = cursor.getString(1);
2379 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002380 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002381 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002382 }
Fred Quintana33269202009-04-20 16:05:10 -07002383 } finally {
2384 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002385 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002386 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002387 }
2388
Carlos Valdivia91979be2015-05-22 14:11:35 -07002389 private void saveCachedToken(
2390 UserAccounts accounts,
2391 Account account,
2392 String callerPkg,
2393 byte[] callerSigDigest,
2394 String tokenType,
2395 String token,
2396 long expiryMillis) {
2397
2398 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2399 return;
2400 }
2401 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002402 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002403 synchronized (accounts.cacheLock) {
2404 accounts.accountTokenCaches.put(
2405 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002406 }
2407 }
2408
Amith Yamasani04e0d262012-02-14 11:50:53 -08002409 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2410 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002411 if (account == null || type == null) {
2412 return false;
2413 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002414 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002415 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002416 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002417 accounts.accountsDb.beginTransaction();
2418 boolean updateCache = false;
2419 try {
2420 long accountId = accounts.accountsDb.findDeAccountId(account);
2421 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002422 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002423 }
2424 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2425 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2426 accounts.accountsDb.setTransactionSuccessful();
2427 updateCache = true;
2428 return true;
2429 }
2430 return false;
2431 } finally {
2432 accounts.accountsDb.endTransaction();
2433 if (updateCache) {
2434 synchronized (accounts.cacheLock) {
2435 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2436 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002437 }
Fred Quintana33269202009-04-20 16:05:10 -07002438 }
Fred Quintana60307342009-03-24 22:48:12 -07002439 }
2440 }
2441
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002442 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002443 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002444 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002445 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2446 Log.v(TAG, "peekAuthToken: " + account
2447 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002448 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002449 + ", pid " + Binder.getCallingPid());
2450 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002451 Preconditions.checkNotNull(account, "account cannot be null");
2452 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002453 int userId = UserHandle.getCallingUserId();
2454 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002455 String msg = String.format(
2456 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2457 callingUid,
2458 account.type);
2459 throw new SecurityException(msg);
2460 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002461 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002462 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2463 + callingUid);
2464 return null;
2465 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002466 long identityToken = clearCallingIdentity();
2467 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002468 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002469 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002470 } finally {
2471 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002472 }
Fred Quintana60307342009-03-24 22:48:12 -07002473 }
2474
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002475 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002476 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002477 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002478 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2479 Log.v(TAG, "setAuthToken: " + account
2480 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002481 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002482 + ", pid " + Binder.getCallingPid());
2483 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002484 Preconditions.checkNotNull(account, "account cannot be null");
2485 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002486 int userId = UserHandle.getCallingUserId();
2487 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002488 String msg = String.format(
2489 "uid %s cannot set auth tokens associated with accounts of type: %s",
2490 callingUid,
2491 account.type);
2492 throw new SecurityException(msg);
2493 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002494 long identityToken = clearCallingIdentity();
2495 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002496 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002497 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002498 } finally {
2499 restoreCallingIdentity(identityToken);
2500 }
Fred Quintana60307342009-03-24 22:48:12 -07002501 }
2502
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002503 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002504 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002505 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002506 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2507 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002508 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002509 + ", pid " + Binder.getCallingPid());
2510 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002511 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002512 int userId = UserHandle.getCallingUserId();
2513 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002514 String msg = String.format(
2515 "uid %s cannot set secrets for accounts of type: %s",
2516 callingUid,
2517 account.type);
2518 throw new SecurityException(msg);
2519 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002520 long identityToken = clearCallingIdentity();
2521 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002522 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002523 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002524 } finally {
2525 restoreCallingIdentity(identityToken);
2526 }
Fred Quintana60307342009-03-24 22:48:12 -07002527 }
2528
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002529 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2530 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002531 if (account == null) {
2532 return;
2533 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002534 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002535 synchronized (accounts.dbLock) {
2536 synchronized (accounts.cacheLock) {
2537 accounts.accountsDb.beginTransaction();
2538 try {
2539 final long accountId = accounts.accountsDb.findDeAccountId(account);
2540 if (accountId >= 0) {
2541 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2542 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2543 accounts.authTokenCache.remove(account);
2544 accounts.accountTokenCaches.remove(account);
2545 accounts.accountsDb.setTransactionSuccessful();
2546 // If there is an account whose password will be updated and the database
2547 // transactions succeed, then we say that a change has occured. Even if the
2548 // new password is the same as the old and there were no authtokens to
2549 // delete.
2550 isChanged = true;
2551 String action = (password == null || password.length() == 0) ?
2552 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2553 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2554 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2555 callingUid);
2556 }
2557 } finally {
2558 accounts.accountsDb.endTransaction();
2559 if (isChanged) {
2560 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2561 sendNotificationAccountUpdated(account, accounts);
2562 sendAccountsChangedBroadcast(accounts.userId);
2563 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002564 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002565 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002566 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002567 }
2568
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002569 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002570 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002571 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002572 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2573 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002574 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002575 + ", pid " + Binder.getCallingPid());
2576 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002577 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002578 int userId = UserHandle.getCallingUserId();
2579 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002580 String msg = String.format(
2581 "uid %s cannot clear passwords for accounts of type: %s",
2582 callingUid,
2583 account.type);
2584 throw new SecurityException(msg);
2585 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002586 long identityToken = clearCallingIdentity();
2587 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002588 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002589 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002590 } finally {
2591 restoreCallingIdentity(identityToken);
2592 }
Fred Quintana60307342009-03-24 22:48:12 -07002593 }
2594
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002595 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002596 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002597 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002598 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2599 Log.v(TAG, "setUserData: " + account
2600 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002601 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002602 + ", pid " + Binder.getCallingPid());
2603 }
Fred Quintana382601f2010-03-25 12:25:10 -07002604 if (key == null) throw new IllegalArgumentException("key is null");
2605 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002606 int userId = UserHandle.getCallingUserId();
2607 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002608 String msg = String.format(
2609 "uid %s cannot set user data for accounts of type: %s",
2610 callingUid,
2611 account.type);
2612 throw new SecurityException(msg);
2613 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002614 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002615 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002616 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002617 if (!accountExistsCache(accounts, account)) {
2618 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002619 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002620 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002621 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002622 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002623 }
2624 }
2625
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002626 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2627 synchronized (accounts.cacheLock) {
2628 if (accounts.accountCache.containsKey(account.type)) {
2629 for (Account acc : accounts.accountCache.get(account.type)) {
2630 if (acc.name.equals(account.name)) {
2631 return true;
2632 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002633 }
2634 }
2635 }
2636 return false;
2637 }
2638
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002639 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002640 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002641 synchronized (accounts.dbLock) {
2642 accounts.accountsDb.beginTransaction();
2643 try {
2644 long accountId = accounts.accountsDb.findDeAccountId(account);
2645 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002646 return;
2647 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002648 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2649 if (extrasId < 0) {
2650 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2651 if (extrasId < 0) {
2652 return;
2653 }
2654 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2655 return;
2656 }
2657 accounts.accountsDb.setTransactionSuccessful();
2658 } finally {
2659 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002660 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002661 synchronized (accounts.cacheLock) {
2662 writeUserDataIntoCacheLocked(accounts, account, key, value);
2663 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002664 }
2665 }
2666
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002667 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002668 if (result == null) {
2669 Log.e(TAG, "the result is unexpectedly null", new Exception());
2670 }
2671 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2672 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2673 + response);
2674 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002675 try {
2676 response.onResult(result);
2677 } catch (RemoteException e) {
2678 // if the caller is dead then there is no one to care about remote
2679 // exceptions
2680 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2681 Log.v(TAG, "failure while notifying response", e);
2682 }
2683 }
2684 }
2685
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002686 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002687 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2688 final String authTokenType)
2689 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002690 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2691 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002692
Fred Quintanad9640ec2012-05-23 12:37:00 -07002693 final int callingUid = getCallingUid();
2694 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002695 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002696 throw new SecurityException("can only call from system");
2697 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002698 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002699 long identityToken = clearCallingIdentity();
2700 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002701 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002702 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2703 false /* stripAuthTokenFromResult */, null /* accountName */,
2704 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002705 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002706 protected String toDebugString(long now) {
2707 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002708 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002709 + ", authTokenType " + authTokenType;
2710 }
2711
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002712 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002713 public void run() throws RemoteException {
2714 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2715 }
2716
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002717 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002718 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002719 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002720 if (result != null) {
2721 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2722 Bundle bundle = new Bundle();
2723 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2724 super.onResult(bundle);
2725 return;
2726 } else {
2727 super.onResult(result);
2728 }
2729 }
2730 }.bind();
2731 } finally {
2732 restoreCallingIdentity(identityToken);
2733 }
2734 }
2735
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002736 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002737 public void getAuthToken(
2738 IAccountManagerResponse response,
2739 final Account account,
2740 final String authTokenType,
2741 final boolean notifyOnAuthFailure,
2742 final boolean expectActivityLaunch,
2743 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002744 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2746 Log.v(TAG, "getAuthToken: " + account
2747 + ", response " + response
2748 + ", authTokenType " + authTokenType
2749 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2750 + ", expectActivityLaunch " + expectActivityLaunch
2751 + ", caller's uid " + Binder.getCallingUid()
2752 + ", pid " + Binder.getCallingPid());
2753 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002754 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002755 try {
2756 if (account == null) {
2757 Slog.w(TAG, "getAuthToken called with null account");
2758 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2759 return;
2760 }
2761 if (authTokenType == null) {
2762 Slog.w(TAG, "getAuthToken called with null authTokenType");
2763 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2764 return;
2765 }
2766 } catch (RemoteException e) {
2767 Slog.w(TAG, "Failed to report error back to the client." + e);
2768 return;
2769 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002770 int userId = UserHandle.getCallingUserId();
2771 long ident = Binder.clearCallingIdentity();
2772 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002773 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002774 try {
2775 accounts = getUserAccounts(userId);
2776 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2777 AuthenticatorDescription.newKey(account.type), accounts.userId);
2778 } finally {
2779 Binder.restoreCallingIdentity(ident);
2780 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002781
Costin Manolachea40c6302010-12-13 14:50:45 -08002782 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002783 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002784
2785 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002786 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002787 final boolean permissionGranted =
2788 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002789
Carlos Valdivia91979be2015-05-22 14:11:35 -07002790 // Get the calling package. We will use it for the purpose of caching.
2791 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002792 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002793 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002794 try {
2795 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2796 } finally {
2797 Binder.restoreCallingIdentity(ident);
2798 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002799 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2800 String msg = String.format(
2801 "Uid %s is attempting to illegally masquerade as package %s!",
2802 callerUid,
2803 callerPkg);
2804 throw new SecurityException(msg);
2805 }
2806
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002807 // let authenticator know the identity of the caller
2808 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2809 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002810
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002811 if (notifyOnAuthFailure) {
2812 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002813 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002814
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002815 long identityToken = clearCallingIdentity();
2816 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002817 // Distill the caller's package signatures into a single digest.
2818 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2819
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002820 // if the caller has permission, do the peek. otherwise go the more expensive
2821 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002822 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002823 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002824 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002825 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002826 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2827 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2828 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002829 onResult(response, result);
2830 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002831 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002832 }
2833
Carlos Valdivia91979be2015-05-22 14:11:35 -07002834 if (customTokens) {
2835 /*
2836 * Look up tokens in the new cache only if the loginOptions don't have parameters
2837 * outside of those expected to be injected by the AccountManager, e.g.
2838 * ANDORID_PACKAGE_NAME.
2839 */
2840 String token = readCachedTokenInternal(
2841 accounts,
2842 account,
2843 authTokenType,
2844 callerPkg,
2845 callerPkgSigDigest);
2846 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002847 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2848 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2849 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002850 Bundle result = new Bundle();
2851 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2852 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2853 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2854 onResult(response, result);
2855 return;
2856 }
2857 }
2858
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002859 new Session(
2860 accounts,
2861 response,
2862 account.type,
2863 expectActivityLaunch,
2864 false /* stripAuthTokenFromResult */,
2865 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002866 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002867 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002868 protected String toDebugString(long now) {
2869 if (loginOptions != null) loginOptions.keySet();
2870 return super.toDebugString(now) + ", getAuthToken"
2871 + ", " + account
2872 + ", authTokenType " + authTokenType
2873 + ", loginOptions " + loginOptions
2874 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2875 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002876
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002877 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002878 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002879 // If the caller doesn't have permission then create and return the
2880 // "grant permission" intent instead of the "getAuthToken" intent.
2881 if (!permissionGranted) {
2882 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2883 } else {
2884 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2885 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002886 }
2887
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002888 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002889 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002890 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002891 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002892 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002893 Intent intent = newGrantCredentialsPermissionIntent(
2894 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002895 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002896 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002897 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002898 authTokenType,
2899 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002900 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002901 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002902 onResult(bundle);
2903 return;
2904 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002905 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002906 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002907 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2908 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002909 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002910 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002911 "the type and name should not be empty");
2912 return;
2913 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002914 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002915 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002916 saveAuthTokenToDatabase(
2917 mAccounts,
2918 resultAccount,
2919 authTokenType,
2920 authToken);
2921 }
2922 long expiryMillis = result.getLong(
2923 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2924 if (customTokens
2925 && expiryMillis > System.currentTimeMillis()) {
2926 saveCachedToken(
2927 mAccounts,
2928 account,
2929 callerPkg,
2930 callerPkgSigDigest,
2931 authTokenType,
2932 authToken,
2933 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002934 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002935 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002936
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002937 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002938 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002939 /*
2940 * Make sure that the supplied intent is owned by the authenticator
2941 * giving it to the system. Otherwise a malicious authenticator could
2942 * have users launching arbitrary activities by tricking users to
2943 * interact with malicious notifications.
2944 */
2945 checkKeyIntent(
2946 Binder.getCallingUid(),
2947 intent);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002948 doNotification(
2949 mAccounts,
2950 account,
2951 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002952 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002953 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002954 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002955 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002956 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002957 }.bind();
2958 } finally {
2959 restoreCallingIdentity(identityToken);
2960 }
Fred Quintana60307342009-03-24 22:48:12 -07002961 }
2962
Carlos Valdivia91979be2015-05-22 14:11:35 -07002963 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2964 MessageDigest digester;
2965 try {
2966 digester = MessageDigest.getInstance("SHA-256");
2967 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2968 callerPkg, PackageManager.GET_SIGNATURES);
2969 for (Signature sig : pkgInfo.signatures) {
2970 digester.update(sig.toByteArray());
2971 }
2972 } catch (NoSuchAlgorithmException x) {
2973 Log.wtf(TAG, "SHA-256 should be available", x);
2974 digester = null;
2975 } catch (NameNotFoundException e) {
2976 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2977 digester = null;
2978 }
2979 return (digester == null) ? null : digester.digest();
2980 }
2981
Dianne Hackborn41203752012-08-31 14:05:51 -07002982 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002983 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002984 int uid = intent.getIntExtra(
2985 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2986 String authTokenType = intent.getStringExtra(
2987 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002988 final String titleAndSubtitle =
2989 mContext.getString(R.string.permission_request_notification_with_subtitle,
2990 account.name);
2991 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002992 String title = titleAndSubtitle;
2993 String subtitle = "";
2994 if (index > 0) {
2995 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002996 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002997 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002998 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002999 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05003000 Notification n =
3001 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
3002 .setSmallIcon(android.R.drawable.stat_sys_warning)
3003 .setWhen(0)
3004 .setColor(contextForUser.getColor(
3005 com.android.internal.R.color.system_notification_accent_color))
3006 .setContentTitle(title)
3007 .setContentText(subtitle)
3008 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
3009 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
3010 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003011 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003012 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003013 }
3014
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003015 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
3016 int uid, AccountAuthenticatorResponse response, String authTokenType,
3017 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003018
3019 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003020
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003021 if (startInNewTask) {
3022 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
3023 // Since it was set in Eclair+ we can't change it without breaking apps using
3024 // the intent from a non-Activity context. This is the default behavior.
3025 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3026 }
Chris Wren717a8812017-03-31 15:34:39 -04003027 intent.addCategory(getCredentialPermissionNotificationId(account,
3028 authTokenType, uid).mTag + (packageName != null ? packageName : ""));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003029 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003030 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
3031 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003032 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003033
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003034 return intent;
3035 }
3036
Chris Wren717a8812017-03-31 15:34:39 -04003037 private NotificationId getCredentialPermissionNotificationId(Account account,
3038 String authTokenType, int uid) {
3039 NotificationId nId;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003040 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003041 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003042 final Pair<Pair<Account, String>, Integer> key =
3043 new Pair<Pair<Account, String>, Integer>(
3044 new Pair<Account, String>(account, authTokenType), uid);
Chris Wren717a8812017-03-31 15:34:39 -04003045 nId = accounts.credentialsPermissionNotificationIds.get(key);
3046 if (nId == null) {
3047 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION
3048 + ":" + account.hashCode() + ":" + authTokenType.hashCode();
3049 int id = SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION;
3050 nId = new NotificationId(tag, id);
3051 accounts.credentialsPermissionNotificationIds.put(key, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003052 }
3053 }
Chris Wren717a8812017-03-31 15:34:39 -04003054 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003055 }
3056
Chris Wren717a8812017-03-31 15:34:39 -04003057 private NotificationId getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
3058 NotificationId nId;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003059 synchronized (accounts.signinRequiredNotificationIds) {
Chris Wren717a8812017-03-31 15:34:39 -04003060 nId = accounts.signinRequiredNotificationIds.get(account);
3061 if (nId == null) {
3062 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN
3063 + ":" + account.hashCode();
3064 int id = SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN;
3065 nId = new NotificationId(tag, id);
3066 accounts.signinRequiredNotificationIds.put(account, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003067 }
3068 }
Chris Wren717a8812017-03-31 15:34:39 -04003069 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003070 }
3071
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003072 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07003073 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07003074 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003075 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003076 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003077 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3078 Log.v(TAG, "addAccount: accountType " + accountType
3079 + ", response " + response
3080 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003081 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08003082 + ", expectActivityLaunch " + expectActivityLaunch
3083 + ", caller's uid " + Binder.getCallingUid()
3084 + ", pid " + Binder.getCallingPid());
3085 }
Fred Quintana382601f2010-03-25 12:25:10 -07003086 if (response == null) throw new IllegalArgumentException("response is null");
3087 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003088
Amith Yamasani71e6c692013-03-24 17:39:28 -07003089 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003090 final int uid = Binder.getCallingUid();
3091 final int userId = UserHandle.getUserId(uid);
3092 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003093 try {
3094 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3095 "User is not allowed to add an account!");
3096 } catch (RemoteException re) {
3097 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003098 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003099 return;
3100 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003101 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003102 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003103 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3104 "User cannot modify accounts of this type (policy).");
3105 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003106 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003107 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3108 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003109 return;
3110 }
3111
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003112 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003113 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3114 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3115 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3116
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003117 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003118 long identityToken = clearCallingIdentity();
3119 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003120 UserAccounts accounts = getUserAccounts(usrId);
3121 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003122 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3123 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003124 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003125 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003126 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003127 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003128 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003129 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003130 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003131 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003132
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003133 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003134 protected String toDebugString(long now) {
3135 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003136 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003137 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003138 }
3139 }.bind();
3140 } finally {
3141 restoreCallingIdentity(identityToken);
3142 }
Fred Quintana60307342009-03-24 22:48:12 -07003143 }
3144
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003145 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003146 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3147 final String authTokenType, final String[] requiredFeatures,
3148 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003149 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003150 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003151 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3152 Log.v(TAG, "addAccount: accountType " + accountType
3153 + ", response " + response
3154 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003155 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003156 + ", expectActivityLaunch " + expectActivityLaunch
3157 + ", caller's uid " + Binder.getCallingUid()
3158 + ", pid " + Binder.getCallingPid()
3159 + ", for user id " + userId);
3160 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003161 Preconditions.checkArgument(response != null, "response cannot be null");
3162 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003163 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003164 if (isCrossUser(callingUid, userId)) {
3165 throw new SecurityException(
3166 String.format(
3167 "User %s trying to add account for %s" ,
3168 UserHandle.getCallingUserId(),
3169 userId));
3170 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003171
3172 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003173 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003174 try {
3175 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3176 "User is not allowed to add an account!");
3177 } catch (RemoteException re) {
3178 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003179 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003180 return;
3181 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003182 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003183 try {
3184 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3185 "User cannot modify accounts of this type (policy).");
3186 } catch (RemoteException re) {
3187 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003188 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3189 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003190 return;
3191 }
3192
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003193 final int pid = Binder.getCallingPid();
3194 final int uid = Binder.getCallingUid();
3195 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3196 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3197 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3198
3199 long identityToken = clearCallingIdentity();
3200 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003201 UserAccounts accounts = getUserAccounts(userId);
3202 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003203 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3204 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003205 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003206 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003207 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003208 @Override
3209 public void run() throws RemoteException {
3210 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3211 options);
3212 }
3213
3214 @Override
3215 protected String toDebugString(long now) {
3216 return super.toDebugString(now) + ", addAccount"
3217 + ", accountType " + accountType
3218 + ", requiredFeatures "
3219 + (requiredFeatures != null
3220 ? TextUtils.join(",", requiredFeatures)
3221 : null);
3222 }
3223 }.bind();
3224 } finally {
3225 restoreCallingIdentity(identityToken);
3226 }
3227 }
3228
Sandra Kwan78812282015-11-04 11:19:47 -08003229 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003230 public void startAddAccountSession(
3231 final IAccountManagerResponse response,
3232 final String accountType,
3233 final String authTokenType,
3234 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003235 final boolean expectActivityLaunch,
3236 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003237 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003238 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3239 Log.v(TAG,
3240 "startAddAccountSession: accountType " + accountType
3241 + ", response " + response
3242 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003243 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003244 + ", expectActivityLaunch " + expectActivityLaunch
3245 + ", caller's uid " + Binder.getCallingUid()
3246 + ", pid " + Binder.getCallingPid());
3247 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003248 Preconditions.checkArgument(response != null, "response cannot be null");
3249 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003250
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003251 final int uid = Binder.getCallingUid();
3252 final int userId = UserHandle.getUserId(uid);
3253 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003254 try {
3255 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3256 "User is not allowed to add an account!");
3257 } catch (RemoteException re) {
3258 }
3259 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3260 return;
3261 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003262 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003263 try {
3264 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3265 "User cannot modify accounts of this type (policy).");
3266 } catch (RemoteException re) {
3267 }
3268 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3269 userId);
3270 return;
3271 }
Sandra Kwan78812282015-11-04 11:19:47 -08003272 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003273 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3274 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3275 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3276
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003277 // Check to see if the Password should be included to the caller.
3278 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3279 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003280 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003281
Sandra Kwan78812282015-11-04 11:19:47 -08003282 long identityToken = clearCallingIdentity();
3283 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003284 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003285 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3286 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003287 new StartAccountSession(
3288 accounts,
3289 response,
3290 accountType,
3291 expectActivityLaunch,
3292 null /* accountName */,
3293 false /* authDetailsRequired */,
3294 true /* updateLastAuthenticationTime */,
3295 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003296 @Override
3297 public void run() throws RemoteException {
3298 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3299 requiredFeatures, options);
3300 }
3301
3302 @Override
3303 protected String toDebugString(long now) {
3304 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3305 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3306 + accountType + ", requiredFeatures "
3307 + (requiredFeatures != null ? requiredFeaturesStr : null);
3308 }
3309 }.bind();
3310 } finally {
3311 restoreCallingIdentity(identityToken);
3312 }
3313 }
3314
3315 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3316 private abstract class StartAccountSession extends Session {
3317
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003318 private final boolean mIsPasswordForwardingAllowed;
3319
3320 public StartAccountSession(
3321 UserAccounts accounts,
3322 IAccountManagerResponse response,
3323 String accountType,
3324 boolean expectActivityLaunch,
3325 String accountName,
3326 boolean authDetailsRequired,
3327 boolean updateLastAuthenticationTime,
3328 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003329 super(accounts, response, accountType, expectActivityLaunch,
3330 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3331 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003332 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003333 }
3334
3335 @Override
3336 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003337 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003338 mNumResults++;
3339 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003340 if (result != null
3341 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003342 checkKeyIntent(
3343 Binder.getCallingUid(),
3344 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08003345 }
Sandra Kwan78812282015-11-04 11:19:47 -08003346 IAccountManagerResponse response;
3347 if (mExpectActivityLaunch && result != null
3348 && result.containsKey(AccountManager.KEY_INTENT)) {
3349 response = mResponse;
3350 } else {
3351 response = getResponseAndClose();
3352 }
3353 if (response == null) {
3354 return;
3355 }
3356 if (result == null) {
3357 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3358 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3359 + response);
3360 }
3361 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3362 "null bundle returned");
3363 return;
3364 }
3365
3366 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3367 // All AccountManager error codes are greater
3368 // than 0
3369 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3370 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3371 return;
3372 }
3373
Hongming Jin368aa192016-07-29 14:29:54 -07003374 // Omit passwords if the caller isn't permitted to see them.
3375 if (!mIsPasswordForwardingAllowed) {
3376 result.remove(AccountManager.KEY_PASSWORD);
3377 }
3378
Sandra Kwan78812282015-11-04 11:19:47 -08003379 // Strip auth token from result.
3380 result.remove(AccountManager.KEY_AUTHTOKEN);
3381
3382 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3383 Log.v(TAG,
3384 getClass().getSimpleName() + " calling onResult() on response " + response);
3385 }
3386
3387 // Get the session bundle created by authenticator. The
3388 // bundle contains data necessary for finishing the session
3389 // later. The session bundle will be encrypted here and
3390 // decrypted later when trying to finish the session.
3391 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3392 if (sessionBundle != null) {
3393 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3394 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003395 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003396 Log.w(TAG, "Account type in session bundle doesn't match request.");
3397 }
3398 // Add accountType info to session bundle. This will
3399 // override any value set by authenticator.
3400 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3401
3402 // Encrypt session bundle before returning to caller.
3403 try {
3404 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3405 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3406 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3407 } catch (GeneralSecurityException e) {
3408 if (Log.isLoggable(TAG, Log.DEBUG)) {
3409 Log.v(TAG, "Failed to encrypt session bundle!", e);
3410 }
3411 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3412 "failed to encrypt session bundle");
3413 return;
3414 }
3415 }
3416
3417 sendResponse(response, result);
3418 }
3419 }
3420
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003421 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003422 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003423 @NonNull Bundle sessionBundle,
3424 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003425 Bundle appInfo,
3426 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003427 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003428 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003429 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3430 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003431 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003432 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003433 + ", caller's uid " + callingUid
3434 + ", caller's user id " + UserHandle.getCallingUserId()
3435 + ", pid " + Binder.getCallingPid()
3436 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003437 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003438 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003439 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3440 // Account type is added to it before encryption.
3441 if (sessionBundle == null || sessionBundle.size() == 0) {
3442 throw new IllegalArgumentException("sessionBundle is empty");
3443 }
3444
Dmitry Dementyev52745472016-12-02 10:27:45 -08003445 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003446 if (isCrossUser(callingUid, userId)) {
3447 throw new SecurityException(
3448 String.format(
3449 "User %s trying to finish session for %s without cross user permission",
3450 UserHandle.getCallingUserId(),
3451 userId));
3452 }
3453
Sandra Kwan0b84b452016-01-20 15:25:42 -08003454 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003455 sendErrorResponse(response,
3456 AccountManager.ERROR_CODE_USER_RESTRICTED,
3457 "User is not allowed to add an account!");
3458 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3459 return;
3460 }
3461
3462 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003463 final Bundle decryptedBundle;
3464 final String accountType;
3465 // First decrypt session bundle to get account type for checking permission.
3466 try {
3467 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3468 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3469 if (decryptedBundle == null) {
3470 sendErrorResponse(
3471 response,
3472 AccountManager.ERROR_CODE_BAD_REQUEST,
3473 "failed to decrypt session bundle");
3474 return;
3475 }
3476 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3477 // Account type cannot be null. This should not happen if session bundle was created
3478 // properly by #StartAccountSession.
3479 if (TextUtils.isEmpty(accountType)) {
3480 sendErrorResponse(
3481 response,
3482 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3483 "accountType is empty");
3484 return;
3485 }
3486
3487 // If by any chances, decryptedBundle contains colliding keys with
3488 // system info
3489 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3490 // update credentials flow, we should replace with the new values of the current call.
3491 if (appInfo != null) {
3492 decryptedBundle.putAll(appInfo);
3493 }
3494
3495 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003496 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003497 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3498 } catch (GeneralSecurityException e) {
3499 if (Log.isLoggable(TAG, Log.DEBUG)) {
3500 Log.v(TAG, "Failed to decrypt session bundle!", e);
3501 }
3502 sendErrorResponse(
3503 response,
3504 AccountManager.ERROR_CODE_BAD_REQUEST,
3505 "failed to decrypt session bundle");
3506 return;
3507 }
3508
Sandra Kwan0b84b452016-01-20 15:25:42 -08003509 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003510 sendErrorResponse(
3511 response,
3512 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3513 "User cannot modify accounts of this type (policy).");
3514 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3515 userId);
3516 return;
3517 }
3518
3519 long identityToken = clearCallingIdentity();
3520 try {
3521 UserAccounts accounts = getUserAccounts(userId);
3522 logRecordWithUid(
3523 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003524 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3525 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003526 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003527 new Session(
3528 accounts,
3529 response,
3530 accountType,
3531 expectActivityLaunch,
3532 true /* stripAuthTokenFromResult */,
3533 null /* accountName */,
3534 false /* authDetailsRequired */,
3535 true /* updateLastAuthenticationTime */) {
3536 @Override
3537 public void run() throws RemoteException {
3538 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3539 }
3540
3541 @Override
3542 protected String toDebugString(long now) {
3543 return super.toDebugString(now)
3544 + ", finishSession"
3545 + ", accountType " + accountType;
3546 }
3547 }.bind();
3548 } finally {
3549 restoreCallingIdentity(identityToken);
3550 }
3551 }
3552
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003553 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003554 final DevicePolicyManagerInternal dpmi =
3555 LocalServices.getService(DevicePolicyManagerInternal.class);
3556 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003557 if (dpmi == null) {
3558 intent = getDefaultCantAddAccountIntent(errorCode);
3559 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003560 intent = dpmi.createUserRestrictionSupportIntent(userId,
3561 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3562 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3563 intent = dpmi.createShowAdminSupportIntent(userId, false);
3564 }
3565 if (intent == null) {
3566 intent = getDefaultCantAddAccountIntent(errorCode);
3567 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003568 long identityToken = clearCallingIdentity();
3569 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003570 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003571 } finally {
3572 restoreCallingIdentity(identityToken);
3573 }
3574 }
3575
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003576 /**
3577 * Called when we don't know precisely who is preventing us from adding an account.
3578 */
3579 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3580 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3581 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3582 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3583 return cantAddAccount;
3584 }
3585
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003586 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003587 public void confirmCredentialsAsUser(
3588 IAccountManagerResponse response,
3589 final Account account,
3590 final Bundle options,
3591 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003592 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003593 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003594 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003595 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3596 Log.v(TAG, "confirmCredentials: " + account
3597 + ", response " + response
3598 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003599 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003600 + ", pid " + Binder.getCallingPid());
3601 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003602 // Only allow the system process to read accounts of other users
3603 if (isCrossUser(callingUid, userId)) {
3604 throw new SecurityException(
3605 String.format(
3606 "User %s trying to confirm account credentials for %s" ,
3607 UserHandle.getCallingUserId(),
3608 userId));
3609 }
Fred Quintana382601f2010-03-25 12:25:10 -07003610 if (response == null) throw new IllegalArgumentException("response is null");
3611 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003612 long identityToken = clearCallingIdentity();
3613 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003614 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003615 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003616 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003617 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003618 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003619 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003620 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003621 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003622 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003623 protected String toDebugString(long now) {
3624 return super.toDebugString(now) + ", confirmCredentials"
3625 + ", " + account;
3626 }
3627 }.bind();
3628 } finally {
3629 restoreCallingIdentity(identityToken);
3630 }
Fred Quintana60307342009-03-24 22:48:12 -07003631 }
3632
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003633 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003634 public void updateCredentials(IAccountManagerResponse response, final Account account,
3635 final String authTokenType, final boolean expectActivityLaunch,
3636 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003637 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003638 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3639 Log.v(TAG, "updateCredentials: " + account
3640 + ", response " + response
3641 + ", authTokenType " + authTokenType
3642 + ", expectActivityLaunch " + expectActivityLaunch
3643 + ", caller's uid " + Binder.getCallingUid()
3644 + ", pid " + Binder.getCallingPid());
3645 }
Fred Quintana382601f2010-03-25 12:25:10 -07003646 if (response == null) throw new IllegalArgumentException("response is null");
3647 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003648 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003649 long identityToken = clearCallingIdentity();
3650 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003651 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003652 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003653 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003654 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003655 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003656 public void run() throws RemoteException {
3657 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3658 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003659 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003660 protected String toDebugString(long now) {
3661 if (loginOptions != null) loginOptions.keySet();
3662 return super.toDebugString(now) + ", updateCredentials"
3663 + ", " + account
3664 + ", authTokenType " + authTokenType
3665 + ", loginOptions " + loginOptions;
3666 }
3667 }.bind();
3668 } finally {
3669 restoreCallingIdentity(identityToken);
3670 }
Fred Quintana60307342009-03-24 22:48:12 -07003671 }
3672
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003673 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003674 public void startUpdateCredentialsSession(
3675 IAccountManagerResponse response,
3676 final Account account,
3677 final String authTokenType,
3678 final boolean expectActivityLaunch,
3679 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003680 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3682 Log.v(TAG,
3683 "startUpdateCredentialsSession: " + account + ", response " + response
3684 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3685 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3686 + ", pid " + Binder.getCallingPid());
3687 }
3688 if (response == null) {
3689 throw new IllegalArgumentException("response is null");
3690 }
3691 if (account == null) {
3692 throw new IllegalArgumentException("account is null");
3693 }
Sandra Kwana578d112015-12-16 16:01:43 -08003694
3695 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003696 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003697
3698 // Check to see if the Password should be included to the caller.
3699 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3700 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003701 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003702
Sandra Kwane68c37e2015-11-12 17:11:49 -08003703 long identityToken = clearCallingIdentity();
3704 try {
3705 UserAccounts accounts = getUserAccounts(userId);
3706 new StartAccountSession(
3707 accounts,
3708 response,
3709 account.type,
3710 expectActivityLaunch,
3711 account.name,
3712 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003713 true /* updateLastCredentialTime */,
3714 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003715 @Override
3716 public void run() throws RemoteException {
3717 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3718 loginOptions);
3719 }
3720
3721 @Override
3722 protected String toDebugString(long now) {
3723 if (loginOptions != null)
3724 loginOptions.keySet();
3725 return super.toDebugString(now)
3726 + ", startUpdateCredentialsSession"
3727 + ", " + account
3728 + ", authTokenType " + authTokenType
3729 + ", loginOptions " + loginOptions;
3730 }
3731 }.bind();
3732 } finally {
3733 restoreCallingIdentity(identityToken);
3734 }
3735 }
3736
3737 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003738 public void isCredentialsUpdateSuggested(
3739 IAccountManagerResponse response,
3740 final Account account,
3741 final String statusToken) {
3742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3743 Log.v(TAG,
3744 "isCredentialsUpdateSuggested: " + account + ", response " + response
3745 + ", caller's uid " + Binder.getCallingUid()
3746 + ", pid " + Binder.getCallingPid());
3747 }
3748 if (response == null) {
3749 throw new IllegalArgumentException("response is null");
3750 }
3751 if (account == null) {
3752 throw new IllegalArgumentException("account is null");
3753 }
3754 if (TextUtils.isEmpty(statusToken)) {
3755 throw new IllegalArgumentException("status token is empty");
3756 }
3757
Sandra Kwan390c9d22016-01-12 14:13:37 -08003758 int usrId = UserHandle.getCallingUserId();
3759 long identityToken = clearCallingIdentity();
3760 try {
3761 UserAccounts accounts = getUserAccounts(usrId);
3762 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3763 false /* stripAuthTokenFromResult */, account.name,
3764 false /* authDetailsRequired */) {
3765 @Override
3766 protected String toDebugString(long now) {
3767 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3768 + ", " + account;
3769 }
3770
3771 @Override
3772 public void run() throws RemoteException {
3773 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3774 }
3775
3776 @Override
3777 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003778 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003779 IAccountManagerResponse response = getResponseAndClose();
3780 if (response == null) {
3781 return;
3782 }
3783
3784 if (result == null) {
3785 sendErrorResponse(
3786 response,
3787 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3788 "null bundle");
3789 return;
3790 }
3791
3792 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3793 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3794 + response);
3795 }
3796 // Check to see if an error occurred. We know if an error occurred because all
3797 // error codes are greater than 0.
3798 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3799 sendErrorResponse(response,
3800 result.getInt(AccountManager.KEY_ERROR_CODE),
3801 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3802 return;
3803 }
3804 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3805 sendErrorResponse(
3806 response,
3807 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3808 "no result in response");
3809 return;
3810 }
3811 final Bundle newResult = new Bundle();
3812 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3813 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3814 sendResponse(response, newResult);
3815 }
3816 }.bind();
3817 } finally {
3818 restoreCallingIdentity(identityToken);
3819 }
3820 }
3821
3822 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003823 public void editProperties(IAccountManagerResponse response, final String accountType,
3824 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003825 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003826 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3827 Log.v(TAG, "editProperties: accountType " + accountType
3828 + ", response " + response
3829 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003830 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003831 + ", pid " + Binder.getCallingPid());
3832 }
Fred Quintana382601f2010-03-25 12:25:10 -07003833 if (response == null) throw new IllegalArgumentException("response is null");
3834 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003835 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003836 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3837 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003838 String msg = String.format(
3839 "uid %s cannot edit authenticator properites for account type: %s",
3840 callingUid,
3841 accountType);
3842 throw new SecurityException(msg);
3843 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003844 long identityToken = clearCallingIdentity();
3845 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003846 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003847 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003848 true /* stripAuthTokenFromResult */, null /* accountName */,
3849 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003850 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003851 public void run() throws RemoteException {
3852 mAuthenticator.editProperties(this, mAccountType);
3853 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003854 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003855 protected String toDebugString(long now) {
3856 return super.toDebugString(now) + ", editProperties"
3857 + ", accountType " + accountType;
3858 }
3859 }.bind();
3860 } finally {
3861 restoreCallingIdentity(identityToken);
3862 }
Fred Quintana60307342009-03-24 22:48:12 -07003863 }
3864
Amith Yamasani12747872015-12-07 14:19:49 -08003865 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003866 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3867 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003868 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003869 throw new SecurityException("Can be called only by system UID");
3870 }
3871 Preconditions.checkNotNull(account, "account cannot be null");
3872 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3873 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3874
3875 final int userId = userHandle.getIdentifier();
3876
3877 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3878
3879 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003880 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003881 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003882 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003883 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003884 return false;
3885 }
3886 }
3887
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003888 // Returns package with oldest target SDK for given UID.
3889 private String getPackageNameForUid(int uid) {
3890 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3891 if (ArrayUtils.isEmpty(packageNames)) {
3892 return null;
3893 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003894 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003895 if (packageNames.length == 1) {
3896 return packageName;
3897 }
3898 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003899 int oldestVersion = Integer.MAX_VALUE;
3900 for (String name : packageNames) {
3901 try {
3902 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3903 if (applicationInfo != null) {
3904 int version = applicationInfo.targetSdkVersion;
3905 if (version < oldestVersion) {
3906 oldestVersion = version;
3907 packageName = name;
3908 }
3909 }
3910 } catch (NameNotFoundException e) {
3911 // skip
3912 }
3913 }
3914 return packageName;
3915 }
3916
Svet Ganovf6d424f12016-09-20 20:18:53 -07003917 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3918 int uid) {
3919 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003920 packageName = getPackageNameForUid(uid);
3921 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07003922 return false;
3923 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003924 }
3925
3926 // Use null token which means any token. Having a token means the package
3927 // is trusted by the authenticator, hence it is fine to access the account.
3928 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
3929 return true;
3930 }
3931 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003932 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07003933
Dmitry Dementyeve366f822017-01-31 10:25:10 -08003934 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003935 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003936 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003937 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003938 }
3939
3940 @Override
3941 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3942 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003943 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003944 throw new SecurityException("Can be called only by system UID");
3945 }
3946
3947 Preconditions.checkNotNull(account, "account cannot be null");
3948 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3949 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3950
3951 final int userId = userHandle.getIdentifier();
3952
3953 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3954
3955 final int uid;
3956 try {
3957 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
3958 } catch (NameNotFoundException e) {
3959 Slog.e(TAG, "Unknown package " + packageName);
3960 return null;
3961 }
3962
3963 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
3964
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003965 final long identity = Binder.clearCallingIdentity();
3966 try {
3967 return PendingIntent.getActivityAsUser(
3968 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
3969 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
3970 null, new UserHandle(userId)).getIntentSender();
3971 } finally {
3972 Binder.restoreCallingIdentity(identity);
3973 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003974 }
3975
3976 private Intent newRequestAccountAccessIntent(Account account, String packageName,
3977 int uid, RemoteCallback callback) {
3978 return newGrantCredentialsPermissionIntent(account, packageName, uid,
3979 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
3980 @Override
3981 public void onResult(Bundle value) throws RemoteException {
3982 handleAuthenticatorResponse(true);
3983 }
3984
3985 @Override
3986 public void onRequestContinued() {
3987 /* ignore */
3988 }
3989
3990 @Override
3991 public void onError(int errorCode, String errorMessage) throws RemoteException {
3992 handleAuthenticatorResponse(false);
3993 }
3994
3995 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
3996 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07003997 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003998 UserHandle.getUserHandleForUid(uid));
3999 if (callback != null) {
4000 Bundle result = new Bundle();
4001 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
4002 callback.sendResult(result);
4003 }
4004 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004005 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004006 }
4007
4008 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08004009 public boolean someUserHasAccount(@NonNull final Account account) {
4010 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
4011 throw new SecurityException("Only system can check for accounts across users");
4012 }
4013 final long token = Binder.clearCallingIdentity();
4014 try {
4015 AccountAndUser[] allAccounts = getAllAccounts();
4016 for (int i = allAccounts.length - 1; i >= 0; i--) {
4017 if (allAccounts[i].account.equals(account)) {
4018 return true;
4019 }
4020 }
4021 return false;
4022 } finally {
4023 Binder.restoreCallingIdentity(token);
4024 }
4025 }
4026
Fred Quintana33269202009-04-20 16:05:10 -07004027 private class GetAccountsByTypeAndFeatureSession extends Session {
4028 private final String[] mFeatures;
4029 private volatile Account[] mAccountsOfType = null;
4030 private volatile ArrayList<Account> mAccountsWithFeatures = null;
4031 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004032 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004033 private final String mPackageName;
Fred Quintana33269202009-04-20 16:05:10 -07004034
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004035 public GetAccountsByTypeAndFeatureSession(
4036 UserAccounts accounts,
4037 IAccountManagerResponse response,
4038 String type,
4039 String[] features,
4040 int callingUid,
4041 String packageName) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004042 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004043 true /* stripAuthTokenFromResult */, null /* accountName */,
4044 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004045 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07004046 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004047 mPackageName = packageName;
Fred Quintana33269202009-04-20 16:05:10 -07004048 }
4049
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004050 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004051 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004052 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
4053 mCallingUid, mPackageName, false /* include managed not visible*/);
Fred Quintana33269202009-04-20 16:05:10 -07004054 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07004055 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07004056 mCurrentAccount = 0;
4057
4058 checkAccount();
4059 }
4060
4061 public void checkAccount() {
4062 if (mCurrentAccount >= mAccountsOfType.length) {
4063 sendResult();
4064 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07004065 }
Fred Quintana33269202009-04-20 16:05:10 -07004066
Fred Quintana29e94b82010-03-10 12:11:51 -08004067 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
4068 if (accountAuthenticator == null) {
4069 // It is possible that the authenticator has died, which is indicated by
4070 // mAuthenticator being set to null. If this happens then just abort.
4071 // There is no need to send back a result or error in this case since
4072 // that already happened when mAuthenticator was cleared.
4073 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4074 Log.v(TAG, "checkAccount: aborting session since we are no longer"
4075 + " connected to the authenticator, " + toDebugString());
4076 }
4077 return;
4078 }
Fred Quintana33269202009-04-20 16:05:10 -07004079 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08004080 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07004081 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004082 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07004083 }
4084 }
4085
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004086 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004087 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004088 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07004089 mNumResults++;
4090 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004091 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07004092 return;
4093 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004094 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07004095 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
4096 }
4097 mCurrentAccount++;
4098 checkAccount();
4099 }
4100
4101 public void sendResult() {
4102 IAccountManagerResponse response = getResponseAndClose();
4103 if (response != null) {
4104 try {
4105 Account[] accounts = new Account[mAccountsWithFeatures.size()];
4106 for (int i = 0; i < accounts.length; i++) {
4107 accounts[i] = mAccountsWithFeatures.get(i);
4108 }
Fred Quintana56285a62010-12-02 14:20:51 -08004109 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4110 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
4111 + response);
4112 }
Fred Quintana33269202009-04-20 16:05:10 -07004113 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004114 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004115 response.onResult(result);
4116 } catch (RemoteException e) {
4117 // if the caller is dead then there is no one to care about remote exceptions
4118 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4119 Log.v(TAG, "failure while notifying response", e);
4120 }
4121 }
4122 }
4123 }
4124
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004125 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004126 protected String toDebugString(long now) {
4127 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4128 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4129 }
4130 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004131
Amith Yamasani04e0d262012-02-14 11:50:53 -08004132 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004133 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004134 * @hide
4135 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004136 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004137 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004138 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004139 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004140 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4141 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004142 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004143 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004144 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004145 long identityToken = clearCallingIdentity();
4146 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004147 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004148 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004149 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004150 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004151 opPackageName,
4152 visibleAccountTypes,
4153 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004154 } finally {
4155 restoreCallingIdentity(identityToken);
4156 }
4157 }
4158
Amith Yamasanif29f2362012-04-05 18:29:52 -07004159 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004160 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004161 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004162 * @hide
4163 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004164 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004165 public AccountAndUser[] getRunningAccounts() {
4166 final int[] runningUserIds;
4167 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004168 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004169 } catch (RemoteException e) {
4170 // Running in system_server; should never happen
4171 throw new RuntimeException(e);
4172 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004173 return getAccounts(runningUserIds);
4174 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004175
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004176 /**
4177 * Returns accounts for all users, ignores visibility values.
4178 *
4179 * @hide
4180 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004181 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004182 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004183 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004184 final int[] userIds = new int[users.size()];
4185 for (int i = 0; i < userIds.length; i++) {
4186 userIds[i] = users.get(i).id;
4187 }
4188 return getAccounts(userIds);
4189 }
4190
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004191 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004192 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004193 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004194 for (int userId : userIds) {
4195 UserAccounts userAccounts = getUserAccounts(userId);
4196 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004197 Account[] accounts = getAccountsFromCache(
4198 userAccounts,
4199 null /* type */,
4200 Binder.getCallingUid(),
4201 null /* packageName */,
4202 false /* include managed not visible*/);
4203 for (Account account : accounts) {
4204 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004205 }
4206 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004207
4208 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4209 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004210 }
4211
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004212 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004213 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004214 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004215 int callingUid = Binder.getCallingUid();
4216 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004217 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004218 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004219 }
4220
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004221 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004222 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004223 String type,
4224 int userId,
4225 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004226 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004227 String opPackageName,
4228 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004229 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004230 // Only allow the system process to read accounts of other users
4231 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004232 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004233 && mContext.checkCallingOrSelfPermission(
4234 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4235 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004236 throw new SecurityException("User " + UserHandle.getCallingUserId()
4237 + " trying to get account for " + userId);
4238 }
4239
Fred Quintana56285a62010-12-02 14:20:51 -08004240 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4241 Log.v(TAG, "getAccounts: accountType " + type
4242 + ", caller's uid " + Binder.getCallingUid()
4243 + ", pid " + Binder.getCallingPid());
4244 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004245
4246 // If the original calling app was using account choosing activity
4247 // provided by the framework or authenticator we'll passing in
4248 // the original caller's uid here, which is what should be used for filtering.
4249 List<String> managedTypes =
4250 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4251 if (packageUid != -1 &&
4252 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4253 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004254 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004255 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004256 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004257 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4258 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004259 if (visibleAccountTypes.isEmpty()
4260 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004261 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004262 } else if (visibleAccountTypes.contains(type)) {
4263 // Prune the list down to just the requested type.
4264 visibleAccountTypes = new ArrayList<>();
4265 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004266 } // else aggregate all the visible accounts (it won't matter if the
4267 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004268
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004269 long identityToken = clearCallingIdentity();
4270 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004271 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004272 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004273 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004274 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004275 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004276 visibleAccountTypes,
4277 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004278 } finally {
4279 restoreCallingIdentity(identityToken);
4280 }
4281 }
4282
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004283 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004284 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004285 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004286 int callingUid,
4287 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004288 List<String> visibleAccountTypes,
4289 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004290 ArrayList<Account> visibleAccounts = new ArrayList<>();
4291 for (String visibleType : visibleAccountTypes) {
4292 Account[] accountsForType = getAccountsFromCache(
4293 userAccounts, visibleType, callingUid, callingPackage,
4294 includeUserManagedNotVisible);
4295 if (accountsForType != null) {
4296 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004297 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004298 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004299 Account[] result = new Account[visibleAccounts.size()];
4300 for (int i = 0; i < visibleAccounts.size(); i++) {
4301 result[i] = visibleAccounts.get(i);
4302 }
4303 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004304 }
4305
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004306 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004307 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4308 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004309 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004310 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004311 for (Account account : accounts) {
4312 addSharedAccountAsUser(account, userId);
4313 }
4314 }
4315
4316 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004317 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004318 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004319 accounts.accountsDb.deleteSharedAccount(account);
4320 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004321 if (accountId < 0) {
4322 Log.w(TAG, "insertAccountIntoDatabase: " + account
4323 + ", skipping the DB insert failed");
4324 return false;
4325 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004326 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4327 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004328 return true;
4329 }
4330
4331 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004332 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4333 userId = handleIncomingUser(userId);
4334 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004335 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4336 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004337 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004338 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004339 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004340 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004341 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004342 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004343 }
4344 return r > 0;
4345 }
4346
4347 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004348 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004349 return removeSharedAccountAsUser(account, userId, getCallingUid());
4350 }
4351
4352 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004353 userId = handleIncomingUser(userId);
4354 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004355 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4356 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004357 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004358 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004359 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004360 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004361 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004362 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004363 }
4364
4365 @Override
4366 public Account[] getSharedAccountsAsUser(int userId) {
4367 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004368 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004369 synchronized (accounts.dbLock) {
4370 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4371 Account[] accountArray = new Account[accountList.size()];
4372 accountList.toArray(accountArray);
4373 return accountArray;
4374 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004375 }
4376
4377 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004378 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004379 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004380 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004381 }
4382
Amith Yamasani27db4682013-03-30 17:07:47 -07004383 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004384 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004385 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004386 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004387 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004388 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004389 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4390 + callingUid + " with uid=" + uid);
4391 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004392 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004393 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004394 }
4395
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004396 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004397 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004398 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4399 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004400 int callingUid = Binder.getCallingUid();
4401 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004402 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004403 int packageUid = -1;
4404 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004405 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4406 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004407 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004408 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004409 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004410 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004411 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4412 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004413 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004414 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004415 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004416 }
4417
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004418 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004419 public void getAccountsByFeatures(
4420 IAccountManagerResponse response,
4421 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004422 String[] features,
4423 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004424 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004425 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004426 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4427 Log.v(TAG, "getAccounts: accountType " + type
4428 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004429 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004430 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004431 + ", pid " + Binder.getCallingPid());
4432 }
Fred Quintana382601f2010-03-25 12:25:10 -07004433 if (response == null) throw new IllegalArgumentException("response is null");
4434 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004435 int userId = UserHandle.getCallingUserId();
4436
Svetoslavf3f02ac2015-09-08 14:36:35 -07004437 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4438 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004439 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004440 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004441 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004442 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004443 try {
4444 response.onResult(result);
4445 } catch (RemoteException e) {
4446 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4447 }
4448 return;
4449 }
Fred Quintana33269202009-04-20 16:05:10 -07004450 long identityToken = clearCallingIdentity();
4451 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004452 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004453 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004454 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4455 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004456 Bundle result = new Bundle();
4457 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4458 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004459 return;
4460 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004461 new GetAccountsByTypeAndFeatureSession(
4462 userAccounts,
4463 response,
4464 type,
4465 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004466 callingUid,
4467 opPackageName).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004468 } finally {
4469 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004470 }
4471 }
4472
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004473 @Override
4474 public void onAccountAccessed(String token) throws RemoteException {
4475 final int uid = Binder.getCallingUid();
4476 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4477 return;
4478 }
4479 final int userId = UserHandle.getCallingUserId();
4480 final long identity = Binder.clearCallingIdentity();
4481 try {
4482 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4483 if (Objects.equals(account.getAccessId(), token)) {
4484 // An app just accessed the account. At this point it knows about
4485 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004486 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004487 if (!hasAccountAccess(account, null, uid)) {
4488 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4489 uid, true);
4490 }
4491 }
4492 }
4493 } finally {
4494 Binder.restoreCallingIdentity(identity);
4495 }
4496 }
4497
Fred Quintanaa698f422009-04-08 19:14:54 -07004498 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004499 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004500 IAccountManagerResponse mResponse;
4501 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004502 final boolean mExpectActivityLaunch;
4503 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004504 final String mAccountName;
4505 // Indicates if we need to add auth details(like last credential time)
4506 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004507 // If set, we need to update the last authenticated time. This is
4508 // currently
4509 // used on
4510 // successful confirming credentials.
4511 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004512
Fred Quintana33269202009-04-20 16:05:10 -07004513 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004514 private int mNumRequestContinued = 0;
4515 private int mNumErrors = 0;
4516
Fred Quintana60307342009-03-24 22:48:12 -07004517 IAccountAuthenticator mAuthenticator = null;
4518
Fred Quintana8570f742010-02-18 10:32:54 -08004519 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004520 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004521
Amith Yamasani04e0d262012-02-14 11:50:53 -08004522 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004523 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4524 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004525 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4526 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4527 }
4528
4529 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4530 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4531 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004532 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004533 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004534 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004535 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004536 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004537 mResponse = response;
4538 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004539 mExpectActivityLaunch = expectActivityLaunch;
4540 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004541 mAccountName = accountName;
4542 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004543 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004544
Fred Quintanaa698f422009-04-08 19:14:54 -07004545 synchronized (mSessions) {
4546 mSessions.put(toString(), this);
4547 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004548 if (response != null) {
4549 try {
4550 response.asBinder().linkToDeath(this, 0 /* flags */);
4551 } catch (RemoteException e) {
4552 mResponse = null;
4553 binderDied();
4554 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004555 }
Fred Quintana60307342009-03-24 22:48:12 -07004556 }
4557
Fred Quintanaa698f422009-04-08 19:14:54 -07004558 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004559 if (mResponse == null) {
4560 // this session has already been closed
4561 return null;
4562 }
Fred Quintana60307342009-03-24 22:48:12 -07004563 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004564 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004565 return response;
4566 }
4567
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004568 /**
4569 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4570 * security policy.
4571 *
4572 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004573 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004574 * supplied entries in the system Settings app.
4575 */
4576 protected void checkKeyIntent(
4577 int authUid,
4578 Intent intent) throws SecurityException {
4579 long bid = Binder.clearCallingIdentity();
4580 try {
4581 PackageManager pm = mContext.getPackageManager();
4582 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4583 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4584 int targetUid = targetActivityInfo.applicationInfo.uid;
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004585 if (!isExportedSystemActivity(targetActivityInfo)
4586 && (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid,
4587 targetUid))) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004588 String pkgName = targetActivityInfo.packageName;
4589 String activityName = targetActivityInfo.name;
4590 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4591 + "does not share a signature with the supplying authenticator (%s).";
4592 throw new SecurityException(
4593 String.format(tmpl, activityName, pkgName, mAccountType));
4594 }
4595 } finally {
4596 Binder.restoreCallingIdentity(bid);
4597 }
4598 }
4599
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004600 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4601 String className = activityInfo.name;
4602 return "android".equals(activityInfo.packageName) &&
4603 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4604 || CantAddAccountActivity.class.getName().equals(className));
4605 }
4606
Fred Quintanaa698f422009-04-08 19:14:54 -07004607 private void close() {
4608 synchronized (mSessions) {
4609 if (mSessions.remove(toString()) == null) {
4610 // the session was already closed, so bail out now
4611 return;
4612 }
4613 }
4614 if (mResponse != null) {
4615 // stop listening for response deaths
4616 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4617
4618 // clear this so that we don't accidentally send any further results
4619 mResponse = null;
4620 }
4621 cancelTimeout();
4622 unbind();
4623 }
4624
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004625 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004626 public void binderDied() {
4627 mResponse = null;
4628 close();
4629 }
4630
4631 protected String toDebugString() {
4632 return toDebugString(SystemClock.elapsedRealtime());
4633 }
4634
4635 protected String toDebugString(long now) {
4636 return "Session: expectLaunch " + mExpectActivityLaunch
4637 + ", connected " + (mAuthenticator != null)
4638 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4639 + "/" + mNumErrors + ")"
4640 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4641 }
4642
Fred Quintana60307342009-03-24 22:48:12 -07004643 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004644 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4645 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4646 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004647 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004648 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004649 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004650 }
4651 }
4652
4653 private void unbind() {
4654 if (mAuthenticator != null) {
4655 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004656 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004657 }
4658 }
4659
Fred Quintana60307342009-03-24 22:48:12 -07004660 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004661 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004662 }
4663
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004664 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004665 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004666 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004667 try {
4668 run();
4669 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004670 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004671 "remote exception");
4672 }
Fred Quintana60307342009-03-24 22:48:12 -07004673 }
4674
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004675 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004676 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004677 mAuthenticator = null;
4678 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004679 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004680 try {
4681 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4682 "disconnected");
4683 } catch (RemoteException e) {
4684 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4685 Log.v(TAG, "Session.onServiceDisconnected: "
4686 + "caught RemoteException while responding", e);
4687 }
4688 }
Fred Quintana60307342009-03-24 22:48:12 -07004689 }
4690 }
4691
Fred Quintanab839afc2009-10-14 15:57:28 -07004692 public abstract void run() throws RemoteException;
4693
Fred Quintana60307342009-03-24 22:48:12 -07004694 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004695 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004696 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004697 try {
4698 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4699 "timeout");
4700 } catch (RemoteException e) {
4701 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4702 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4703 e);
4704 }
4705 }
Fred Quintana60307342009-03-24 22:48:12 -07004706 }
4707 }
4708
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004709 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004710 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004711 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004712 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004713 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004714 if (result != null) {
4715 boolean isSuccessfulConfirmCreds = result.getBoolean(
4716 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004717 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004718 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4719 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004720 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004721 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4722 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004723 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004724 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004725 if (needUpdate || mAuthDetailsRequired) {
4726 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4727 if (needUpdate && accountPresent) {
4728 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4729 }
4730 if (mAuthDetailsRequired) {
4731 long lastAuthenticatedTime = -1;
4732 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004733 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004734 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004735 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004736 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004737 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004738 lastAuthenticatedTime);
4739 }
4740 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004741 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004742 if (result != null
4743 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004744 checkKeyIntent(
4745 Binder.getCallingUid(),
4746 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004747 }
4748 if (result != null
4749 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004750 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4751 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004752 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4753 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004754 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4755 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004756 }
Fred Quintana60307342009-03-24 22:48:12 -07004757 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004758 IAccountManagerResponse response;
4759 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004760 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004761 response = mResponse;
4762 } else {
4763 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004764 }
Fred Quintana60307342009-03-24 22:48:12 -07004765 if (response != null) {
4766 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004767 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004768 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4769 Log.v(TAG, getClass().getSimpleName()
4770 + " calling onError() on response " + response);
4771 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004772 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004773 "null bundle returned");
4774 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004775 if (mStripAuthTokenFromResult) {
4776 result.remove(AccountManager.KEY_AUTHTOKEN);
4777 }
Fred Quintana56285a62010-12-02 14:20:51 -08004778 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4779 Log.v(TAG, getClass().getSimpleName()
4780 + " calling onResult() on response " + response);
4781 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004782 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4783 (intent == null)) {
4784 // All AccountManager error codes are greater than 0
4785 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4786 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4787 } else {
4788 response.onResult(result);
4789 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004790 }
Fred Quintana60307342009-03-24 22:48:12 -07004791 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004792 // if the caller is dead then there is no one to care about remote exceptions
4793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4794 Log.v(TAG, "failure while notifying response", e);
4795 }
Fred Quintana60307342009-03-24 22:48:12 -07004796 }
4797 }
4798 }
Fred Quintana60307342009-03-24 22:48:12 -07004799
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004800 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004801 public void onRequestContinued() {
4802 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004803 }
4804
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004805 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004806 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004807 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004808 IAccountManagerResponse response = getResponseAndClose();
4809 if (response != null) {
4810 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004811 Log.v(TAG, getClass().getSimpleName()
4812 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004813 }
4814 try {
4815 response.onError(errorCode, errorMessage);
4816 } catch (RemoteException e) {
4817 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4818 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4819 }
4820 }
4821 } else {
4822 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4823 Log.v(TAG, "Session.onError: already closed");
4824 }
Fred Quintana60307342009-03-24 22:48:12 -07004825 }
4826 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004827
4828 /**
4829 * find the component name for the authenticator and initiate a bind
4830 * if no authenticator or the bind fails then return false, otherwise return true
4831 */
4832 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004833 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4834 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4835 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004836 if (authenticatorInfo == null) {
4837 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4838 Log.v(TAG, "there is no authenticator for " + authenticatorType
4839 + ", bailing out");
4840 }
4841 return false;
4842 }
4843
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004844 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004845 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004846 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4847 + " which isn't encryption aware");
4848 return false;
4849 }
4850
Fred Quintanab839afc2009-10-14 15:57:28 -07004851 Intent intent = new Intent();
4852 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4853 intent.setComponent(authenticatorInfo.componentName);
4854 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4855 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4856 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004857 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004858 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004859 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4860 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4861 }
4862 return false;
4863 }
4864
Fred Quintanab839afc2009-10-14 15:57:28 -07004865 return true;
4866 }
Fred Quintana60307342009-03-24 22:48:12 -07004867 }
4868
Svet Ganov5d09c992016-09-07 09:57:41 -07004869 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07004870 MessageHandler(Looper looper) {
4871 super(looper);
4872 }
Costin Manolache3348f142009-09-29 18:58:36 -07004873
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004874 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004875 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004876 switch (msg.what) {
4877 case MESSAGE_TIMED_OUT:
4878 Session session = (Session)msg.obj;
4879 session.onTimedOut();
4880 break;
4881
Amith Yamasani5be347b2013-03-31 17:44:31 -07004882 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004883 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004884 break;
4885
Fred Quintana60307342009-03-24 22:48:12 -07004886 default:
4887 throw new IllegalStateException("unhandled message: " + msg.what);
4888 }
4889 }
4890 }
4891
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004892 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004893 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004894 }
4895
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004896 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004897 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004898 }
4899
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004900 /*
4901 * This function receives an opened writable database.
4902 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004903 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004904 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004905 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004906 }
4907
4908 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004909 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004910 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004911 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004912 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004913
4914 class LogRecordTask implements Runnable {
4915 private final String action;
4916 private final String tableName;
4917 private final long accountId;
4918 private final UserAccounts userAccount;
4919 private final int callingUid;
4920 private final long userDebugDbInsertionPoint;
4921
4922 LogRecordTask(final String action,
4923 final String tableName,
4924 final long accountId,
4925 final UserAccounts userAccount,
4926 final int callingUid,
4927 final long userDebugDbInsertionPoint) {
4928 this.action = action;
4929 this.tableName = tableName;
4930 this.accountId = accountId;
4931 this.userAccount = userAccount;
4932 this.callingUid = callingUid;
4933 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
4934 }
4935
4936 public void run() {
4937 SQLiteStatement logStatement = userAccount.statementForLogging;
4938 logStatement.bindLong(1, accountId);
4939 logStatement.bindString(2, action);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004940 logStatement.bindString(3, mDateFormat.format(new Date()));
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004941 logStatement.bindLong(4, callingUid);
4942 logStatement.bindString(5, tableName);
4943 logStatement.bindLong(6, userDebugDbInsertionPoint);
4944 logStatement.execute();
4945 logStatement.clearBindings();
4946 }
4947 }
4948
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004949 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
4950 callingUid, userAccount.debugDbInsertionPoint);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004951 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004952 % AccountsDb.MAX_DEBUG_DB_SIZE;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004953 mHandler.post(logTask);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004954 }
4955
4956 /*
4957 * This should only be called once to compile the sql statement for logging
4958 * and to find the insertion point.
4959 */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004960 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(UserAccounts userAccount) {
4961 userAccount.debugDbInsertionPoint = userAccount.accountsDb
4962 .calculateDebugTableInsertionPoint();
4963 userAccount.statementForLogging = userAccount.accountsDb.compileSqlStatementForLogging();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004964 }
4965
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004966 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004967 return asBinder();
4968 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004969
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004970 /**
4971 * Searches array of arguments for the specified string
4972 * @param args array of argument strings
4973 * @param value value to search for
4974 * @return true if the value is contained in the array
4975 */
4976 private static boolean scanArgs(String[] args, String value) {
4977 if (args != null) {
4978 for (String arg : args) {
4979 if (value.equals(arg)) {
4980 return true;
4981 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004982 }
4983 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004984 return false;
4985 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004986
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004987 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004988 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004989 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004990 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004991 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004992
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004993 final List<UserInfo> users = getUserManager().getUsers();
4994 for (UserInfo user : users) {
4995 ipw.println("User " + user + ":");
4996 ipw.increaseIndent();
4997 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4998 ipw.println();
4999 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005000 }
5001 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005002
Amith Yamasani04e0d262012-02-14 11:50:53 -08005003 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5004 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005005 if (isCheckinRequest) {
5006 // This is a checkin request. *Only* upload the account types and the count of
5007 // each.
5008 synchronized (userAccounts.dbLock) {
5009 userAccounts.accountsDb.dumpDeAccountsTable(fout);
5010 }
5011 } else {
5012 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
5013 Process.SYSTEM_UID, null /* packageName */, false);
5014 fout.println("Accounts: " + accounts.length);
5015 for (Account account : accounts) {
5016 fout.println(" " + account);
5017 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005018
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005019 // Add debug information.
5020 fout.println();
5021 synchronized (userAccounts.dbLock) {
5022 userAccounts.accountsDb.dumpDebugTable(fout);
5023 }
5024 fout.println();
5025 synchronized (mSessions) {
5026 final long now = SystemClock.elapsedRealtime();
5027 fout.println("Active Sessions: " + mSessions.size());
5028 for (Session session : mSessions.values()) {
5029 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005030 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005031 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005032
5033 fout.println();
5034 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005035 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005036 }
5037
Amith Yamasani04e0d262012-02-14 11:50:53 -08005038 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005039 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005040 long identityToken = clearCallingIdentity();
5041 try {
5042 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5043 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5044 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005045
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005046 if (intent.getComponent() != null &&
5047 GrantCredentialsPermissionActivity.class.getName().equals(
5048 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005049 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005050 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005051 Context contextForUser = getContextForUser(new UserHandle(userId));
Chris Wren717a8812017-03-31 15:34:39 -04005052 final NotificationId id = getSigninRequiredNotificationId(accounts, account);
5053 intent.addCategory(id.mTag);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005054
Fred Quintana33f889a2009-09-14 17:31:26 -07005055 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005056 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05005057 Notification n =
5058 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005059 .setWhen(0)
5060 .setSmallIcon(android.R.drawable.stat_sys_warning)
5061 .setColor(contextForUser.getColor(
5062 com.android.internal.R.color.system_notification_accent_color))
5063 .setContentTitle(String.format(notificationTitleFormat, account.name))
5064 .setContentText(message)
5065 .setContentIntent(PendingIntent.getActivityAsUser(
5066 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005067 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005068 .build();
Chris Wren717a8812017-03-31 15:34:39 -04005069 installNotification(id, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005070 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005071 } finally {
5072 restoreCallingIdentity(identityToken);
5073 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005074 }
5075
Chris Wren717a8812017-03-31 15:34:39 -04005076 private void installNotification(NotificationId id, final Notification notification,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005077 String packageName, int userId) {
5078 final long token = clearCallingIdentity();
5079 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005080 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005081 try {
Chris Wren717a8812017-03-31 15:34:39 -04005082 notificationManager.enqueueNotificationWithTag(packageName, packageName,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04005083 id.mTag, id.mId, notification, userId);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005084 } catch (RemoteException e) {
5085 /* ignore - local call */
5086 }
5087 } finally {
5088 Binder.restoreCallingIdentity(token);
5089 }
Fred Quintana56285a62010-12-02 14:20:51 -08005090 }
5091
Chris Wren717a8812017-03-31 15:34:39 -04005092 private void cancelNotification(NotificationId id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005093 cancelNotification(id, mContext.getPackageName(), user);
5094 }
5095
Chris Wren717a8812017-03-31 15:34:39 -04005096 private void cancelNotification(NotificationId id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005097 long identityToken = clearCallingIdentity();
5098 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005099 INotificationManager service = mInjector.getNotificationManager();
Chris Wren717a8812017-03-31 15:34:39 -04005100 service.cancelNotificationWithTag(packageName, id.mTag, id.mId, user.getIdentifier());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005101 } catch (RemoteException e) {
5102 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005103 } finally {
5104 restoreCallingIdentity(identityToken);
5105 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005106 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005107
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005108 private boolean isPermittedForPackage(String packageName, int uid, int userId,
5109 String... permissions) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005110 final long identity = Binder.clearCallingIdentity();
5111 try {
5112 IPackageManager pm = ActivityThread.getPackageManager();
5113 for (String perm : permissions) {
5114 if (pm.checkPermission(perm, packageName, userId)
5115 == PackageManager.PERMISSION_GRANTED) {
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005116 // Checks runtime permission revocation.
5117 final int opCode = AppOpsManager.permissionToOpCode(perm);
5118 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5119 opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
5120 return true;
5121 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005122 }
5123 }
5124 } catch (RemoteException e) {
5125 /* ignore - local call */
5126 } finally {
5127 Binder.restoreCallingIdentity(identity);
5128 }
5129 return false;
5130 }
5131
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005132 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5133 for (String perm : permissions) {
5134 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5135 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5136 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5137 }
5138 final int opCode = AppOpsManager.permissionToOpCode(perm);
5139 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5140 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5141 return true;
5142 }
5143 }
5144 }
5145 return false;
5146 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005147
Amith Yamasani67df64b2012-12-14 12:09:36 -08005148 private int handleIncomingUser(int userId) {
5149 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005150 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005151 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5152 } catch (RemoteException re) {
5153 // Shouldn't happen, local.
5154 }
5155 return userId;
5156 }
5157
Christopher Tateccbf84f2013-05-08 15:25:41 -07005158 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005159 String[] packages;
5160 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005161 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005162 packages = mPackageManager.getPackagesForUid(callingUid);
5163 } finally {
5164 Binder.restoreCallingIdentity(identityToken);
5165 }
5166 if (packages == null) {
5167 Log.d(TAG, "No packages for callingUid " + callingUid);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005168 return false;
5169 }
Fred Quintana7be59642009-08-24 18:29:25 -07005170 for (String name : packages) {
5171 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005172 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005173 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005174 && (packageInfo.applicationInfo.privateFlags
5175 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005176 return true;
5177 }
5178 } catch (PackageManager.NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005179 Log.d(TAG, "Package not found " + e.getMessage());
Fred Quintana7be59642009-08-24 18:29:25 -07005180 return false;
5181 }
5182 }
5183 return false;
5184 }
5185
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005186 private boolean permissionIsGranted(
5187 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005188 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5189 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5190 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5191 }
5192 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005193 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005194
5195 if (isPrivileged(callerUid)) {
5196 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5197 Log.v(TAG, "Access to " + account + " granted calling uid "
5198 + callerUid + " privileged");
5199 }
5200 return true;
5201 }
5202 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5203 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5204 Log.v(TAG, "Access to " + account + " granted calling uid "
5205 + callerUid + " manages the account");
5206 }
5207 return true;
5208 }
5209 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5210 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5211 Log.v(TAG, "Access to " + account + " granted calling uid "
5212 + callerUid + " user granted access");
5213 }
5214 return true;
5215 }
5216
5217 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5218 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5219 }
5220
5221 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005222 }
5223
Svetoslavf3f02ac2015-09-08 14:36:35 -07005224 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5225 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005226 if (accountType == null) {
5227 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005228 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005229 return getTypesVisibleToCaller(callingUid, userId,
5230 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005231 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005232 }
5233
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005234 // Method checks visibility for applications targeing API level below {@link
5235 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005236 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005237 private boolean checkGetAccountsPermission(String packageName, int uid, int userId) {
5238 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.GET_ACCOUNTS,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005239 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5240 }
5241
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005242 private boolean checkReadContactsPermission(String packageName, int uid, int userId) {
5243 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.READ_CONTACTS);
5244 }
5245
5246 // Heuristic to check that account type may be associated with some contacts data and
5247 // therefore READ_CONTACTS permission grants the access to account by default.
5248 private boolean accountTypeManagesContacts(String accountType, int userId) {
5249 if (accountType == null) {
5250 return false;
5251 }
5252 long identityToken = Binder.clearCallingIdentity();
5253 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5254 try {
5255 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5256 } finally {
5257 Binder.restoreCallingIdentity(identityToken);
5258 }
5259 // Check contacts related permissions for authenticator.
5260 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5261 : serviceInfos) {
5262 if (accountType.equals(serviceInfo.type.type)) {
5263 return isPermittedForPackage(serviceInfo.type.packageName, serviceInfo.uid, userId,
5264 Manifest.permission.WRITE_CONTACTS);
5265 }
5266 }
5267 return false;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005268 }
5269
5270 /**
5271 * Method checks package uid and signature with Authenticator which manages accountType.
5272 *
5273 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5274 * SIGNATURE_CHECK_MISMATCH otherwise.
5275 */
5276 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5277 if (accountType == null) {
5278 return SIGNATURE_CHECK_MISMATCH;
5279 }
5280
5281 long identityToken = Binder.clearCallingIdentity();
5282 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5283 try {
5284 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5285 } finally {
5286 Binder.restoreCallingIdentity(identityToken);
5287 }
5288 // Check for signature match with Authenticator.
5289 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5290 : serviceInfos) {
5291 if (accountType.equals(serviceInfo.type.type)) {
5292 if (serviceInfo.uid == callingUid) {
5293 return SIGNATURE_CHECK_UID_MATCH;
5294 }
5295 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5296 if (sigChk == PackageManager.SIGNATURE_MATCH) {
5297 return SIGNATURE_CHECK_MATCH;
5298 }
5299 }
5300 }
5301 return SIGNATURE_CHECK_MISMATCH;
5302 }
5303
5304 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005305 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5306 if (accountType == null) {
5307 return false;
5308 } else {
5309 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5310 }
5311 }
5312
Svetoslavf3f02ac2015-09-08 14:36:35 -07005313 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5314 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005315 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005316 }
5317
5318 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005319 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005320 }
5321
5322 private List<String> getTypesForCaller(
5323 int callingUid, int userId, boolean isOtherwisePermitted) {
5324 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005325 long identityToken = Binder.clearCallingIdentity();
5326 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5327 try {
5328 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5329 } finally {
5330 Binder.restoreCallingIdentity(identityToken);
5331 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005332 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005333 serviceInfos) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005334 if (isOtherwisePermitted || (mPackageManager.checkSignatures(serviceInfo.uid,
5335 callingUid) == PackageManager.SIGNATURE_MATCH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005336 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005337 }
5338 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005339 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005340 }
5341
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005342 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5343 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5344 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5345 if (account.name.equals(accountName)) {
5346 return true;
5347 }
5348 }
5349 }
5350 return false;
5351 }
5352
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005353 private static void checkManageUsersPermission(String message) {
5354 if (ActivityManager.checkComponentPermission(
5355 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5356 != PackageManager.PERMISSION_GRANTED) {
5357 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5358 }
5359 }
5360
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005361 private static void checkManageOrCreateUsersPermission(String message) {
5362 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5363 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5364 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5365 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5366 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5367 + message);
5368 }
5369 }
5370
Amith Yamasani04e0d262012-02-14 11:50:53 -08005371 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5372 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005373 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005374 return true;
5375 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005376 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005377 synchronized (accounts.dbLock) {
5378 synchronized (accounts.cacheLock) {
5379 long grantsCount;
5380 if (authTokenType != null) {
5381 grantsCount = accounts.accountsDb
5382 .findMatchingGrantsCount(callerUid, authTokenType, account);
5383 } else {
5384 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5385 account);
5386 }
5387 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005388
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005389 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5390 // TODO: Skip this check when running automated tests. Replace this
5391 // with a more general solution.
5392 Log.d(TAG, "no credentials permission for usage of " + account + ", "
5393 + authTokenType + " by uid " + callerUid
5394 + " but ignoring since device is in test harness.");
5395 return true;
5396 }
5397 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005398 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005399 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005400 }
5401
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005402 private boolean isSystemUid(int callingUid) {
5403 String[] packages = null;
5404 long ident = Binder.clearCallingIdentity();
5405 try {
5406 packages = mPackageManager.getPackagesForUid(callingUid);
5407 } finally {
5408 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005409 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005410 if (packages != null) {
5411 for (String name : packages) {
5412 try {
5413 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5414 if (packageInfo != null
5415 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5416 != 0) {
5417 return true;
5418 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005419 } catch (NameNotFoundException e) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005420 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5421 }
5422 }
5423 } else {
5424 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005425 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005426 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005427 }
5428
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005429 /** Succeeds if any of the specified permissions are granted. */
5430 private void checkReadAccountsPermitted(
5431 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005432 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005433 int userId,
5434 String opPackageName) {
5435 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005436 String msg = String.format(
5437 "caller uid %s cannot access %s accounts",
5438 callingUid,
5439 accountType);
5440 Log.w(TAG, " " + msg);
5441 throw new SecurityException(msg);
5442 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005443 }
5444
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005445 private boolean canUserModifyAccounts(int userId, int callingUid) {
5446 // the managing app can always modify accounts
5447 if (isProfileOwner(callingUid)) {
5448 return true;
5449 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005450 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5451 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5452 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005453 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005454 return true;
5455 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005456
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005457 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5458 // the managing app can always modify accounts
5459 if (isProfileOwner(callingUid)) {
5460 return true;
5461 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005462 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5463 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005464 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005465 if (typesArray == null) {
5466 return true;
5467 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005468 for (String forbiddenType : typesArray) {
5469 if (forbiddenType.equals(accountType)) {
5470 return false;
5471 }
5472 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005473 return true;
5474 }
5475
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005476 private boolean isProfileOwner(int uid) {
5477 final DevicePolicyManagerInternal dpmi =
5478 LocalServices.getService(DevicePolicyManagerInternal.class);
5479 return (dpmi != null)
5480 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5481 }
5482
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005483 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005484 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5485 throws RemoteException {
5486 final int callingUid = getCallingUid();
5487
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005488 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005489 throw new SecurityException();
5490 }
5491
5492 if (value) {
5493 grantAppPermission(account, authTokenType, uid);
5494 } else {
5495 revokeAppPermission(account, authTokenType, uid);
5496 }
5497 }
5498
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005499 /**
5500 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5501 * <p>
5502 * Although this is public it can only be accessed via the AccountManagerService object
5503 * which is in the system. This means we don't need to protect it with permissions.
5504 * @hide
5505 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005506 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005507 if (account == null || authTokenType == null) {
5508 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005509 return;
5510 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005511 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005512 synchronized (accounts.dbLock) {
5513 synchronized (accounts.cacheLock) {
5514 long accountId = accounts.accountsDb.findDeAccountId(account);
5515 if (accountId >= 0) {
5516 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5517 }
5518 cancelNotification(
5519 getCredentialPermissionNotificationId(account, authTokenType, uid),
5520 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005521
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005522 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5523 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005524 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005525
5526 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5527 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5528 : mAppPermissionChangeListeners) {
5529 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5530 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005531 }
5532
5533 /**
5534 * Don't allow callers with the given uid permission to get credentials for
5535 * account/authTokenType.
5536 * <p>
5537 * Although this is public it can only be accessed via the AccountManagerService object
5538 * which is in the system. This means we don't need to protect it with permissions.
5539 * @hide
5540 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005541 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005542 if (account == null || authTokenType == null) {
5543 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005544 return;
5545 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005546 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005547 synchronized (accounts.dbLock) {
5548 synchronized (accounts.cacheLock) {
5549 accounts.accountsDb.beginTransaction();
5550 try {
5551 long accountId = accounts.accountsDb.findDeAccountId(account);
5552 if (accountId >= 0) {
5553 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5554 accountId, authTokenType, uid);
5555 accounts.accountsDb.setTransactionSuccessful();
5556 }
5557 } finally {
5558 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005559 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005560
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005561 cancelNotification(
5562 getCredentialPermissionNotificationId(account, authTokenType, uid),
5563 UserHandle.of(accounts.userId));
5564 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005565 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005566
5567 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5568 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5569 : mAppPermissionChangeListeners) {
5570 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5571 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005572 }
Fred Quintana56285a62010-12-02 14:20:51 -08005573
Amith Yamasani04e0d262012-02-14 11:50:53 -08005574 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5575 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005576 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005577 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005578 for (Account curAccount : oldAccountsForType) {
5579 if (!curAccount.equals(account)) {
5580 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005581 }
5582 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005583 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005584 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005585 } else {
5586 Account[] newAccountsForType = new Account[newAccountsList.size()];
5587 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005588 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005589 }
Fred Quintana56285a62010-12-02 14:20:51 -08005590 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005591 accounts.userDataCache.remove(account);
5592 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005593 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005594 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005595 }
5596
5597 /**
5598 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005599 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5600 * processes and if you will return this account to apps you should return the result.
5601 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005602 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005603 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005604 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005605 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5606 Account[] newAccountsForType = new Account[oldLength + 1];
5607 if (accountsForType != null) {
5608 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005609 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005610 String token = account.getAccessId() != null ? account.getAccessId()
5611 : UUID.randomUUID().toString();
5612 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005613 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005614 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005615 }
5616
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005617 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005618 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005619 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005620 String visibilityFilterPackage = callingPackage;
5621 if (visibilityFilterPackage == null) {
5622 visibilityFilterPackage = getPackageNameForUid(callingUid);
5623 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005624 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005625 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005626 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005627 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5628 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5629 || (includeManagedNotVisible
5630 && (visibility
5631 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5632 firstPass.put(account, visibility);
5633 }
5634 }
5635 Map<Account, Integer> secondPass =
5636 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5637
5638 Account[] filtered = new Account[secondPass.size()];
5639 filtered = secondPass.keySet().toArray(filtered);
5640 return filtered;
5641 }
5642
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005643 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005644 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005645 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005646 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005647 // first part is to filter shared accounts.
5648 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005649 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005650 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005651 return unfiltered;
5652 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005653 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005654 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005655 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005656 if (packages == null) {
5657 packages = new String[] {};
5658 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005659 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005660 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005661 // This might be a temporary way to specify a visible list
5662 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005663 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5664 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005665 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005666 return unfiltered;
5667 }
5668 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005669 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005670 if (ArrayUtils.isEmpty(sharedAccounts)) {
5671 return unfiltered;
5672 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005673 String requiredAccountType = "";
5674 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005675 // If there's an explicit callingPackage specified, check if that package
5676 // opted in to see restricted accounts.
5677 if (callingPackage != null) {
5678 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005679 if (pi != null && pi.restrictedAccountType != null) {
5680 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005681 }
5682 } else {
5683 // Otherwise check if the callingUid has a package that has opted in
5684 for (String packageName : packages) {
5685 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5686 if (pi != null && pi.restrictedAccountType != null) {
5687 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005688 break;
5689 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005690 }
5691 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005692 } catch (NameNotFoundException e) {
5693 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005694 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005695 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005696 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5697 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005698 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005699 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005700 } else {
5701 boolean found = false;
5702 for (Account shared : sharedAccounts) {
5703 if (shared.equals(account)) {
5704 found = true;
5705 break;
5706 }
5707 }
5708 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005709 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005710 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005711 }
5712 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005713 return filtered;
5714 } else {
5715 return unfiltered;
5716 }
5717 }
5718
Amith Yamasani27db4682013-03-30 17:07:47 -07005719 /*
5720 * packageName can be null. If not null, it should be used to filter out restricted accounts
5721 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005722 *
5723 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5724 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005725 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005726 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005727 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005728 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005729 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5730 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005731 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005732 Account[] accounts;
5733 synchronized (userAccounts.cacheLock) {
5734 accounts = userAccounts.accountCache.get(accountType);
5735 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005736 if (accounts == null) {
5737 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005738 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005739 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5740 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005741 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005742 } else {
5743 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005744 Account[] accountsArray;
5745 synchronized (userAccounts.cacheLock) {
5746 for (Account[] accounts : userAccounts.accountCache.values()) {
5747 totalLength += accounts.length;
5748 }
5749 if (totalLength == 0) {
5750 return EMPTY_ACCOUNT_ARRAY;
5751 }
5752 accountsArray = new Account[totalLength];
5753 totalLength = 0;
5754 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5755 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
5756 accountsOfType.length);
5757 totalLength += accountsOfType.length;
5758 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005759 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005760 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005761 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005762 }
5763 }
5764
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005765 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005766 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005767 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005768 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005769 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005770 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005771 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005772 }
5773 if (value == null) {
5774 userDataForAccount.remove(key);
5775 } else {
5776 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005777 }
5778 }
5779
Carlos Valdivia91979be2015-05-22 14:11:35 -07005780 protected String readCachedTokenInternal(
5781 UserAccounts accounts,
5782 Account account,
5783 String tokenType,
5784 String callingPackage,
5785 byte[] pkgSigDigest) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005786 synchronized (accounts.dbLock) {
5787 synchronized (accounts.cacheLock) {
5788 return accounts.accountTokenCaches.get(
5789 account, tokenType, callingPackage, pkgSigDigest);
5790 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07005791 }
5792 }
5793
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005794 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005795 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005796 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005797 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005798 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005799 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005800 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005801 }
5802 if (value == null) {
5803 authTokensForAccount.remove(key);
5804 } else {
5805 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005806 }
5807 }
5808
Amith Yamasani04e0d262012-02-14 11:50:53 -08005809 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5810 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005811 // Fast path - check if account is already cached
5812 synchronized (accounts.cacheLock) {
5813 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5814 if (authTokensForAccount != null) {
5815 return authTokensForAccount.get(authTokenType);
5816 }
5817 }
5818 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005819 synchronized (accounts.dbLock) {
5820 synchronized (accounts.cacheLock) {
5821 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5822 if (authTokensForAccount == null) {
5823 // need to populate the cache for this account
5824 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
5825 accounts.authTokenCache.put(account, authTokensForAccount);
5826 }
5827 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08005828 }
Fred Quintana56285a62010-12-02 14:20:51 -08005829 }
5830 }
5831
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005832 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
5833 Map<String, String> userDataForAccount;
5834 // Fast path - check if data is already cached
5835 synchronized (accounts.cacheLock) {
5836 userDataForAccount = accounts.userDataCache.get(account);
5837 }
5838 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00005839 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005840 synchronized (accounts.dbLock) {
5841 synchronized (accounts.cacheLock) {
5842 userDataForAccount = accounts.userDataCache.get(account);
5843 if (userDataForAccount == null) {
5844 // need to populate the cache for this account
5845 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
5846 accounts.userDataCache.put(account, userDataForAccount);
5847 }
5848 }
5849 }
Fred Quintana56285a62010-12-02 14:20:51 -08005850 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005851 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005852 }
5853
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005854 private Context getContextForUser(UserHandle user) {
5855 try {
5856 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5857 } catch (NameNotFoundException e) {
5858 // Default to mContext, not finding the package system is running as is unlikely.
5859 return mContext;
5860 }
5861 }
Sandra Kwan78812282015-11-04 11:19:47 -08005862
5863 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5864 try {
5865 response.onResult(result);
5866 } catch (RemoteException e) {
5867 // if the caller is dead then there is no one to care about remote
5868 // exceptions
5869 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5870 Log.v(TAG, "failure while notifying response", e);
5871 }
5872 }
5873 }
5874
5875 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5876 String errorMessage) {
5877 try {
5878 response.onError(errorCode, errorMessage);
5879 } catch (RemoteException e) {
5880 // if the caller is dead then there is no one to care about remote
5881 // exceptions
5882 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5883 Log.v(TAG, "failure while notifying response", e);
5884 }
5885 }
5886 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005887
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005888 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07005889 private final Object mLock = new Object();
5890
5891 @GuardedBy("mLock")
5892 private AccountManagerBackupHelper mBackupHelper;
5893
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005894 @Override
5895 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
5896 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
5897 if (account == null) {
5898 Slog.w(TAG, "account cannot be null");
5899 return;
5900 }
5901 if (packageName == null) {
5902 Slog.w(TAG, "packageName cannot be null");
5903 return;
5904 }
5905 if (userId < UserHandle.USER_SYSTEM) {
5906 Slog.w(TAG, "user id must be concrete");
5907 return;
5908 }
5909 if (callback == null) {
5910 Slog.w(TAG, "callback cannot be null");
5911 return;
5912 }
5913
Svet Ganovf6d424f12016-09-20 20:18:53 -07005914 if (AccountManagerService.this.hasAccountAccess(account, packageName,
5915 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005916 Bundle result = new Bundle();
5917 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
5918 callback.sendResult(result);
5919 return;
5920 }
5921
5922 final int uid;
5923 try {
5924 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
5925 } catch (NameNotFoundException e) {
5926 Slog.e(TAG, "Unknown package " + packageName);
5927 return;
5928 }
5929
5930 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07005931 final UserAccounts userAccounts;
5932 synchronized (mUsers) {
5933 userAccounts = mUsers.get(userId);
5934 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04005935 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07005936 doNotification(userAccounts, account, null, intent, packageName, userId);
5937 }
5938
5939 @Override
5940 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
5941 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5942 mAppPermissionChangeListeners.add(listener);
5943 }
5944
5945 @Override
5946 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
5947 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005948 }
Svet Ganov5d09c992016-09-07 09:57:41 -07005949
5950 @Override
5951 public byte[] backupAccountAccessPermissions(int userId) {
5952 synchronized (mLock) {
5953 if (mBackupHelper == null) {
5954 mBackupHelper = new AccountManagerBackupHelper(
5955 AccountManagerService.this, this);
5956 }
5957 return mBackupHelper.backupAccountAccessPermissions(userId);
5958 }
5959 }
5960
5961 @Override
5962 public void restoreAccountAccessPermissions(byte[] data, int userId) {
5963 synchronized (mLock) {
5964 if (mBackupHelper == null) {
5965 mBackupHelper = new AccountManagerBackupHelper(
5966 AccountManagerService.this, this);
5967 }
5968 mBackupHelper.restoreAccountAccessPermissions(data, userId);
5969 }
5970 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005971 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07005972
5973 @VisibleForTesting
5974 static class Injector {
5975 private final Context mContext;
5976
5977 public Injector(Context context) {
5978 mContext = context;
5979 }
5980
5981 Looper getMessageHandlerLooper() {
5982 ServiceThread serviceThread = new ServiceThread(TAG,
5983 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
5984 serviceThread.start();
5985 return serviceThread.getLooper();
5986 }
5987
5988 Context getContext() {
5989 return mContext;
5990 }
5991
5992 void addLocalService(AccountManagerInternal service) {
5993 LocalServices.addService(AccountManagerInternal.class, service);
5994 }
5995
5996 String getDeDatabaseName(int userId) {
5997 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
5998 AccountsDb.DE_DATABASE_NAME);
5999 return databaseFile.getPath();
6000 }
6001
6002 String getCeDatabaseName(int userId) {
6003 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
6004 AccountsDb.CE_DATABASE_NAME);
6005 return databaseFile.getPath();
6006 }
6007
6008 String getPreNDatabaseName(int userId) {
6009 File systemDir = Environment.getDataSystemDirectory();
6010 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
6011 PRE_N_DATABASE_NAME);
6012 if (userId == 0) {
6013 // Migrate old file, if it exists, to the new location.
6014 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006015 // accidentally created in the old location,
6016 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07006017 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
6018 if (oldFile.exists() && !databaseFile.exists()) {
6019 // Check for use directory; create if it doesn't exist, else renameTo will fail
6020 File userDir = Environment.getUserSystemDirectory(userId);
6021 if (!userDir.exists()) {
6022 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006023 throw new IllegalStateException(
6024 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006025 }
6026 }
6027 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006028 throw new IllegalStateException(
6029 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006030 }
6031 }
6032 }
6033 return databaseFile.getPath();
6034 }
6035
6036 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
6037 return new AccountAuthenticatorCache(mContext);
6038 }
6039
6040 INotificationManager getNotificationManager() {
6041 return NotificationManager.getService();
6042 }
6043 }
Chris Wren717a8812017-03-31 15:34:39 -04006044
6045 private class NotificationId {
6046 final String mTag;
6047 private final int mId;
6048
6049 NotificationId(String tag, int type) {
6050 mTag = tag;
6051 mId = type;
6052 }
6053 }
Fred Quintana60307342009-03-24 22:48:12 -07006054}