blob: b5cab1f8d62bdda7e27984b58aa03d7b239a0417 [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;
sunjianf29d5492017-05-11 15:42:31 -070026import android.accounts.AccountManagerResponse;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070028import android.accounts.CantAddAccountActivity;
sunjianf29d5492017-05-11 15:42:31 -070029import android.accounts.ChooseAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080030import android.accounts.GrantCredentialsPermissionActivity;
31import android.accounts.IAccountAuthenticator;
32import android.accounts.IAccountAuthenticatorResponse;
33import android.accounts.IAccountManager;
34import android.accounts.IAccountManagerResponse;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070035import android.annotation.IntRange;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070036import android.annotation.NonNull;
Svet Ganovf6d424f12016-09-20 20:18:53 -070037import android.annotation.Nullable;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080038import android.app.ActivityManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070039import android.app.ActivityThread;
Svetoslavf3f02ac2015-09-08 14:36:35 -070040import android.app.AppOpsManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070041import android.app.INotificationManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070042import android.app.Notification;
43import android.app.NotificationManager;
44import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000045import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010046import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000047import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070048import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070049import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070050import android.content.Context;
51import android.content.Intent;
52import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070053import android.content.IntentSender;
Fred Quintanab839afc2009-10-14 15:57:28 -070054import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080055import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.content.pm.ApplicationInfo;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070057import android.content.pm.IPackageManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070058import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070060import android.content.pm.PackageManager.NameNotFoundException;
Dan Cashman303c4bb2018-04-10 07:41:16 -070061import android.content.pm.PackageManagerInternal;
62import android.content.pm.PackageParser;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070063import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070064import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070065import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070066import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070067import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070068import android.database.Cursor;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070069import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070070import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070071import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080072import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070073import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070074import android.os.IBinder;
75import android.os.Looper;
76import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070077import android.os.Parcel;
sunjianf29d5492017-05-11 15:42:31 -070078import android.os.Parcelable;
Amith Yamasani27db4682013-03-30 17:07:47 -070079import android.os.Process;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070080import android.os.RemoteCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import android.os.RemoteException;
Hongming Jin8e2bfc12018-05-30 11:01:06 -070082import android.os.ResultReceiver;
83import android.os.ShellCallback;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080084import android.os.StrictMode;
Fred Quintanaa698f422009-04-08 19:14:54 -070085import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070086import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070087import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070088import android.text.TextUtils;
89import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070090import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070091import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080092import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070093import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070094
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070095import com.android.internal.R;
Svet Ganov5d09c992016-09-07 09:57:41 -070096import com.android.internal.annotations.GuardedBy;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070097import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070098import com.android.internal.content.PackageMonitor;
Chris Wren282cfef2017-03-27 15:01:44 -040099import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500100import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800101import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600102import com.android.internal.util.DumpUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800103import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700104import com.android.internal.util.Preconditions;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000105import com.android.server.LocalServices;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700106import com.android.server.ServiceThread;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600107import com.android.server.SystemService;
108
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700109import com.google.android.collect.Lists;
110import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700111
Oscar Montemayora8529f62009-11-18 10:14:20 -0800112import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700113import java.io.FileDescriptor;
114import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800115import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700116import java.security.MessageDigest;
117import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700118import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700119import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800120import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700121import java.util.Collection;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700122import java.util.Collections;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700123import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700124import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700125import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800126import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700127import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800128import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800129import java.util.Map.Entry;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700130import java.util.Objects;
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700131import java.util.Set;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700132import java.util.UUID;
Svet Ganovf6d424f12016-09-20 20:18:53 -0700133import java.util.concurrent.CopyOnWriteArrayList;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700134import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700135
Fred Quintana60307342009-03-24 22:48:12 -0700136/**
137 * A system service that provides account, password, and authtoken management for all
138 * accounts on the device. Some of these calls are implemented with the help of the corresponding
139 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
140 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700141 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700142 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700143 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700144public class AccountManagerService
145 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800146 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700147 private static final String TAG = "AccountManagerService";
148
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600149 public static class Lifecycle extends SystemService {
150 private AccountManagerService mService;
151
152 public Lifecycle(Context context) {
153 super(context);
154 }
155
156 @Override
157 public void onStart() {
Fyodor Kupolovda993802016-09-21 14:47:10 -0700158 mService = new AccountManagerService(new Injector(getContext()));
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600159 publishBinderService(Context.ACCOUNT_SERVICE, mService);
160 }
161
162 @Override
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600163 public void onUnlockUser(int userHandle) {
164 mService.onUnlockUser(userHandle);
165 }
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700166
167 @Override
Fyodor Kupolovce25ed22017-05-04 11:44:31 -0700168 public void onStopUser(int userHandle) {
Fyodor Kupolov945c97e2017-06-21 17:45:19 -0700169 Slog.i(TAG, "onStopUser " + userHandle);
170 mService.purgeUserData(userHandle);
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700171 }
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600172 }
173
Svet Ganov5d09c992016-09-07 09:57:41 -0700174 final Context mContext;
Fred Quintana60307342009-03-24 22:48:12 -0700175
Fred Quintana56285a62010-12-02 14:20:51 -0800176 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700177 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700178 private UserManager mUserManager;
Fyodor Kupolovda993802016-09-21 14:47:10 -0700179 private final Injector mInjector;
Fred Quintana56285a62010-12-02 14:20:51 -0800180
Svet Ganov5d09c992016-09-07 09:57:41 -0700181 final MessageHandler mHandler;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700182
Fred Quintana60307342009-03-24 22:48:12 -0700183 // Messages that can be sent on mHandler
184 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700185 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700186
Fred Quintana56285a62010-12-02 14:20:51 -0800187 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700188 private static final String PRE_N_DATABASE_NAME = "accounts.db";
Fred Quintana7be59642009-08-24 18:29:25 -0700189 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800190
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800191 private static final int SIGNATURE_CHECK_MISMATCH = 0;
192 private static final int SIGNATURE_CHECK_MATCH = 1;
193 private static final int SIGNATURE_CHECK_UID_MATCH = 2;
194
Carlos Valdivia91979be2015-05-22 14:11:35 -0700195 static {
196 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Christopher Tatebded68f2017-02-21 11:41:55 -0800197 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
198 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700199 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700200
201 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700202
Amith Yamasani04e0d262012-02-14 11:50:53 -0800203 static class UserAccounts {
204 private final int userId;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700205 final AccountsDb accountsDb;
Chris Wren717a8812017-03-31 15:34:39 -0400206 private final HashMap<Pair<Pair<Account, String>, Integer>, NotificationId>
207 credentialsPermissionNotificationIds = new HashMap<>();
208 private final HashMap<Account, NotificationId> signinRequiredNotificationIds
209 = new HashMap<>();
Svet Ganov5d09c992016-09-07 09:57:41 -0700210 final Object cacheLock = new Object();
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700211 final Object dbLock = new Object(); // if needed, dbLock must be obtained before cacheLock
Amith Yamasani04e0d262012-02-14 11:50:53 -0800212 /** protected by the {@link #cacheLock} */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700213 final HashMap<String, Account[]> accountCache = new LinkedHashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800214 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700215 private final Map<Account, Map<String, String>> userDataCache = new HashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800216 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700217 private final Map<Account, Map<String, String>> authTokenCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700218 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700219 private final TokenCache accountTokenCaches = new TokenCache();
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700220 /** protected by the {@link #cacheLock} */
221 private final Map<Account, Map<String, Integer>> visibilityCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700222
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700223 /** protected by the {@link #mReceiversForType},
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700224 * type -> (packageName -> number of active receivers)
225 * type == null is used to get notifications about all account types
226 */
227 private final Map<String, Map<String, Integer>> mReceiversForType = new HashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800228
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700229 /**
230 * protected by the {@link #cacheLock}
231 *
232 * Caches the previous names associated with an account. Previous names
233 * should be cached because we expect that when an Account is renamed,
234 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
235 * want to know if the accounts they care about have been renamed.
236 *
237 * The previous names are wrapped in an {@link AtomicReference} so that
238 * we can distinguish between those accounts with no previous names and
239 * those whose previous names haven't been cached (yet).
240 */
241 private final HashMap<Account, AtomicReference<String>> previousNameCache =
242 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800243
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700244 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800245 this.userId = userId;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700246 synchronized (dbLock) {
247 synchronized (cacheLock) {
248 accountsDb = AccountsDb.create(context, userId, preNDbFile, deDbFile);
249 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800250 }
251 }
252 }
253
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700254 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600255 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -0700256 // Not thread-safe. Only use in synchronized context
257 private final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Svet Ganovf6d424f12016-09-20 20:18:53 -0700258 private CopyOnWriteArrayList<AccountManagerInternal.OnAppPermissionChangeListener>
259 mAppPermissionChangeListeners = new CopyOnWriteArrayList<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800260
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700261 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700262 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700263
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700264 /**
265 * This should only be called by system code. One should only call this after the service
266 * has started.
267 * @return a reference to the AccountManagerService instance
268 * @hide
269 */
270 public static AccountManagerService getSingleton() {
271 return sThis.get();
272 }
Fred Quintana60307342009-03-24 22:48:12 -0700273
Fyodor Kupolovda993802016-09-21 14:47:10 -0700274 public AccountManagerService(Injector injector) {
275 mInjector = injector;
276 mContext = injector.getContext();
277 mPackageManager = mContext.getPackageManager();
Svetoslavf3f02ac2015-09-08 14:36:35 -0700278 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fyodor Kupolovda993802016-09-21 14:47:10 -0700279 mHandler = new MessageHandler(injector.getMessageHandlerLooper());
280 mAuthenticatorCache = mInjector.getAccountAuthenticatorCache();
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800281 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700282
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700283 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800284
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800285 IntentFilter intentFilter = new IntentFilter();
286 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
287 intentFilter.addDataScheme("package");
288 mContext.registerReceiver(new BroadcastReceiver() {
289 @Override
290 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700291 // Don't delete accounts when updating a authenticator's
292 // package.
293 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700294 /* Purging data requires file io, don't block the main thread. This is probably
295 * less than ideal because we are introducing a race condition where old grants
296 * could be exercised until they are purged. But that race condition existed
297 * anyway with the broadcast receiver.
298 *
299 * Ideally, we would completely clear the cache, purge data from the database,
300 * and then rebuild the cache. All under the cache lock. But that change is too
301 * large at this point.
302 */
Dmitry Dementyev0b676422017-03-09 11:51:26 -0800303 final String removedPackageName = intent.getData().getSchemeSpecificPart();
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700304 Runnable purgingRunnable = new Runnable() {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700305 @Override
306 public void run() {
307 purgeOldGrantsAll();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800308 // Notify authenticator about removed app?
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800309 removeVisibilityValuesForPackage(removedPackageName);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700310 }
311 };
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700312 mHandler.post(purgingRunnable);
Carlos Valdivia23f58262014-09-05 10:52:41 -0700313 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800314 }
315 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800316
Fyodor Kupolovda993802016-09-21 14:47:10 -0700317 injector.addLocalService(new AccountManagerInternalImpl());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700318
Fyodor Kupolov945c97e2017-06-21 17:45:19 -0700319 IntentFilter userFilter = new IntentFilter();
320 userFilter.addAction(Intent.ACTION_USER_REMOVED);
321 mContext.registerReceiverAsUser(new BroadcastReceiver() {
322 @Override
323 public void onReceive(Context context, Intent intent) {
324 String action = intent.getAction();
325 if (Intent.ACTION_USER_REMOVED.equals(action)) {
326 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
327 if (userId < 1) return;
328 Slog.i(TAG, "User " + userId + " removed");
329 purgeUserData(userId);
330 }
331 }
332 }, UserHandle.ALL, userFilter, null, null);
333
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700334 // Need to cancel account request notifications if the update/install can access the account
335 new PackageMonitor() {
336 @Override
337 public void onPackageAdded(String packageName, int uid) {
338 // Called on a handler, and running as the system
339 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
340 }
341
342 @Override
343 public void onPackageUpdateFinished(String packageName, int uid) {
344 // Called on a handler, and running as the system
345 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
346 }
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700347 }.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700348
349 // Cancel account request notification if an app op was preventing the account access
350 mAppOpsManager.startWatchingMode(AppOpsManager.OP_GET_ACCOUNTS, null,
351 new AppOpsManager.OnOpChangedInternalListener() {
352 @Override
353 public void onOpChanged(int op, String packageName) {
354 try {
355 final int userId = ActivityManager.getCurrentUser();
356 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
357 final int mode = mAppOpsManager.checkOpNoThrow(
358 AppOpsManager.OP_GET_ACCOUNTS, uid, packageName);
359 if (mode == AppOpsManager.MODE_ALLOWED) {
360 final long identity = Binder.clearCallingIdentity();
361 try {
362 cancelAccountAccessRequestNotificationIfNeeded(packageName, uid, true);
363 } finally {
364 Binder.restoreCallingIdentity(identity);
365 }
366 }
367 } catch (NameNotFoundException e) {
368 /* ignore */
369 }
370 }
371 });
372
373 // Cancel account request notification if a permission was preventing the account access
374 mPackageManager.addOnPermissionsChangeListener(
375 (int uid) -> {
376 Account[] accounts = null;
377 String[] packageNames = mPackageManager.getPackagesForUid(uid);
378 if (packageNames != null) {
379 final int userId = UserHandle.getUserId(uid);
380 final long identity = Binder.clearCallingIdentity();
381 try {
382 for (String packageName : packageNames) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800383 // if app asked for permission we need to cancel notification even
384 // for O+ applications.
385 if (mPackageManager.checkPermission(
386 Manifest.permission.GET_ACCOUNTS,
387 packageName) != PackageManager.PERMISSION_GRANTED) {
388 continue;
389 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700390
391 if (accounts == null) {
392 accounts = getAccountsAsUser(null, userId, "android");
393 if (ArrayUtils.isEmpty(accounts)) {
394 return;
395 }
396 }
397
398 for (Account account : accounts) {
399 cancelAccountAccessRequestNotificationIfNeeded(
400 account, uid, packageName, true);
401 }
402 }
403 } finally {
404 Binder.restoreCallingIdentity(identity);
405 }
406 }
407 });
408 }
409
Hongming Jin8e2bfc12018-05-30 11:01:06 -0700410
411 boolean getBindInstantServiceAllowed(int userId) {
412 return mAuthenticatorCache.getBindInstantServiceAllowed(userId);
413 }
414
415 void setBindInstantServiceAllowed(int userId, boolean allowed) {
416 mAuthenticatorCache.setBindInstantServiceAllowed(userId, allowed);
417 }
418
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700419 private void cancelAccountAccessRequestNotificationIfNeeded(int uid,
420 boolean checkAccess) {
421 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
422 for (Account account : accounts) {
423 cancelAccountAccessRequestNotificationIfNeeded(account, uid, checkAccess);
424 }
425 }
426
427 private void cancelAccountAccessRequestNotificationIfNeeded(String packageName, int uid,
428 boolean checkAccess) {
429 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
430 for (Account account : accounts) {
431 cancelAccountAccessRequestNotificationIfNeeded(account, uid, packageName, checkAccess);
432 }
433 }
434
435 private void cancelAccountAccessRequestNotificationIfNeeded(Account account, int uid,
436 boolean checkAccess) {
437 String[] packageNames = mPackageManager.getPackagesForUid(uid);
438 if (packageNames != null) {
439 for (String packageName : packageNames) {
440 cancelAccountAccessRequestNotificationIfNeeded(account, uid,
441 packageName, checkAccess);
442 }
443 }
444 }
445
446 private void cancelAccountAccessRequestNotificationIfNeeded(Account account,
447 int uid, String packageName, boolean checkAccess) {
448 if (!checkAccess || hasAccountAccess(account, packageName,
449 UserHandle.getUserHandleForUid(uid))) {
450 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -0700451 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700452 UserHandle.getUserHandleForUid(uid));
453 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800454 }
455
Dianne Hackborn164371f2013-10-01 19:10:13 -0700456 @Override
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800457 public boolean addAccountExplicitlyWithVisibility(Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800458 Bundle extras, Map packageToVisibility) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800459 Bundle.setDefusable(extras, true);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700460 int callingUid = Binder.getCallingUid();
461 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800462 if (Log.isLoggable(TAG, Log.VERBOSE)) {
463 Log.v(TAG, "addAccountExplicitly: " + account + ", caller's uid " + callingUid
464 + ", pid " + Binder.getCallingPid());
465 }
466 Preconditions.checkNotNull(account, "account cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800467 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
468 String msg = String.format("uid %s cannot explicitly add accounts of type: %s",
469 callingUid, account.type);
470 throw new SecurityException(msg);
471 }
472 /*
473 * Child users are not allowed to add accounts. Only the accounts that are shared by the
474 * parent profile can be added to child profile.
475 *
476 * TODO: Only allow accounts that were shared to be added by a limited user.
477 */
478 // fails if the account already exists
479 long identityToken = clearCallingIdentity();
480 try {
481 UserAccounts accounts = getUserAccounts(userId);
482 return addAccountInternal(accounts, account, password, extras, callingUid,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800483 (Map<String, Integer>) packageToVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800484 } finally {
485 restoreCallingIdentity(identityToken);
486 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700487 }
488
489 @Override
Dmitry Dementyev52745472016-12-02 10:27:45 -0800490 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
491 String accountType) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800492 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700493 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800494 boolean isSystemUid = UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700495 List<String> managedTypes = getTypesForCaller(callingUid, userId, isSystemUid);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800496
497 if ((accountType != null && !managedTypes.contains(accountType))
498 || (accountType == null && !isSystemUid)) {
499 throw new SecurityException(
500 "getAccountsAndVisibilityForPackage() called from unauthorized uid "
501 + callingUid + " with packageName=" + packageName);
502 }
503 if (accountType != null) {
504 managedTypes = new ArrayList<String>();
505 managedTypes.add(accountType);
506 }
507
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800508 long identityToken = clearCallingIdentity();
509 try {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700510 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800511 return getAccountsAndVisibilityForPackage(packageName, managedTypes, callingUid,
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700512 accounts);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800513 } finally {
514 restoreCallingIdentity(identityToken);
515 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800516 }
517
518 /*
519 * accountTypes may not be null
520 */
521 private Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
522 List<String> accountTypes, Integer callingUid, UserAccounts accounts) {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700523 if (!packageExistsForUser(packageName, accounts.userId)) {
524 Log.d(TAG, "Package not found " + packageName);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800525 return new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800526 }
527
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800528 Map<Account, Integer> result = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800529 for (String accountType : accountTypes) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700530 synchronized (accounts.dbLock) {
531 synchronized (accounts.cacheLock) {
532 final Account[] accountsOfType = accounts.accountCache.get(accountType);
533 if (accountsOfType != null) {
534 for (Account account : accountsOfType) {
535 result.put(account,
536 resolveAccountVisibility(account, packageName, accounts));
537 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800538 }
539 }
540 }
541 }
542 return filterSharedAccounts(accounts, result, callingUid, packageName);
Dmitry Dementyev52745472016-12-02 10:27:45 -0800543 }
544
545 @Override
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800546 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700547 Preconditions.checkNotNull(account, "account cannot be null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700548 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700549 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800550 if (!isAccountManagedByCaller(account.type, callingUid, userId)
551 && !isSystemUid(callingUid)) {
552 String msg =
553 String.format("uid %s cannot get secrets for account %s", callingUid, account);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700554 throw new SecurityException(msg);
555 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700556
557 long identityToken = clearCallingIdentity();
558 try {
559 UserAccounts accounts = getUserAccounts(userId);
560 synchronized (accounts.dbLock) {
561 synchronized (accounts.cacheLock) {
562 return getPackagesAndVisibilityForAccountLocked(account, accounts);
563 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700564 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700565 } finally {
566 restoreCallingIdentity(identityToken);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700567 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700568
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800569 }
570
571 /**
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700572 * Returns Map with all package names and visibility values for given account.
573 * The method and returned map must be guarded by accounts.cacheLock
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800574 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800575 * @param account Account to get visibility values.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800576 * @param accounts UserAccount that currently hosts the account and application
577 *
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700578 * @return Map with cache for package names to visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800579 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700580 private @NonNull Map<String, Integer> getPackagesAndVisibilityForAccountLocked(Account account,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800581 UserAccounts accounts) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700582 Map<String, Integer> accountVisibility = accounts.visibilityCache.get(account);
583 if (accountVisibility == null) {
584 Log.d(TAG, "Visibility was not initialized");
585 accountVisibility = new HashMap<>();
586 accounts.visibilityCache.put(account, accountVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800587 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700588 return accountVisibility;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700589 }
590
591 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700592 public int getAccountVisibility(Account account, String packageName) {
593 Preconditions.checkNotNull(account, "account cannot be null");
594 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800595 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700596 int userId = UserHandle.getCallingUserId();
597 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800598 && !isSystemUid(callingUid)) {
599 String msg = String.format(
600 "uid %s cannot get secrets for accounts of type: %s",
601 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700602 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800603 throw new SecurityException(msg);
604 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700605 long identityToken = clearCallingIdentity();
606 try {
607 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyevcbe1bd12017-04-25 17:02:47 -0700608 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)) {
609 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
610 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
611 return visibility;
612 } else {
613 return AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
614 }
615 }
616 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName)) {
617 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
618 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
619 return visibility;
620 } else {
621 return AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
622 }
623 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700624 return resolveAccountVisibility(account, packageName, accounts);
625 } finally {
626 restoreCallingIdentity(identityToken);
627 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800628 }
629
630 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800631 * Method returns visibility for given account and package name.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800632 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800633 * @param account The account to check visibility.
634 * @param packageName Package name to check visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800635 * @param accounts UserAccount that currently hosts the account and application
636 *
637 * @return Visibility value, AccountManager.VISIBILITY_UNDEFINED if no value was stored.
638 *
639 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700640 private int getAccountVisibilityFromCache(Account account, String packageName,
641 UserAccounts accounts) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700642 synchronized (accounts.cacheLock) {
643 Map<String, Integer> accountVisibility =
644 getPackagesAndVisibilityForAccountLocked(account, accounts);
645 Integer visibility = accountVisibility.get(packageName);
646 return visibility != null ? visibility : AccountManager.VISIBILITY_UNDEFINED;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800647 }
648 }
649
650 /**
651 * Method which handles default values for Account visibility.
652 *
653 * @param account The account to check visibility.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800654 * @param packageName Package name to check visibility
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800655 * @param accounts UserAccount that currently hosts the account and application
656 *
657 * @return Visibility value, the method never returns AccountManager.VISIBILITY_UNDEFINED
658 *
659 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800660 private Integer resolveAccountVisibility(Account account, @NonNull String packageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800661 UserAccounts accounts) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800662 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800663 int uid = -1;
664 try {
665 long identityToken = clearCallingIdentity();
666 try {
667 uid = mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
668 } finally {
669 restoreCallingIdentity(identityToken);
670 }
671 } catch (NameNotFoundException e) {
672 Log.d(TAG, "Package not found " + e.getMessage());
673 return AccountManager.VISIBILITY_NOT_VISIBLE;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800674 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800675
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800676 // System visibility can not be restricted.
677 if (UserHandle.isSameApp(uid, Process.SYSTEM_UID)) {
678 return AccountManager.VISIBILITY_VISIBLE;
679 }
680
681 int signatureCheckResult =
682 checkPackageSignature(account.type, uid, accounts.userId);
683
684 // Authenticator can not restrict visibility to itself.
685 if (signatureCheckResult == SIGNATURE_CHECK_UID_MATCH) {
686 return AccountManager.VISIBILITY_VISIBLE; // Authenticator can always see the account
687 }
688
689 // Return stored value if it was set.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700690 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800691
692 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
693 return visibility;
694 }
695
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -0700696 boolean isPrivileged = isPermittedForPackage(packageName, accounts.userId,
Dmitry Dementyevf794c8d2017-02-03 18:17:59 -0800697 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
698
699 // Device/Profile owner gets visibility by default.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800700 if (isProfileOwner(uid)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800701 return AccountManager.VISIBILITY_VISIBLE;
702 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800703
704 boolean preO = isPreOApplication(packageName);
705 if ((signatureCheckResult != SIGNATURE_CHECK_MISMATCH)
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -0700706 || (preO && checkGetAccountsPermission(packageName, accounts.userId))
707 || (checkReadContactsPermission(packageName, accounts.userId)
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700708 && accountTypeManagesContacts(account.type, accounts.userId))
709 || isPrivileged) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800710 // Use legacy for preO apps with GET_ACCOUNTS permission or pre/postO with signature
711 // match.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700712 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800713 AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800714 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
715 visibility = AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
716 }
717 } else {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700718 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800719 AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800720 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
721 visibility = AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
722 }
723 }
724 return visibility;
725 }
726
727 /**
728 * Checks targetSdk for a package;
729 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800730 * @param packageName Package name
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800731 *
732 * @return True if package's target SDK is below {@link android.os.Build.VERSION_CODES#O}, or
733 * undefined
734 */
735 private boolean isPreOApplication(String packageName) {
736 try {
737 long identityToken = clearCallingIdentity();
738 ApplicationInfo applicationInfo;
739 try {
740 applicationInfo = mPackageManager.getApplicationInfo(packageName, 0);
741 } finally {
742 restoreCallingIdentity(identityToken);
743 }
744
745 if (applicationInfo != null) {
746 int version = applicationInfo.targetSdkVersion;
747 return version < android.os.Build.VERSION_CODES.O;
748 }
749 return true;
750 } catch (NameNotFoundException e) {
751 Log.d(TAG, "Package not found " + e.getMessage());
752 return true;
753 }
Dmitry Dementyev58fa83622016-12-20 18:08:51 -0800754 }
755
756 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700757 public boolean setAccountVisibility(Account account, String packageName, int newVisibility) {
758 Preconditions.checkNotNull(account, "account cannot be null");
759 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800760 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700761 int userId = UserHandle.getCallingUserId();
762 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800763 && !isSystemUid(callingUid)) {
764 String msg = String.format(
765 "uid %s cannot get secrets for accounts of type: %s",
766 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700767 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800768 throw new SecurityException(msg);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700769 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700770 long identityToken = clearCallingIdentity();
771 try {
772 UserAccounts accounts = getUserAccounts(userId);
773 return setAccountVisibility(account, packageName, newVisibility, true /* notify */,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700774 accounts);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700775 } finally {
776 restoreCallingIdentity(identityToken);
777 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700778 }
779
sunjian066aa5e2017-06-05 12:16:59 -0700780 private boolean isVisible(int visibility) {
781 return visibility == AccountManager.VISIBILITY_VISIBLE ||
782 visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
783 }
784
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700785 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800786 * Updates visibility for given account name and package.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700787 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800788 * @param account Account to update visibility.
789 * @param packageName Package name for which visibility is updated.
790 * @param newVisibility New visibility calue
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800791 * @param notify if the flag is set applications will get notification about visibility change
792 * @param accounts UserAccount that currently hosts the account and application
793 *
794 * @return True if account visibility was changed.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700795 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800796 private boolean setAccountVisibility(Account account, String packageName, int newVisibility,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800797 boolean notify, UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700798 synchronized (accounts.dbLock) {
799 synchronized (accounts.cacheLock) {
800 Map<String, Integer> packagesToVisibility;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700801 List<String> accountRemovedReceivers;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700802 if (notify) {
803 if (isSpecialPackageKey(packageName)) {
804 packagesToVisibility =
805 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700806 accountRemovedReceivers = getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700807 } else {
808 if (!packageExistsForUser(packageName, accounts.userId)) {
809 return false; // package is not installed.
810 }
811 packagesToVisibility = new HashMap<>();
812 packagesToVisibility.put(packageName,
813 resolveAccountVisibility(account, packageName, accounts));
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700814 accountRemovedReceivers = new ArrayList<>();
815 if (shouldNotifyPackageOnAccountRemoval(account, packageName, accounts)) {
816 accountRemovedReceivers.add(packageName);
817 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700818 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800819 } else {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700820 // Notifications will not be send - only used during add account.
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700821 if (!isSpecialPackageKey(packageName) &&
822 !packageExistsForUser(packageName, accounts.userId)) {
823 // package is not installed and not meta value.
824 return false;
Nicolas Prevotf7d8df12016-09-16 17:45:34 +0100825 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700826 packagesToVisibility = Collections.emptyMap();
827 accountRemovedReceivers = Collections.emptyList();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800828 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700829
830 if (!updateAccountVisibilityLocked(account, packageName, newVisibility, accounts)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800831 return false;
832 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800833
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700834 if (notify) {
835 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
836 .entrySet()) {
sunjian066aa5e2017-06-05 12:16:59 -0700837 int oldVisibility = packageToVisibility.getValue();
838 int currentVisibility =
839 resolveAccountVisibility(account, packageName, accounts);
840 if (isVisible(oldVisibility) != isVisible(currentVisibility)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700841 notifyPackage(packageToVisibility.getKey(), accounts);
842 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700843 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700844 for (String packageNameToNotify : accountRemovedReceivers) {
845 sendAccountRemovedBroadcast(account, packageNameToNotify, accounts.userId);
846 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700847 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700848 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700849 return true;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800850 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700851 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700852 }
853
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700854 // Update account visibility in cache and database.
855 private boolean updateAccountVisibilityLocked(Account account, String packageName,
856 int newVisibility, UserAccounts accounts) {
857 final long accountId = accounts.accountsDb.findDeAccountId(account);
858 if (accountId < 0) {
859 return false;
860 }
861
862 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
863 try {
864 if (!accounts.accountsDb.setAccountVisibility(accountId, packageName,
865 newVisibility)) {
866 return false;
867 }
868 } finally {
869 StrictMode.setThreadPolicy(oldPolicy);
870 }
871 Map<String, Integer> accountVisibility =
872 getPackagesAndVisibilityForAccountLocked(account, accounts);
873 accountVisibility.put(packageName, newVisibility);
874 return true;
875 }
876
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700877 @Override
878 public void registerAccountListener(String[] accountTypes, String opPackageName) {
879 int callingUid = Binder.getCallingUid();
880 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700881
882 int userId = UserHandle.getCallingUserId();
883 long identityToken = clearCallingIdentity();
884 try {
885 UserAccounts accounts = getUserAccounts(userId);
886 registerAccountListener(accountTypes, opPackageName, accounts);
887 } finally {
888 restoreCallingIdentity(identityToken);
889 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800890 }
891
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700892 private void registerAccountListener(String[] accountTypes, String opPackageName,
893 UserAccounts accounts) {
894 synchronized (accounts.mReceiversForType) {
895 if (accountTypes == null) {
896 // null for any type
897 accountTypes = new String[] {null};
898 }
899 for (String type : accountTypes) {
900 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
901 if (receivers == null) {
902 receivers = new HashMap<>();
903 accounts.mReceiversForType.put(type, receivers);
904 }
905 Integer cnt = receivers.get(opPackageName);
906 receivers.put(opPackageName, cnt != null ? cnt + 1 : 1);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800907 }
908 }
909 }
910
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700911 @Override
912 public void unregisterAccountListener(String[] accountTypes, String opPackageName) {
913 int callingUid = Binder.getCallingUid();
914 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700915 int userId = UserHandle.getCallingUserId();
916 long identityToken = clearCallingIdentity();
917 try {
918 UserAccounts accounts = getUserAccounts(userId);
919 unregisterAccountListener(accountTypes, opPackageName, accounts);
920 } finally {
921 restoreCallingIdentity(identityToken);
922 }
923 }
924
925 private void unregisterAccountListener(String[] accountTypes, String opPackageName,
926 UserAccounts accounts) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700927 synchronized (accounts.mReceiversForType) {
928 if (accountTypes == null) {
929 // null for any type
930 accountTypes = new String[] {null};
931 }
932 for (String type : accountTypes) {
933 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
934 if (receivers == null || receivers.get(opPackageName) == null) {
935 throw new IllegalArgumentException("attempt to unregister wrong receiver");
936 }
937 Integer cnt = receivers.get(opPackageName);
938 if (cnt == 1) {
939 receivers.remove(opPackageName);
940 } else {
941 receivers.put(opPackageName, cnt - 1);
942 }
943 }
944 }
945 }
946
947 // Send notification to all packages which can potentially see the account
948 private void sendNotificationAccountUpdated(Account account, UserAccounts accounts) {
949 Map<String, Integer> packagesToVisibility = getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700950
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700951 for (Entry<String, Integer> packageToVisibility : packagesToVisibility.entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700952 if ((packageToVisibility.getValue() != AccountManager.VISIBILITY_NOT_VISIBLE)
953 && (packageToVisibility.getValue()
954 != AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE)) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700955 notifyPackage(packageToVisibility.getKey(), accounts);
956 }
957 }
958 }
959
960 /**
961 * Sends a direct intent to a package, notifying it of account visibility change.
962 *
963 * @param packageName to send Account to
964 * @param accounts UserAccount that currently hosts the account
965 */
966 private void notifyPackage(String packageName, UserAccounts accounts) {
967 Intent intent = new Intent(AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED);
968 intent.setPackage(packageName);
969 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
970 mContext.sendBroadcastAsUser(intent, new UserHandle(accounts.userId));
971 }
972
973 // Returns a map from package name to visibility, for packages subscribed
974 // to notifications about any account type, or type of provided account
975 // account type or all types.
976 private Map<String, Integer> getRequestingPackages(Account account, UserAccounts accounts) {
977 Set<String> packages = new HashSet<>();
978 synchronized (accounts.mReceiversForType) {
979 for (String type : new String[] {account.type, null}) {
980 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
981 if (receivers != null) {
982 packages.addAll(receivers.keySet());
983 }
984 }
985 }
986 Map<String, Integer> result = new HashMap<>();
987 for (String packageName : packages) {
988 result.put(packageName, resolveAccountVisibility(account, packageName, accounts));
989 }
990 return result;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800991 }
992
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700993 // Returns a list of packages listening to ACTION_ACCOUNT_REMOVED able to see the account.
994 private List<String> getAccountRemovedReceivers(Account account, UserAccounts accounts) {
995 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
996 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
997 List<ResolveInfo> receivers =
998 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
999 List<String> result = new ArrayList<>();
1000 if (receivers == null) {
1001 return result;
1002 }
1003 for (ResolveInfo resolveInfo: receivers) {
1004 String packageName = resolveInfo.activityInfo.applicationInfo.packageName;
1005 int visibility = resolveAccountVisibility(account, packageName, accounts);
1006 if (visibility == AccountManager.VISIBILITY_VISIBLE
1007 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
1008 result.add(packageName);
1009 }
1010 }
1011 return result;
1012 }
1013
1014 // Returns true if given package is listening to ACTION_ACCOUNT_REMOVED and can see the account.
1015 private boolean shouldNotifyPackageOnAccountRemoval(Account account,
1016 String packageName, UserAccounts accounts) {
1017 int visibility = resolveAccountVisibility(account, packageName, accounts);
1018 if (visibility != AccountManager.VISIBILITY_VISIBLE
1019 && visibility != AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
1020 return false;
1021 }
1022
1023 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1024 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
1025 intent.setPackage(packageName);
1026 List<ResolveInfo> receivers =
1027 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
1028 return (receivers != null && receivers.size() > 0);
1029 }
1030
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001031 private boolean packageExistsForUser(String packageName, int userId) {
1032 try {
1033 long identityToken = clearCallingIdentity();
1034 try {
1035 mPackageManager.getPackageUidAsUser(packageName, userId);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -07001036 return true;
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001037 } finally {
1038 restoreCallingIdentity(identityToken);
1039 }
1040 } catch (NameNotFoundException e) {
1041 return false;
1042 }
1043 }
1044
1045 /**
1046 * Returns true if packageName is one of special values.
1047 */
1048 private boolean isSpecialPackageKey(String packageName) {
1049 return (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)
1050 || AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName));
1051 }
1052
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001053 private void sendAccountsChangedBroadcast(int userId) {
1054 Log.i(TAG, "the accounts changed, sending broadcast of "
1055 + ACCOUNTS_CHANGED_INTENT.getAction());
1056 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001057 }
1058
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001059 private void sendAccountRemovedBroadcast(Account account, String packageName, int userId) {
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001060 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1061 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001062 intent.setPackage(packageName);
1063 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
1064 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001065 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
1066 }
1067
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001068 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -07001069 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1070 throws RemoteException {
1071 try {
1072 return super.onTransact(code, data, reply, flags);
1073 } catch (RuntimeException e) {
1074 // The account manager only throws security exceptions, so let's
1075 // log all others.
1076 if (!(e instanceof SecurityException)) {
1077 Slog.wtf(TAG, "Account Manager Crash", e);
1078 }
1079 throw e;
1080 }
1081 }
1082
Amith Yamasani258848d2012-08-10 17:06:33 -07001083 private UserManager getUserManager() {
1084 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001085 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -07001086 }
1087 return mUserManager;
1088 }
1089
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001090 /**
1091 * Validate internal set of accounts against installed authenticators for
1092 * given user. Clears cached authenticators before validating.
1093 */
1094 public void validateAccounts(int userId) {
1095 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001096 // Invalidate user-specific cache to make sure we catch any
1097 // removed authenticators.
1098 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
1099 }
1100
1101 /**
1102 * Validate internal set of accounts against installed authenticators for
1103 * given user. Clear cached authenticators before validating when requested.
1104 */
1105 private void validateAccountsInternal(
1106 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001107 if (Log.isLoggable(TAG, Log.DEBUG)) {
1108 Log.d(TAG, "validateAccountsInternal " + accounts.userId
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001109 + " isCeDatabaseAttached=" + accounts.accountsDb.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001110 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001111 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001112
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001113 if (invalidateAuthenticatorCache) {
1114 mAuthenticatorCache.invalidateCache(accounts.userId);
1115 }
1116
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001117 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
1118 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001119 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001120
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001121 synchronized (accounts.dbLock) {
1122 synchronized (accounts.cacheLock) {
1123 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001124
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001125 // Get a map of stored authenticator types to UID
1126 final AccountsDb accountsDb = accounts.accountsDb;
1127 Map<String, Integer> metaAuthUid = accountsDb.findMetaAuthUid();
1128 // Create a list of authenticator type whose previous uid no longer exists
1129 HashSet<String> obsoleteAuthType = Sets.newHashSet();
1130 SparseBooleanArray knownUids = null;
1131 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
1132 String type = authToUidEntry.getKey();
1133 int uid = authToUidEntry.getValue();
1134 Integer knownUid = knownAuth.get(type);
1135 if (knownUid != null && uid == knownUid) {
1136 // Remove it from the knownAuth list if it's unchanged.
1137 knownAuth.remove(type);
1138 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001139 /*
1140 * The authenticator is presently not cached and should only be triggered
1141 * when we think an authenticator has been removed (or is being updated).
1142 * But we still want to check if any data with the associated uid is
1143 * around. This is an (imperfect) signal that the package may be updating.
1144 *
1145 * A side effect of this is that an authenticator sharing a uid with
1146 * multiple apps won't get its credentials wiped as long as some app with
1147 * that uid is still on the device. But I suspect that this is a rare case.
1148 * And it isn't clear to me how an attacker could really exploit that
1149 * feature.
1150 *
1151 * The upshot is that we don't have to worry about accounts getting
1152 * uninstalled while the authenticator's package is being updated.
1153 *
1154 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001155 if (knownUids == null) {
1156 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
1157 }
1158 if (!knownUids.get(uid)) {
1159 // The authenticator is not presently available to the cache. And the
1160 // package no longer has a data directory (so we surmise it isn't
1161 // updating). So purge its data from the account databases.
1162 obsoleteAuthType.add(type);
1163 // And delete it from the TABLE_META
1164 accountsDb.deleteMetaByAuthTypeAndUid(type, uid);
1165 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001166 }
1167 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001168
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001169 // Add the newly registered authenticator to TABLE_META. If old authenticators have
1170 // been re-enabled (after being updated for example), then we just overwrite the old
1171 // values.
1172 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1173 accountsDb.insertOrReplaceMetaAuthTypeAndUid(entry.getKey(), entry.getValue());
1174 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001175
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001176 final Map<Long, Account> accountsMap = accountsDb.findAllDeAccounts();
1177 try {
1178 accounts.accountCache.clear();
1179 final HashMap<String, ArrayList<String>> accountNamesByType
1180 = new LinkedHashMap<>();
1181 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1182 final long accountId = accountEntry.getKey();
1183 final Account account = accountEntry.getValue();
1184 if (obsoleteAuthType.contains(account.type)) {
Hui Yu139c2482018-08-10 15:37:51 -07001185 Slog.w(TAG, "deleting account " + account.toSafeString()
1186 + " because type " + account.type
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001187 + "'s registered authenticator no longer exist.");
1188 Map<String, Integer> packagesToVisibility =
1189 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001190 List<String> accountRemovedReceivers =
1191 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001192 accountsDb.beginTransaction();
1193 try {
1194 accountsDb.deleteDeAccount(accountId);
1195 // Also delete from CE table if user is unlocked; if user is
1196 // currently locked the account will be removed later by
1197 // syncDeCeAccountsLocked
1198 if (userUnlocked) {
1199 accountsDb.deleteCeAccount(accountId);
1200 }
1201 accountsDb.setTransactionSuccessful();
1202 } finally {
1203 accountsDb.endTransaction();
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001204 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001205 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001206
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001207 logRecord(AccountsDb.DEBUG_ACTION_AUTHENTICATOR_REMOVE,
1208 AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001209
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001210 accounts.userDataCache.remove(account);
1211 accounts.authTokenCache.remove(account);
1212 accounts.accountTokenCaches.remove(account);
1213 accounts.visibilityCache.remove(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001214
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001215 for (Entry<String, Integer> packageToVisibility :
1216 packagesToVisibility.entrySet()) {
sunjian066aa5e2017-06-05 12:16:59 -07001217 if (isVisible(packageToVisibility.getValue())) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001218 notifyPackage(packageToVisibility.getKey(), accounts);
1219 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001220 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001221 for (String packageName : accountRemovedReceivers) {
1222 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
1223 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001224 } else {
1225 ArrayList<String> accountNames = accountNamesByType.get(account.type);
1226 if (accountNames == null) {
1227 accountNames = new ArrayList<>();
1228 accountNamesByType.put(account.type, accountNames);
1229 }
1230 accountNames.add(account.name);
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001231 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001232 }
1233 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
1234 final String accountType = cur.getKey();
1235 final ArrayList<String> accountNames = cur.getValue();
1236 final Account[] accountsForType = new Account[accountNames.size()];
1237 for (int i = 0; i < accountsForType.length; i++) {
1238 accountsForType[i] = new Account(accountNames.get(i), accountType,
1239 UUID.randomUUID().toString());
Fred Quintana56285a62010-12-02 14:20:51 -08001240 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001241 accounts.accountCache.put(accountType, accountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08001242 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001243 accounts.visibilityCache.putAll(accountsDb.findAllVisibilityValues());
1244 } finally {
1245 if (accountDeleted) {
1246 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintana56285a62010-12-02 14:20:51 -08001247 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001248 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001249 }
1250 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001251 }
1252
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001253 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1254 // Get the UIDs of all apps that might have data on the device. We want
1255 // to preserve user data if the app might otherwise be storing data.
1256 List<PackageInfo> pkgsWithData =
1257 mPackageManager.getInstalledPackagesAsUser(
1258 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1259 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1260 for (PackageInfo pkgInfo : pkgsWithData) {
1261 if (pkgInfo.applicationInfo != null
1262 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1263 knownUids.put(pkgInfo.applicationInfo.uid, true);
1264 }
1265 }
1266 return knownUids;
1267 }
1268
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001269 static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001270 Context context,
1271 int userId) {
1272 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001273 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1274 }
1275
1276 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1277 IAccountAuthenticatorCache authCache,
1278 int userId) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08001279 HashMap<String, Integer> knownAuth = new LinkedHashMap<>();
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001280 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1281 .getAllServices(userId)) {
1282 knownAuth.put(service.type.type, service.uid);
1283 }
1284 return knownAuth;
1285 }
1286
Amith Yamasani04e0d262012-02-14 11:50:53 -08001287 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001288 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001289 }
1290
1291 protected UserAccounts getUserAccounts(int userId) {
1292 synchronized (mUsers) {
1293 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001294 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001295 if (accounts == null) {
Fyodor Kupolovda993802016-09-21 14:47:10 -07001296 File preNDbFile = new File(mInjector.getPreNDatabaseName(userId));
1297 File deDbFile = new File(mInjector.getDeDatabaseName(userId));
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001298 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001299 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001300 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001301 validateAccounts = true;
1302 }
1303 // open CE database if necessary
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001304 if (!accounts.accountsDb.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001305 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001306 synchronized (accounts.dbLock) {
1307 synchronized (accounts.cacheLock) {
1308 File ceDatabaseFile = new File(mInjector.getCeDatabaseName(userId));
1309 accounts.accountsDb.attachCeDatabase(ceDatabaseFile);
1310 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001311 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001312 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001313 }
1314 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001315 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001316 }
1317 return accounts;
1318 }
1319 }
1320
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001321 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1322 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001323 List<Account> accountsToRemove = accounts.accountsDb.findCeAccountsNotInDe();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001324 if (!accountsToRemove.isEmpty()) {
Hui Yu139c2482018-08-10 15:37:51 -07001325 Slog.i(TAG, accountsToRemove.size()
1326 + " accounts were previously deleted while user "
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001327 + accounts.userId + " was locked. Removing accounts from CE tables");
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001328 logRecord(accounts, AccountsDb.DEBUG_ACTION_SYNC_DE_CE_ACCOUNTS,
1329 AccountsDb.TABLE_ACCOUNTS);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001330
1331 for (Account account : accountsToRemove) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001332 removeAccountInternal(accounts, account, Process.SYSTEM_UID);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001333 }
1334 }
1335 }
1336
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001337 private void purgeOldGrantsAll() {
1338 synchronized (mUsers) {
1339 for (int i = 0; i < mUsers.size(); i++) {
1340 purgeOldGrants(mUsers.valueAt(i));
1341 }
1342 }
1343 }
1344
1345 private void purgeOldGrants(UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001346 synchronized (accounts.dbLock) {
1347 synchronized (accounts.cacheLock) {
1348 List<Integer> uids = accounts.accountsDb.findAllUidGrants();
1349 for (int uid : uids) {
1350 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1351 if (packageExists) {
1352 continue;
1353 }
1354 Log.d(TAG, "deleting grants for UID " + uid
1355 + " because its package is no longer installed");
1356 accounts.accountsDb.deleteGrantsByUid(uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001357 }
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001358 }
1359 }
1360 }
1361
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001362 private void removeVisibilityValuesForPackage(String packageName) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001363 if (isSpecialPackageKey(packageName)) {
1364 return;
1365 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001366 synchronized (mUsers) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001367 int numberOfUsers = mUsers.size();
1368 for (int i = 0; i < numberOfUsers; i++) {
1369 UserAccounts accounts = mUsers.valueAt(i);
1370 try {
1371 mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
1372 } catch (NameNotFoundException e) {
1373 // package does not exist - remove visibility values
1374 accounts.accountsDb.deleteAccountVisibilityForPackage(packageName);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001375 synchronized (accounts.dbLock) {
1376 synchronized (accounts.cacheLock) {
1377 for (Account account : accounts.visibilityCache.keySet()) {
1378 Map<String, Integer> accountVisibility =
1379 getPackagesAndVisibilityForAccountLocked(account, accounts);
1380 accountVisibility.remove(packageName);
1381 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001382 }
1383 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001384 }
1385 }
1386 }
1387 }
1388
Fyodor Kupolov945c97e2017-06-21 17:45:19 -07001389 private void purgeUserData(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001390 UserAccounts accounts;
1391 synchronized (mUsers) {
1392 accounts = mUsers.get(userId);
1393 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001394 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001395 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001396 if (accounts != null) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001397 synchronized (accounts.dbLock) {
1398 synchronized (accounts.cacheLock) {
Dmitry Dementyev47443192018-10-24 13:31:59 -07001399 accounts.accountsDb.closeDebugStatement();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001400 accounts.accountsDb.close();
1401 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001402 }
Amith Yamasani13593602012-03-22 16:16:17 -07001403 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001404 }
1405
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001406 @VisibleForTesting
1407 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001408 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1409 }
1410
1411 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001412 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1413 Log.v(TAG, "onUserUnlocked " + userId);
1414 }
1415 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001416 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001417 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001418 if (userId < 1) return;
Fyodor Kupolov2bc895d2017-12-19 11:53:47 -08001419 mHandler.post(() -> syncSharedAccounts(userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001420 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001421
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001422 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001423 // Check if there's a shared account that needs to be created as an account
1424 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1425 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001426 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001427 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001428 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001429 : UserHandle.USER_SYSTEM;
1430 if (parentUserId < 0) {
1431 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1432 return;
1433 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001434 for (Account sa : sharedAccounts) {
1435 if (ArrayUtils.contains(accounts, sa)) continue;
1436 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001437 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001438 }
1439 }
1440
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001441 @Override
1442 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Dmitry Dementyevc3e913b2019-07-11 11:32:16 -07001443 UserInfo user = getUserManager().getUserInfo(userId);
1444 if (user == null) {
1445 Log.w(TAG, "onServiceChanged: ignore removed user " + userId);
1446 return;
1447 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001448 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001449 }
1450
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001451 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001452 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001453 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001454 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1455 Log.v(TAG, "getPassword: " + account
1456 + ", caller's uid " + Binder.getCallingUid()
1457 + ", pid " + Binder.getCallingPid());
1458 }
Fred Quintana382601f2010-03-25 12:25:10 -07001459 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001460 int userId = UserHandle.getCallingUserId();
1461 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001462 String msg = String.format(
1463 "uid %s cannot get secrets for accounts of type: %s",
1464 callingUid,
1465 account.type);
1466 throw new SecurityException(msg);
1467 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001468 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001469 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001470 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001471 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001472 } finally {
1473 restoreCallingIdentity(identityToken);
1474 }
1475 }
1476
Amith Yamasani04e0d262012-02-14 11:50:53 -08001477 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001478 if (account == null) {
1479 return null;
1480 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001481 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001482 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1483 return null;
1484 }
Fred Quintana31957f12009-10-21 13:43:10 -07001485
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001486 synchronized (accounts.dbLock) {
1487 synchronized (accounts.cacheLock) {
1488 return accounts.accountsDb
1489 .findAccountPasswordByNameAndType(account.name, account.type);
1490 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001491 }
1492 }
1493
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001494 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001495 public String getPreviousName(Account account) {
1496 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1497 Log.v(TAG, "getPreviousName: " + account
1498 + ", caller's uid " + Binder.getCallingUid()
1499 + ", pid " + Binder.getCallingPid());
1500 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001501 Preconditions.checkNotNull(account, "account cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001502 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001503 long identityToken = clearCallingIdentity();
1504 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001505 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001506 return readPreviousNameInternal(accounts, account);
1507 } finally {
1508 restoreCallingIdentity(identityToken);
1509 }
1510 }
1511
1512 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1513 if (account == null) {
1514 return null;
1515 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001516 synchronized (accounts.dbLock) {
1517 synchronized (accounts.cacheLock) {
1518 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1519 if (previousNameRef == null) {
1520 String previousName = accounts.accountsDb.findDeAccountPreviousName(account);
1521 previousNameRef = new AtomicReference<>(previousName);
1522 accounts.previousNameCache.put(account, previousNameRef);
1523 return previousName;
1524 } else {
1525 return previousNameRef.get();
1526 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001527 }
1528 }
1529 }
1530
1531 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001532 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001533 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001534 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001535 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1536 account, key, callingUid, Binder.getCallingPid());
1537 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001538 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001539 Preconditions.checkNotNull(account, "account cannot be null");
1540 Preconditions.checkNotNull(key, "key cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001541 int userId = UserHandle.getCallingUserId();
1542 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001543 String msg = String.format(
1544 "uid %s cannot get user data for accounts of type: %s",
1545 callingUid,
1546 account.type);
1547 throw new SecurityException(msg);
1548 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001549 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001550 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1551 return null;
1552 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001553 long identityToken = clearCallingIdentity();
1554 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001555 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001556 if (!accountExistsCache(accounts, account)) {
1557 return null;
Simranjit Kohli858511c2016-03-10 18:36:11 +00001558 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001559 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001560 } finally {
1561 restoreCallingIdentity(identityToken);
1562 }
1563 }
1564
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001565 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001566 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001567 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001568 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1569 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001570 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001571 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001572 + ", pid " + Binder.getCallingPid());
1573 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001574 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001575 if (isCrossUser(callingUid, userId)) {
1576 throw new SecurityException(
1577 String.format(
1578 "User %s tying to get authenticator types for %s" ,
1579 UserHandle.getCallingUserId(),
1580 userId));
1581 }
1582
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001583 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001584 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001585 return getAuthenticatorTypesInternal(userId);
1586
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001587 } finally {
1588 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001589 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001590 }
1591
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001592 /**
1593 * Should only be called inside of a clearCallingIdentity block.
1594 */
1595 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
Fyodor Kupolov81446482016-08-24 11:27:49 -07001596 mAuthenticatorCache.updateServices(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001597 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1598 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1599 AuthenticatorDescription[] types =
1600 new AuthenticatorDescription[authenticatorCollection.size()];
1601 int i = 0;
1602 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1603 : authenticatorCollection) {
1604 types[i] = authenticator.type;
1605 i++;
1606 }
1607 return types;
1608 }
1609
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001610 private boolean isCrossUser(int callingUid, int userId) {
1611 return (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001612 && callingUid != Process.SYSTEM_UID
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001613 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001614 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1615 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001616 }
1617
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001618 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001619 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001620 return addAccountExplicitlyWithVisibility(account, password, extras, null);
Fred Quintana60307342009-03-24 22:48:12 -07001621 }
1622
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001623 @Override
1624 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001625 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001626 int callingUid = Binder.getCallingUid();
1627 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1628 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001629 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001630 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001631 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1632 final UserAccounts toAccounts = getUserAccounts(userTo);
1633 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001634 if (response != null) {
1635 Bundle result = new Bundle();
1636 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1637 try {
1638 response.onResult(result);
1639 } catch (RemoteException e) {
1640 Slog.w(TAG, "Failed to report error back to the client." + e);
1641 }
1642 }
1643 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001644 }
1645
Hui Yu139c2482018-08-10 15:37:51 -07001646 Slog.d(TAG, "Copying account " + account.toSafeString()
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001647 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001648 long identityToken = clearCallingIdentity();
1649 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001650 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001651 false /* stripAuthTokenFromResult */, account.name,
1652 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001653 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001654 protected String toDebugString(long now) {
1655 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1656 + ", " + account.type;
1657 }
1658
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001659 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001660 public void run() throws RemoteException {
1661 mAuthenticator.getAccountCredentialsForCloning(this, account);
1662 }
1663
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001664 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001665 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001666 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001667 if (result != null
1668 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1669 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001670 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001671 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001672 super.onResult(result);
1673 }
1674 }
1675 }.bind();
1676 } finally {
1677 restoreCallingIdentity(identityToken);
1678 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001679 }
1680
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001681 @Override
1682 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001683 final int callingUid = Binder.getCallingUid();
1684 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1685 String msg = String.format(
1686 "accountAuthenticated( account: %s, callerUid: %s)",
1687 account,
1688 callingUid);
1689 Log.v(TAG, msg);
1690 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001691 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001692 int userId = UserHandle.getCallingUserId();
1693 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001694 String msg = String.format(
1695 "uid %s cannot notify authentication for accounts of type: %s",
1696 callingUid,
1697 account.type);
1698 throw new SecurityException(msg);
1699 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001700
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001701 if (!canUserModifyAccounts(userId, callingUid) ||
1702 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001703 return false;
1704 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001705
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001706 long identityToken = clearCallingIdentity();
1707 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001708 UserAccounts accounts = getUserAccounts(userId);
1709 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001710 } finally {
1711 restoreCallingIdentity(identityToken);
1712 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001713 }
1714
1715 private boolean updateLastAuthenticatedTime(Account account) {
1716 final UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001717 synchronized (accounts.dbLock) {
1718 synchronized (accounts.cacheLock) {
1719 return accounts.accountsDb.updateAccountLastAuthenticatedTime(account);
1720 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001721 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001722 }
1723
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001724 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001725 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1726 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001727 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001728 long id = clearCallingIdentity();
1729 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001730 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001731 false /* stripAuthTokenFromResult */, account.name,
1732 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001733 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001734 protected String toDebugString(long now) {
1735 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1736 + ", " + account.type;
1737 }
1738
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001739 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001740 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001741 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov16bedd42017-03-30 10:00:49 -07001742 for (Account acc : getAccounts(parentUserId, mContext.getOpPackageName())) {
1743 if (acc.equals(account)) {
1744 mAuthenticator.addAccountFromCredentials(
1745 this, account, accountCredentials);
1746 break;
Amith Yamasani5be347b2013-03-31 17:44:31 -07001747 }
1748 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001749 }
1750
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001751 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001752 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001753 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001754 // TODO: Anything to do if if succedded?
1755 // TODO: If it failed: Show error notification? Should we remove the shadow
1756 // account to avoid retries?
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001757 // TODO: what we do with the visibility?
1758
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001759 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001760 }
1761
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001762 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001763 public void onError(int errorCode, String errorMessage) {
1764 super.onError(errorCode, errorMessage);
1765 // TODO: Show error notification to user
1766 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1767 }
1768
1769 }.bind();
1770 } finally {
1771 restoreCallingIdentity(id);
1772 }
1773 }
1774
Amith Yamasani04e0d262012-02-14 11:50:53 -08001775 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001776 Bundle extras, int callingUid, Map<String, Integer> packageToVisibility) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001777 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001778 if (account == null) {
1779 return false;
1780 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001781 if (!isLocalUnlockedUser(accounts.userId)) {
Hui Yu139c2482018-08-10 15:37:51 -07001782 Log.w(TAG, "Account " + account.toSafeString() + " cannot be added - user "
1783 + accounts.userId + " is locked. callingUid=" + callingUid);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001784 return false;
1785 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001786 synchronized (accounts.dbLock) {
1787 synchronized (accounts.cacheLock) {
1788 accounts.accountsDb.beginTransaction();
1789 try {
1790 if (accounts.accountsDb.findCeAccountId(account) >= 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001791 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001792 + ", skipping since the account already exists");
1793 return false;
1794 }
1795 long accountId = accounts.accountsDb.insertCeAccount(account, password);
1796 if (accountId < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001797 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001798 + ", skipping the DB insert failed");
1799 return false;
1800 }
1801 // Insert into DE table
1802 if (accounts.accountsDb.insertDeAccount(account, accountId) < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001803 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001804 + ", skipping the DB insert failed");
1805 return false;
1806 }
1807 if (extras != null) {
1808 for (String key : extras.keySet()) {
1809 final String value = extras.getString(key);
1810 if (accounts.accountsDb.insertExtra(accountId, key, value) < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001811 Log.w(TAG, "insertAccountIntoDatabase: "
1812 + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001813 + ", skipping since insertExtra failed for key " + key);
1814 return false;
1815 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001816 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001817 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001818
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001819 if (packageToVisibility != null) {
1820 for (Entry<String, Integer> entry : packageToVisibility.entrySet()) {
1821 setAccountVisibility(account, entry.getKey() /* package */,
1822 entry.getValue() /* visibility */, false /* notify */,
1823 accounts);
1824 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001825 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001826 accounts.accountsDb.setTransactionSuccessful();
1827
1828 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
1829 accountId,
1830 accounts, callingUid);
1831
1832 insertAccountIntoCacheLocked(accounts, account);
1833 } finally {
1834 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001835 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001836 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001837 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001838 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1839 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001840 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001841
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001842 sendNotificationAccountUpdated(account, accounts);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001843 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1844 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001845
Amith Yamasani5be347b2013-03-31 17:44:31 -07001846 return true;
1847 }
1848
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001849 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001850 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001851 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001852 }
1853 }
1854
Amith Yamasani5be347b2013-03-31 17:44:31 -07001855 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001856 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001857 * running, then clone the account too.
1858 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001859 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001860 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001861 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001862 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001863 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001864 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001865 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001866 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07001867 mHandler.sendMessage(mHandler.obtainMessage(
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001868 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001869 }
1870 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001871 }
1872 }
1873
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001874 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001875 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001876 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001877 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001878 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08001879 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1880 Log.v(TAG, "hasFeatures: " + account
1881 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001882 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001883 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001884 + ", pid " + Binder.getCallingPid());
1885 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001886 Preconditions.checkArgument(account != null, "account cannot be null");
1887 Preconditions.checkArgument(response != null, "response cannot be null");
1888 Preconditions.checkArgument(features != null, "features cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001889 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001890 checkReadAccountsPermitted(callingUid, account.type, userId,
1891 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001892
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001893 long identityToken = clearCallingIdentity();
1894 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001895 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001896 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001897 } finally {
1898 restoreCallingIdentity(identityToken);
1899 }
1900 }
1901
1902 private class TestFeaturesSession extends Session {
1903 private final String[] mFeatures;
1904 private final Account mAccount;
1905
Amith Yamasani04e0d262012-02-14 11:50:53 -08001906 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001907 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001908 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001909 true /* stripAuthTokenFromResult */, account.name,
1910 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001911 mFeatures = features;
1912 mAccount = account;
1913 }
1914
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001915 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001916 public void run() throws RemoteException {
1917 try {
1918 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1919 } catch (RemoteException e) {
1920 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1921 }
1922 }
1923
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001924 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001925 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001926 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001927 IAccountManagerResponse response = getResponseAndClose();
1928 if (response != null) {
1929 try {
1930 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001931 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001932 return;
1933 }
Fred Quintana56285a62010-12-02 14:20:51 -08001934 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1935 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1936 + response);
1937 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001938 final Bundle newResult = new Bundle();
1939 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1940 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1941 response.onResult(newResult);
1942 } catch (RemoteException e) {
1943 // if the caller is dead then there is no one to care about remote exceptions
1944 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1945 Log.v(TAG, "failure while notifying response", e);
1946 }
1947 }
1948 }
1949 }
1950
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001951 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001952 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001953 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001954 + ", " + mAccount
1955 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1956 }
1957 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001958
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001959 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001960 public void renameAccount(
1961 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001962 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001963 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1964 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001965 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001966 + ", pid " + Binder.getCallingPid());
1967 }
1968 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001969 int userId = UserHandle.getCallingUserId();
1970 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001971 String msg = String.format(
1972 "uid %s cannot rename accounts of type: %s",
1973 callingUid,
1974 accountToRename.type);
1975 throw new SecurityException(msg);
1976 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001977 long identityToken = clearCallingIdentity();
1978 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001979 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001980 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001981 Bundle result = new Bundle();
1982 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1983 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001984 result.putString(AccountManager.KEY_ACCOUNT_ACCESS_ID,
1985 resultingAccount.getAccessId());
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001986 try {
1987 response.onResult(result);
1988 } catch (RemoteException e) {
1989 Log.w(TAG, e.getMessage());
1990 }
1991 } finally {
1992 restoreCallingIdentity(identityToken);
1993 }
1994 }
1995
1996 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001997 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001998 Account resultAccount = null;
1999 /*
2000 * Cancel existing notifications. Let authenticators
2001 * re-post notifications as required. But we don't know if
2002 * the authenticators have bound their notifications to
2003 * now stale account name data.
2004 *
2005 * With a rename api, we might not need to do this anymore but it
2006 * shouldn't hurt.
2007 */
2008 cancelNotification(
2009 getSigninRequiredNotificationId(accounts, accountToRename),
Chris Wren717a8812017-03-31 15:34:39 -04002010 new UserHandle(accounts.userId));
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002011 synchronized(accounts.credentialsPermissionNotificationIds) {
2012 for (Pair<Pair<Account, String>, Integer> pair:
2013 accounts.credentialsPermissionNotificationIds.keySet()) {
2014 if (accountToRename.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002015 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002016 cancelNotification(id, new UserHandle(accounts.userId));
2017 }
2018 }
2019 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002020 synchronized (accounts.dbLock) {
2021 synchronized (accounts.cacheLock) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002022 List<String> accountRemovedReceivers =
2023 getAccountRemovedReceivers(accountToRename, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002024 accounts.accountsDb.beginTransaction();
2025 Account renamedAccount = new Account(newName, accountToRename.type);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002026 try {
chengangf2d081c2017-12-27 17:17:32 +08002027 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
2028 Log.e(TAG, "renameAccount failed - account with new name already exists");
2029 return null;
2030 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002031 final long accountId = accounts.accountsDb.findDeAccountId(accountToRename);
2032 if (accountId >= 0) {
2033 accounts.accountsDb.renameCeAccount(accountId, newName);
2034 if (accounts.accountsDb.renameDeAccount(
2035 accountId, newName, accountToRename.name)) {
2036 accounts.accountsDb.setTransactionSuccessful();
2037 } else {
2038 Log.e(TAG, "renameAccount failed");
2039 return null;
2040 }
2041 } else {
2042 Log.e(TAG, "renameAccount failed - old account does not exist");
2043 return null;
2044 }
2045 } finally {
2046 accounts.accountsDb.endTransaction();
2047 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002048 /*
2049 * Database transaction was successful. Clean up cached
2050 * data associated with the account in the user profile.
2051 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002052 renamedAccount = insertAccountIntoCacheLocked(accounts, renamedAccount);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002053 /*
2054 * Extract the data and token caches before removing the
2055 * old account to preserve the user data associated with
2056 * the account.
2057 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002058 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
2059 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
2060 Map<String, Integer> tmpVisibility = accounts.visibilityCache.get(accountToRename);
2061 removeAccountFromCacheLocked(accounts, accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002062 /*
2063 * Update the cached data associated with the renamed
2064 * account.
2065 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002066 accounts.userDataCache.put(renamedAccount, tmpData);
2067 accounts.authTokenCache.put(renamedAccount, tmpTokens);
2068 accounts.visibilityCache.put(renamedAccount, tmpVisibility);
2069 accounts.previousNameCache.put(
2070 renamedAccount,
2071 new AtomicReference<>(accountToRename.name));
2072 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002073
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002074 int parentUserId = accounts.userId;
2075 if (canHaveProfile(parentUserId)) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002076 /*
2077 * Owner or system user account was renamed, rename the account for
2078 * those users with which the account was shared.
2079 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002080 List<UserInfo> users = getUserManager().getUsers(true);
2081 for (UserInfo user : users) {
2082 if (user.isRestricted()
2083 && (user.restrictedProfileParentId == parentUserId)) {
2084 renameSharedAccountAsUser(accountToRename, newName, user.id);
2085 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002086 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002087 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002088
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002089 sendNotificationAccountUpdated(resultAccount, accounts);
2090 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002091 for (String packageName : accountRemovedReceivers) {
2092 sendAccountRemovedBroadcast(accountToRename, packageName, accounts.userId);
2093 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002094 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002095 }
2096 return resultAccount;
2097 }
2098
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002099 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002100 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002101 return userInfo != null && userInfo.canHaveProfile();
2102 }
2103
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002104 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002105 public void removeAccount(IAccountManagerResponse response, Account account,
2106 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002107 removeAccountAsUser(
2108 response,
2109 account,
2110 expectActivityLaunch,
2111 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002112 }
2113
2114 @Override
2115 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002116 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002117 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002118 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2119 Log.v(TAG, "removeAccount: " + account
2120 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002121 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002122 + ", pid " + Binder.getCallingPid()
2123 + ", for user id " + userId);
2124 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002125 Preconditions.checkArgument(account != null, "account cannot be null");
2126 Preconditions.checkArgument(response != null, "response cannot be null");
2127
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002128 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002129 if (isCrossUser(callingUid, userId)) {
2130 throw new SecurityException(
2131 String.format(
2132 "User %s tying remove account for %s" ,
2133 UserHandle.getCallingUserId(),
2134 userId));
2135 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002136 /*
Alex Chauf788f9c2017-12-08 15:16:46 +00002137 * Only the system, authenticator or profile owner should be allowed to remove accounts for
2138 * that authenticator. This will let users remove accounts (via Settings in the system) but
2139 * not arbitrary applications (like competing authenticators).
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002140 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002141 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00002142 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
Alex Chauf788f9c2017-12-08 15:16:46 +00002143 && !isSystemUid(callingUid)
2144 && !isProfileOwner(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002145 String msg = String.format(
2146 "uid %s cannot remove accounts of type: %s",
2147 callingUid,
2148 account.type);
2149 throw new SecurityException(msg);
2150 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002151 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002152 try {
2153 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2154 "User cannot modify accounts");
2155 } catch (RemoteException re) {
2156 }
2157 return;
2158 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002159 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002160 try {
2161 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2162 "User cannot modify accounts of this type (policy).");
2163 } catch (RemoteException re) {
2164 }
2165 return;
2166 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002167 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002168 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002169 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002170 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002171 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002172 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002173 if (account.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002174 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002175 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002176 }
2177 }
2178 }
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002179 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002180 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002181 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2182 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002183 accountId,
2184 accounts,
2185 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002186 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002187 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2188 } finally {
2189 restoreCallingIdentity(identityToken);
2190 }
2191 }
2192
2193 @Override
2194 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002195 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002196 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2197 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002198 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002199 + ", pid " + Binder.getCallingPid());
2200 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002201 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002202 if (account == null) {
2203 /*
2204 * Null accounts should result in returning false, as per
2205 * AccountManage.addAccountExplicitly(...) java doc.
2206 */
2207 Log.e(TAG, "account is null");
2208 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002209 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002210 String msg = String.format(
Brandon Weeks9e4e96d2017-08-24 15:24:16 -07002211 "uid %s cannot explicitly remove accounts of type: %s",
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002212 callingUid,
2213 account.type);
2214 throw new SecurityException(msg);
2215 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002216 UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002217 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002218 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002219 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2220 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002221 accountId,
2222 accounts,
2223 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002224 long identityToken = clearCallingIdentity();
2225 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002226 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002227 } finally {
2228 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002229 }
Fred Quintana60307342009-03-24 22:48:12 -07002230 }
2231
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002232 private class RemoveAccountSession extends Session {
2233 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002234 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002235 Account account, boolean expectActivityLaunch) {
2236 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002237 true /* stripAuthTokenFromResult */, account.name,
2238 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002239 mAccount = account;
2240 }
2241
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002242 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002243 protected String toDebugString(long now) {
2244 return super.toDebugString(now) + ", removeAccount"
2245 + ", account " + mAccount;
2246 }
2247
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002248 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002249 public void run() throws RemoteException {
2250 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2251 }
2252
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002253 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002254 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002255 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002256 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2257 && !result.containsKey(AccountManager.KEY_INTENT)) {
2258 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002259 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002260 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002261 }
2262 IAccountManagerResponse response = getResponseAndClose();
2263 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002264 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2265 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2266 + response);
2267 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002268 try {
tiansiming5330b5a2017-10-13 10:57:25 +08002269 response.onResult(result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002270 } catch (RemoteException e) {
tiansiming5330b5a2017-10-13 10:57:25 +08002271 Slog.e(TAG, "Error calling onResult()", e);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002272 }
2273 }
2274 }
2275 super.onResult(result);
2276 }
2277 }
2278
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002279 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002280 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002281 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002282 }
2283
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002284 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002285 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002286 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002287 if (!userUnlocked) {
Hui Yu139c2482018-08-10 15:37:51 -07002288 Slog.i(TAG, "Removing account " + account.toSafeString()
2289 + " while user " + accounts.userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002290 + " is still locked. CE data will be removed later");
2291 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002292 synchronized (accounts.dbLock) {
2293 synchronized (accounts.cacheLock) {
2294 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2295 accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002296 List<String> accountRemovedReceivers =
2297 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002298 accounts.accountsDb.beginTransaction();
2299 // Set to a dummy value, this will only be used if the database
2300 // transaction succeeds.
2301 long accountId = -1;
2302 try {
2303 accountId = accounts.accountsDb.findDeAccountId(account);
2304 if (accountId >= 0) {
2305 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002306 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002307 // always delete from CE table if CE storage is available
2308 // DE account could be removed while CE was locked
2309 if (userUnlocked) {
2310 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2311 if (ceAccountId >= 0) {
2312 accounts.accountsDb.deleteCeAccount(ceAccountId);
2313 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002314 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002315 accounts.accountsDb.setTransactionSuccessful();
2316 } finally {
2317 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002318 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002319 if (isChanged) {
2320 removeAccountFromCacheLocked(accounts, account);
2321 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2322 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002323 if ((packageToVisibility.getValue() == AccountManager.VISIBILITY_VISIBLE)
2324 || (packageToVisibility.getValue()
2325 == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002326 notifyPackage(packageToVisibility.getKey(), accounts);
2327 }
2328 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002329
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002330 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2331 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002332 for (String packageName : accountRemovedReceivers) {
2333 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
2334 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002335 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2336 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2337 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2338 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002339 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002340 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002341 long id = Binder.clearCallingIdentity();
2342 try {
2343 int parentUserId = accounts.userId;
2344 if (canHaveProfile(parentUserId)) {
2345 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002346 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002347 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002348 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002349 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002350 }
2351 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002352 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002353 } finally {
2354 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002355 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002356
2357 if (isChanged) {
2358 synchronized (accounts.credentialsPermissionNotificationIds) {
2359 for (Pair<Pair<Account, String>, Integer> key
2360 : accounts.credentialsPermissionNotificationIds.keySet()) {
2361 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002362 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002363 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002364 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002365 account, uid, false));
2366 }
2367 }
2368 }
2369 }
2370
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002371 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002372 }
2373
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002374 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002375 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002376 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002377 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2378 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002379 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2380 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002381 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002382 + ", pid " + Binder.getCallingPid());
2383 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002384 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002385 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002386 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002387 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002388 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002389 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002390 accounts.accountsDb.beginTransaction();
2391 try {
2392 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2393 accounts.accountsDb.setTransactionSuccessful();
2394 } finally {
2395 accounts.accountsDb.endTransaction();
2396 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002397 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002398 for (Pair<Account, String> tokenInfo : deletedTokens) {
2399 Account act = tokenInfo.first;
2400 String tokenType = tokenInfo.second;
2401 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002402 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002403 // wipe out cached token in memory.
2404 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002405 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002406 }
Fred Quintana60307342009-03-24 22:48:12 -07002407 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002408 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002409 }
2410 }
2411
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002412 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002413 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002414 // TODO Move to AccountsDB
2415 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002416 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002417
Fred Quintana33269202009-04-20 16:05:10 -07002418 try {
2419 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002420 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002421 String accountName = cursor.getString(1);
2422 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002423 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002424 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002425 }
Fred Quintana33269202009-04-20 16:05:10 -07002426 } finally {
2427 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002428 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002429 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002430 }
2431
Carlos Valdivia91979be2015-05-22 14:11:35 -07002432 private void saveCachedToken(
2433 UserAccounts accounts,
2434 Account account,
2435 String callerPkg,
2436 byte[] callerSigDigest,
2437 String tokenType,
2438 String token,
2439 long expiryMillis) {
2440
2441 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2442 return;
2443 }
2444 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002445 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002446 synchronized (accounts.cacheLock) {
2447 accounts.accountTokenCaches.put(
2448 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002449 }
2450 }
2451
Amith Yamasani04e0d262012-02-14 11:50:53 -08002452 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2453 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002454 if (account == null || type == null) {
2455 return false;
2456 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002457 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002458 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002459 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002460 accounts.accountsDb.beginTransaction();
2461 boolean updateCache = false;
2462 try {
2463 long accountId = accounts.accountsDb.findDeAccountId(account);
2464 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002465 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002466 }
2467 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2468 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2469 accounts.accountsDb.setTransactionSuccessful();
2470 updateCache = true;
2471 return true;
2472 }
2473 return false;
2474 } finally {
2475 accounts.accountsDb.endTransaction();
2476 if (updateCache) {
2477 synchronized (accounts.cacheLock) {
2478 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2479 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002480 }
Fred Quintana33269202009-04-20 16:05:10 -07002481 }
Fred Quintana60307342009-03-24 22:48:12 -07002482 }
2483 }
2484
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002485 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002486 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002487 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002488 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2489 Log.v(TAG, "peekAuthToken: " + account
2490 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002491 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002492 + ", pid " + Binder.getCallingPid());
2493 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002494 Preconditions.checkNotNull(account, "account cannot be null");
2495 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002496 int userId = UserHandle.getCallingUserId();
2497 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002498 String msg = String.format(
2499 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2500 callingUid,
2501 account.type);
2502 throw new SecurityException(msg);
2503 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002504 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002505 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2506 + callingUid);
2507 return null;
2508 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002509 long identityToken = clearCallingIdentity();
2510 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002511 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002512 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002513 } finally {
2514 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002515 }
Fred Quintana60307342009-03-24 22:48:12 -07002516 }
2517
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002518 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002519 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002520 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2522 Log.v(TAG, "setAuthToken: " + account
2523 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002524 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002525 + ", pid " + Binder.getCallingPid());
2526 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002527 Preconditions.checkNotNull(account, "account cannot be null");
2528 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002529 int userId = UserHandle.getCallingUserId();
2530 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002531 String msg = String.format(
2532 "uid %s cannot set auth tokens associated with accounts of type: %s",
2533 callingUid,
2534 account.type);
2535 throw new SecurityException(msg);
2536 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002537 long identityToken = clearCallingIdentity();
2538 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002539 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002540 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002541 } finally {
2542 restoreCallingIdentity(identityToken);
2543 }
Fred Quintana60307342009-03-24 22:48:12 -07002544 }
2545
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002546 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002547 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002548 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002549 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2550 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002551 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002552 + ", pid " + Binder.getCallingPid());
2553 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002554 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002555 int userId = UserHandle.getCallingUserId();
2556 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002557 String msg = String.format(
2558 "uid %s cannot set secrets for accounts of type: %s",
2559 callingUid,
2560 account.type);
2561 throw new SecurityException(msg);
2562 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002563 long identityToken = clearCallingIdentity();
2564 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002565 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002566 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002567 } finally {
2568 restoreCallingIdentity(identityToken);
2569 }
Fred Quintana60307342009-03-24 22:48:12 -07002570 }
2571
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002572 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2573 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002574 if (account == null) {
2575 return;
2576 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002577 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002578 synchronized (accounts.dbLock) {
2579 synchronized (accounts.cacheLock) {
2580 accounts.accountsDb.beginTransaction();
2581 try {
2582 final long accountId = accounts.accountsDb.findDeAccountId(account);
2583 if (accountId >= 0) {
2584 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2585 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2586 accounts.authTokenCache.remove(account);
2587 accounts.accountTokenCaches.remove(account);
2588 accounts.accountsDb.setTransactionSuccessful();
2589 // If there is an account whose password will be updated and the database
2590 // transactions succeed, then we say that a change has occured. Even if the
2591 // new password is the same as the old and there were no authtokens to
2592 // delete.
2593 isChanged = true;
2594 String action = (password == null || password.length() == 0) ?
2595 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2596 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2597 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2598 callingUid);
2599 }
2600 } finally {
2601 accounts.accountsDb.endTransaction();
2602 if (isChanged) {
2603 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2604 sendNotificationAccountUpdated(account, accounts);
2605 sendAccountsChangedBroadcast(accounts.userId);
2606 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002607 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002608 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002609 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002610 }
2611
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002612 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002613 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002614 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002615 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2616 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002617 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002618 + ", pid " + Binder.getCallingPid());
2619 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002620 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002621 int userId = UserHandle.getCallingUserId();
2622 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002623 String msg = String.format(
2624 "uid %s cannot clear passwords for accounts of type: %s",
2625 callingUid,
2626 account.type);
2627 throw new SecurityException(msg);
2628 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002629 long identityToken = clearCallingIdentity();
2630 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002631 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002632 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002633 } finally {
2634 restoreCallingIdentity(identityToken);
2635 }
Fred Quintana60307342009-03-24 22:48:12 -07002636 }
2637
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002638 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002639 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002640 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002641 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2642 Log.v(TAG, "setUserData: " + account
2643 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002644 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002645 + ", pid " + Binder.getCallingPid());
2646 }
Fred Quintana382601f2010-03-25 12:25:10 -07002647 if (key == null) throw new IllegalArgumentException("key is null");
2648 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002649 int userId = UserHandle.getCallingUserId();
2650 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002651 String msg = String.format(
2652 "uid %s cannot set user data for accounts of type: %s",
2653 callingUid,
2654 account.type);
2655 throw new SecurityException(msg);
2656 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002657 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002658 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002659 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002660 if (!accountExistsCache(accounts, account)) {
2661 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002662 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002663 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002664 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002665 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002666 }
2667 }
2668
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002669 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2670 synchronized (accounts.cacheLock) {
2671 if (accounts.accountCache.containsKey(account.type)) {
2672 for (Account acc : accounts.accountCache.get(account.type)) {
2673 if (acc.name.equals(account.name)) {
2674 return true;
2675 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002676 }
2677 }
2678 }
2679 return false;
2680 }
2681
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002682 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002683 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002684 synchronized (accounts.dbLock) {
2685 accounts.accountsDb.beginTransaction();
2686 try {
2687 long accountId = accounts.accountsDb.findDeAccountId(account);
2688 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002689 return;
2690 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002691 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2692 if (extrasId < 0) {
2693 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2694 if (extrasId < 0) {
2695 return;
2696 }
2697 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2698 return;
2699 }
2700 accounts.accountsDb.setTransactionSuccessful();
2701 } finally {
2702 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002703 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002704 synchronized (accounts.cacheLock) {
2705 writeUserDataIntoCacheLocked(accounts, account, key, value);
2706 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002707 }
2708 }
2709
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002710 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002711 if (result == null) {
2712 Log.e(TAG, "the result is unexpectedly null", new Exception());
2713 }
2714 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2715 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2716 + response);
2717 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002718 try {
2719 response.onResult(result);
2720 } catch (RemoteException e) {
2721 // if the caller is dead then there is no one to care about remote
2722 // exceptions
2723 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2724 Log.v(TAG, "failure while notifying response", e);
2725 }
2726 }
2727 }
2728
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002729 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002730 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2731 final String authTokenType)
2732 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002733 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2734 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002735
Fred Quintanad9640ec2012-05-23 12:37:00 -07002736 final int callingUid = getCallingUid();
2737 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002738 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002739 throw new SecurityException("can only call from system");
2740 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002741 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002742 long identityToken = clearCallingIdentity();
2743 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002744 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002745 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2746 false /* stripAuthTokenFromResult */, null /* accountName */,
2747 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002748 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002749 protected String toDebugString(long now) {
2750 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002751 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002752 + ", authTokenType " + authTokenType;
2753 }
2754
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002755 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002756 public void run() throws RemoteException {
2757 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2758 }
2759
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002760 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002761 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002762 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002763 if (result != null) {
2764 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2765 Bundle bundle = new Bundle();
2766 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2767 super.onResult(bundle);
2768 return;
2769 } else {
2770 super.onResult(result);
2771 }
2772 }
2773 }.bind();
2774 } finally {
2775 restoreCallingIdentity(identityToken);
2776 }
2777 }
2778
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002779 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002780 public void getAuthToken(
2781 IAccountManagerResponse response,
2782 final Account account,
2783 final String authTokenType,
2784 final boolean notifyOnAuthFailure,
2785 final boolean expectActivityLaunch,
2786 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002787 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002788 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2789 Log.v(TAG, "getAuthToken: " + account
2790 + ", response " + response
2791 + ", authTokenType " + authTokenType
2792 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2793 + ", expectActivityLaunch " + expectActivityLaunch
2794 + ", caller's uid " + Binder.getCallingUid()
2795 + ", pid " + Binder.getCallingPid());
2796 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002797 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002798 try {
2799 if (account == null) {
2800 Slog.w(TAG, "getAuthToken called with null account");
2801 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2802 return;
2803 }
2804 if (authTokenType == null) {
2805 Slog.w(TAG, "getAuthToken called with null authTokenType");
2806 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2807 return;
2808 }
2809 } catch (RemoteException e) {
2810 Slog.w(TAG, "Failed to report error back to the client." + e);
2811 return;
2812 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002813 int userId = UserHandle.getCallingUserId();
2814 long ident = Binder.clearCallingIdentity();
2815 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002816 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002817 try {
2818 accounts = getUserAccounts(userId);
2819 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2820 AuthenticatorDescription.newKey(account.type), accounts.userId);
2821 } finally {
2822 Binder.restoreCallingIdentity(ident);
2823 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002824
Costin Manolachea40c6302010-12-13 14:50:45 -08002825 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002826 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002827
2828 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002829 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002830 final boolean permissionGranted =
2831 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002832
Carlos Valdivia91979be2015-05-22 14:11:35 -07002833 // Get the calling package. We will use it for the purpose of caching.
2834 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002835 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002836 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002837 try {
2838 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2839 } finally {
2840 Binder.restoreCallingIdentity(ident);
2841 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002842 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2843 String msg = String.format(
2844 "Uid %s is attempting to illegally masquerade as package %s!",
2845 callerUid,
2846 callerPkg);
2847 throw new SecurityException(msg);
2848 }
2849
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002850 // let authenticator know the identity of the caller
2851 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2852 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002853
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002854 if (notifyOnAuthFailure) {
2855 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002856 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002857
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002858 long identityToken = clearCallingIdentity();
2859 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002860 // Distill the caller's package signatures into a single digest.
2861 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2862
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002863 // if the caller has permission, do the peek. otherwise go the more expensive
2864 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002865 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002866 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002867 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002868 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002869 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2870 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2871 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002872 onResult(response, result);
2873 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002874 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002875 }
2876
Carlos Valdivia91979be2015-05-22 14:11:35 -07002877 if (customTokens) {
2878 /*
2879 * Look up tokens in the new cache only if the loginOptions don't have parameters
2880 * outside of those expected to be injected by the AccountManager, e.g.
2881 * ANDORID_PACKAGE_NAME.
2882 */
2883 String token = readCachedTokenInternal(
2884 accounts,
2885 account,
2886 authTokenType,
2887 callerPkg,
2888 callerPkgSigDigest);
2889 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002890 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2891 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2892 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002893 Bundle result = new Bundle();
2894 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2895 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2896 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2897 onResult(response, result);
2898 return;
2899 }
2900 }
2901
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002902 new Session(
2903 accounts,
2904 response,
2905 account.type,
2906 expectActivityLaunch,
2907 false /* stripAuthTokenFromResult */,
2908 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002909 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002910 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002911 protected String toDebugString(long now) {
2912 if (loginOptions != null) loginOptions.keySet();
2913 return super.toDebugString(now) + ", getAuthToken"
Hui Yu139c2482018-08-10 15:37:51 -07002914 + ", " + account.toSafeString()
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002915 + ", authTokenType " + authTokenType
2916 + ", loginOptions " + loginOptions
2917 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2918 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002919
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002920 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002921 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002922 // If the caller doesn't have permission then create and return the
2923 // "grant permission" intent instead of the "getAuthToken" intent.
2924 if (!permissionGranted) {
2925 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2926 } else {
2927 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2928 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002929 }
2930
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002931 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002932 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002933 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002934 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002935 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002936 Intent intent = newGrantCredentialsPermissionIntent(
2937 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002938 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002939 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002940 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002941 authTokenType,
2942 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002943 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002944 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002945 onResult(bundle);
2946 return;
2947 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002948 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002949 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002950 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2951 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002952 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002953 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002954 "the type and name should not be empty");
2955 return;
2956 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002957 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002958 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002959 saveAuthTokenToDatabase(
2960 mAccounts,
2961 resultAccount,
2962 authTokenType,
2963 authToken);
2964 }
2965 long expiryMillis = result.getLong(
2966 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2967 if (customTokens
2968 && expiryMillis > System.currentTimeMillis()) {
2969 saveCachedToken(
2970 mAccounts,
2971 account,
2972 callerPkg,
2973 callerPkgSigDigest,
2974 authTokenType,
2975 authToken,
2976 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002977 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002978 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002979
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002980 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002981 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002982 /*
2983 * Make sure that the supplied intent is owned by the authenticator
2984 * giving it to the system. Otherwise a malicious authenticator could
2985 * have users launching arbitrary activities by tricking users to
2986 * interact with malicious notifications.
2987 */
tiansiminga8868bf2017-09-20 13:59:13 +08002988 if (!checkKeyIntent(
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002989 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08002990 intent)) {
2991 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
2992 "invalid intent in bundle returned");
2993 return;
2994 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002995 doNotification(
2996 mAccounts,
2997 account,
2998 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002999 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003000 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003001 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003002 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07003003 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003004 }.bind();
3005 } finally {
3006 restoreCallingIdentity(identityToken);
3007 }
Fred Quintana60307342009-03-24 22:48:12 -07003008 }
3009
Carlos Valdivia91979be2015-05-22 14:11:35 -07003010 private byte[] calculatePackageSignatureDigest(String callerPkg) {
3011 MessageDigest digester;
3012 try {
3013 digester = MessageDigest.getInstance("SHA-256");
3014 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3015 callerPkg, PackageManager.GET_SIGNATURES);
3016 for (Signature sig : pkgInfo.signatures) {
3017 digester.update(sig.toByteArray());
3018 }
3019 } catch (NoSuchAlgorithmException x) {
3020 Log.wtf(TAG, "SHA-256 should be available", x);
3021 digester = null;
3022 } catch (NameNotFoundException e) {
3023 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
3024 digester = null;
3025 }
3026 return (digester == null) ? null : digester.digest();
3027 }
3028
Dianne Hackborn41203752012-08-31 14:05:51 -07003029 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003030 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003031 int uid = intent.getIntExtra(
3032 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
3033 String authTokenType = intent.getStringExtra(
3034 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07003035 final String titleAndSubtitle =
3036 mContext.getString(R.string.permission_request_notification_with_subtitle,
3037 account.name);
3038 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07003039 String title = titleAndSubtitle;
3040 String subtitle = "";
3041 if (index > 0) {
3042 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04003043 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07003044 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07003045 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003046 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05003047 Notification n =
3048 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
3049 .setSmallIcon(android.R.drawable.stat_sys_warning)
3050 .setWhen(0)
3051 .setColor(contextForUser.getColor(
3052 com.android.internal.R.color.system_notification_accent_color))
3053 .setContentTitle(title)
3054 .setContentText(subtitle)
3055 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
3056 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
3057 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003058 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003059 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003060 }
3061
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003062 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
3063 int uid, AccountAuthenticatorResponse response, String authTokenType,
3064 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003065
3066 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003067
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003068 if (startInNewTask) {
3069 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
3070 // Since it was set in Eclair+ we can't change it without breaking apps using
3071 // the intent from a non-Activity context. This is the default behavior.
3072 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3073 }
Chris Wren717a8812017-03-31 15:34:39 -04003074 intent.addCategory(getCredentialPermissionNotificationId(account,
3075 authTokenType, uid).mTag + (packageName != null ? packageName : ""));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003076 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003077 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
3078 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003079 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003080
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003081 return intent;
3082 }
3083
Chris Wren717a8812017-03-31 15:34:39 -04003084 private NotificationId getCredentialPermissionNotificationId(Account account,
3085 String authTokenType, int uid) {
3086 NotificationId nId;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003087 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003088 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003089 final Pair<Pair<Account, String>, Integer> key =
3090 new Pair<Pair<Account, String>, Integer>(
3091 new Pair<Account, String>(account, authTokenType), uid);
Chris Wren717a8812017-03-31 15:34:39 -04003092 nId = accounts.credentialsPermissionNotificationIds.get(key);
3093 if (nId == null) {
3094 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION
3095 + ":" + account.hashCode() + ":" + authTokenType.hashCode();
3096 int id = SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION;
3097 nId = new NotificationId(tag, id);
3098 accounts.credentialsPermissionNotificationIds.put(key, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003099 }
3100 }
Chris Wren717a8812017-03-31 15:34:39 -04003101 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003102 }
3103
Chris Wren717a8812017-03-31 15:34:39 -04003104 private NotificationId getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
3105 NotificationId nId;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003106 synchronized (accounts.signinRequiredNotificationIds) {
Chris Wren717a8812017-03-31 15:34:39 -04003107 nId = accounts.signinRequiredNotificationIds.get(account);
3108 if (nId == null) {
3109 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN
3110 + ":" + account.hashCode();
3111 int id = SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN;
3112 nId = new NotificationId(tag, id);
3113 accounts.signinRequiredNotificationIds.put(account, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003114 }
3115 }
Chris Wren717a8812017-03-31 15:34:39 -04003116 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003117 }
3118
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003119 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07003120 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07003121 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003122 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003123 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003124 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3125 Log.v(TAG, "addAccount: accountType " + accountType
3126 + ", response " + response
3127 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003128 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08003129 + ", expectActivityLaunch " + expectActivityLaunch
3130 + ", caller's uid " + Binder.getCallingUid()
3131 + ", pid " + Binder.getCallingPid());
3132 }
Fred Quintana382601f2010-03-25 12:25:10 -07003133 if (response == null) throw new IllegalArgumentException("response is null");
3134 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003135
Amith Yamasani71e6c692013-03-24 17:39:28 -07003136 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003137 final int uid = Binder.getCallingUid();
3138 final int userId = UserHandle.getUserId(uid);
3139 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003140 try {
3141 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3142 "User is not allowed to add an account!");
3143 } catch (RemoteException re) {
3144 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003145 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003146 return;
3147 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003148 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003149 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003150 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3151 "User cannot modify accounts of this type (policy).");
3152 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003153 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003154 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3155 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003156 return;
3157 }
3158
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003159 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003160 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3161 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3162 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3163
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003164 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003165 long identityToken = clearCallingIdentity();
3166 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003167 UserAccounts accounts = getUserAccounts(usrId);
3168 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003169 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3170 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003171 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003172 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003173 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003174 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003175 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003176 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003177 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003178 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003179
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003180 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003181 protected String toDebugString(long now) {
3182 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003183 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003184 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003185 }
3186 }.bind();
3187 } finally {
3188 restoreCallingIdentity(identityToken);
3189 }
Fred Quintana60307342009-03-24 22:48:12 -07003190 }
3191
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003192 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003193 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3194 final String authTokenType, final String[] requiredFeatures,
3195 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003196 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003197 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003198 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3199 Log.v(TAG, "addAccount: accountType " + accountType
3200 + ", response " + response
3201 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003202 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003203 + ", expectActivityLaunch " + expectActivityLaunch
3204 + ", caller's uid " + Binder.getCallingUid()
3205 + ", pid " + Binder.getCallingPid()
3206 + ", for user id " + userId);
3207 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003208 Preconditions.checkArgument(response != null, "response cannot be null");
3209 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003210 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003211 if (isCrossUser(callingUid, userId)) {
3212 throw new SecurityException(
3213 String.format(
3214 "User %s trying to add account for %s" ,
3215 UserHandle.getCallingUserId(),
3216 userId));
3217 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003218
3219 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003220 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003221 try {
3222 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3223 "User is not allowed to add an account!");
3224 } catch (RemoteException re) {
3225 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003226 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003227 return;
3228 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003229 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003230 try {
3231 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3232 "User cannot modify accounts of this type (policy).");
3233 } catch (RemoteException re) {
3234 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003235 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3236 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003237 return;
3238 }
3239
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003240 final int pid = Binder.getCallingPid();
3241 final int uid = Binder.getCallingUid();
3242 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3243 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3244 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3245
3246 long identityToken = clearCallingIdentity();
3247 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003248 UserAccounts accounts = getUserAccounts(userId);
3249 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003250 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
Valentin Iftime0e7f5bb2019-10-30 19:29:33 +01003251 uid);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003252 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003253 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003254 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003255 @Override
3256 public void run() throws RemoteException {
3257 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3258 options);
3259 }
3260
3261 @Override
3262 protected String toDebugString(long now) {
3263 return super.toDebugString(now) + ", addAccount"
3264 + ", accountType " + accountType
3265 + ", requiredFeatures "
3266 + (requiredFeatures != null
3267 ? TextUtils.join(",", requiredFeatures)
3268 : null);
3269 }
3270 }.bind();
3271 } finally {
3272 restoreCallingIdentity(identityToken);
3273 }
3274 }
3275
Sandra Kwan78812282015-11-04 11:19:47 -08003276 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003277 public void startAddAccountSession(
3278 final IAccountManagerResponse response,
3279 final String accountType,
3280 final String authTokenType,
3281 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003282 final boolean expectActivityLaunch,
3283 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003284 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003285 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3286 Log.v(TAG,
3287 "startAddAccountSession: accountType " + accountType
3288 + ", response " + response
3289 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003290 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003291 + ", expectActivityLaunch " + expectActivityLaunch
3292 + ", caller's uid " + Binder.getCallingUid()
3293 + ", pid " + Binder.getCallingPid());
3294 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003295 Preconditions.checkArgument(response != null, "response cannot be null");
3296 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003297
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003298 final int uid = Binder.getCallingUid();
3299 final int userId = UserHandle.getUserId(uid);
3300 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003301 try {
3302 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3303 "User is not allowed to add an account!");
3304 } catch (RemoteException re) {
3305 }
3306 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3307 return;
3308 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003309 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003310 try {
3311 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3312 "User cannot modify accounts of this type (policy).");
3313 } catch (RemoteException re) {
3314 }
3315 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3316 userId);
3317 return;
3318 }
Sandra Kwan78812282015-11-04 11:19:47 -08003319 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003320 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3321 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3322 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3323
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003324 // Check to see if the Password should be included to the caller.
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07003325 String callerPkg = options.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3326 boolean isPasswordForwardingAllowed = checkPermissionAndNote(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003327 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003328
Sandra Kwan78812282015-11-04 11:19:47 -08003329 long identityToken = clearCallingIdentity();
3330 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003331 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003332 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3333 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003334 new StartAccountSession(
3335 accounts,
3336 response,
3337 accountType,
3338 expectActivityLaunch,
3339 null /* accountName */,
3340 false /* authDetailsRequired */,
3341 true /* updateLastAuthenticationTime */,
3342 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003343 @Override
3344 public void run() throws RemoteException {
3345 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3346 requiredFeatures, options);
3347 }
3348
3349 @Override
3350 protected String toDebugString(long now) {
3351 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3352 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3353 + accountType + ", requiredFeatures "
3354 + (requiredFeatures != null ? requiredFeaturesStr : null);
3355 }
3356 }.bind();
3357 } finally {
3358 restoreCallingIdentity(identityToken);
3359 }
3360 }
3361
3362 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3363 private abstract class StartAccountSession extends Session {
3364
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003365 private final boolean mIsPasswordForwardingAllowed;
3366
3367 public StartAccountSession(
3368 UserAccounts accounts,
3369 IAccountManagerResponse response,
3370 String accountType,
3371 boolean expectActivityLaunch,
3372 String accountName,
3373 boolean authDetailsRequired,
3374 boolean updateLastAuthenticationTime,
3375 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003376 super(accounts, response, accountType, expectActivityLaunch,
3377 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3378 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003379 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003380 }
3381
3382 @Override
3383 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003384 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003385 mNumResults++;
3386 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003387 if (result != null
3388 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
tiansiminga8868bf2017-09-20 13:59:13 +08003389 if (!checkKeyIntent(
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003390 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08003391 intent)) {
3392 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
3393 "invalid intent in bundle returned");
3394 return;
3395 }
Sandra Kwan78812282015-11-04 11:19:47 -08003396 }
Sandra Kwan78812282015-11-04 11:19:47 -08003397 IAccountManagerResponse response;
3398 if (mExpectActivityLaunch && result != null
3399 && result.containsKey(AccountManager.KEY_INTENT)) {
3400 response = mResponse;
3401 } else {
3402 response = getResponseAndClose();
3403 }
3404 if (response == null) {
3405 return;
3406 }
3407 if (result == null) {
3408 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3409 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3410 + response);
3411 }
3412 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3413 "null bundle returned");
3414 return;
3415 }
3416
3417 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3418 // All AccountManager error codes are greater
3419 // than 0
3420 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3421 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3422 return;
3423 }
3424
Hongming Jin368aa192016-07-29 14:29:54 -07003425 // Omit passwords if the caller isn't permitted to see them.
3426 if (!mIsPasswordForwardingAllowed) {
3427 result.remove(AccountManager.KEY_PASSWORD);
3428 }
3429
Sandra Kwan78812282015-11-04 11:19:47 -08003430 // Strip auth token from result.
3431 result.remove(AccountManager.KEY_AUTHTOKEN);
3432
3433 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3434 Log.v(TAG,
3435 getClass().getSimpleName() + " calling onResult() on response " + response);
3436 }
3437
3438 // Get the session bundle created by authenticator. The
3439 // bundle contains data necessary for finishing the session
3440 // later. The session bundle will be encrypted here and
3441 // decrypted later when trying to finish the session.
3442 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3443 if (sessionBundle != null) {
3444 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3445 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003446 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003447 Log.w(TAG, "Account type in session bundle doesn't match request.");
3448 }
3449 // Add accountType info to session bundle. This will
3450 // override any value set by authenticator.
3451 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3452
3453 // Encrypt session bundle before returning to caller.
3454 try {
3455 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3456 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3457 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3458 } catch (GeneralSecurityException e) {
3459 if (Log.isLoggable(TAG, Log.DEBUG)) {
3460 Log.v(TAG, "Failed to encrypt session bundle!", e);
3461 }
3462 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3463 "failed to encrypt session bundle");
3464 return;
3465 }
3466 }
3467
3468 sendResponse(response, result);
3469 }
3470 }
3471
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003472 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003473 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003474 @NonNull Bundle sessionBundle,
3475 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003476 Bundle appInfo,
3477 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003478 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003479 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3481 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003482 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003483 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003484 + ", caller's uid " + callingUid
3485 + ", caller's user id " + UserHandle.getCallingUserId()
3486 + ", pid " + Binder.getCallingPid()
3487 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003488 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003489 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003490 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3491 // Account type is added to it before encryption.
3492 if (sessionBundle == null || sessionBundle.size() == 0) {
3493 throw new IllegalArgumentException("sessionBundle is empty");
3494 }
3495
Dmitry Dementyev52745472016-12-02 10:27:45 -08003496 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003497 if (isCrossUser(callingUid, userId)) {
3498 throw new SecurityException(
3499 String.format(
3500 "User %s trying to finish session for %s without cross user permission",
3501 UserHandle.getCallingUserId(),
3502 userId));
3503 }
3504
Sandra Kwan0b84b452016-01-20 15:25:42 -08003505 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003506 sendErrorResponse(response,
3507 AccountManager.ERROR_CODE_USER_RESTRICTED,
3508 "User is not allowed to add an account!");
3509 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3510 return;
3511 }
3512
3513 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003514 final Bundle decryptedBundle;
3515 final String accountType;
3516 // First decrypt session bundle to get account type for checking permission.
3517 try {
3518 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3519 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3520 if (decryptedBundle == null) {
3521 sendErrorResponse(
3522 response,
3523 AccountManager.ERROR_CODE_BAD_REQUEST,
3524 "failed to decrypt session bundle");
3525 return;
3526 }
3527 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3528 // Account type cannot be null. This should not happen if session bundle was created
3529 // properly by #StartAccountSession.
3530 if (TextUtils.isEmpty(accountType)) {
3531 sendErrorResponse(
3532 response,
3533 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3534 "accountType is empty");
3535 return;
3536 }
3537
3538 // If by any chances, decryptedBundle contains colliding keys with
3539 // system info
3540 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3541 // update credentials flow, we should replace with the new values of the current call.
3542 if (appInfo != null) {
3543 decryptedBundle.putAll(appInfo);
3544 }
3545
3546 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003547 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003548 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3549 } catch (GeneralSecurityException e) {
3550 if (Log.isLoggable(TAG, Log.DEBUG)) {
3551 Log.v(TAG, "Failed to decrypt session bundle!", e);
3552 }
3553 sendErrorResponse(
3554 response,
3555 AccountManager.ERROR_CODE_BAD_REQUEST,
3556 "failed to decrypt session bundle");
3557 return;
3558 }
3559
Sandra Kwan0b84b452016-01-20 15:25:42 -08003560 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003561 sendErrorResponse(
3562 response,
3563 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3564 "User cannot modify accounts of this type (policy).");
3565 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3566 userId);
3567 return;
3568 }
3569
3570 long identityToken = clearCallingIdentity();
3571 try {
3572 UserAccounts accounts = getUserAccounts(userId);
3573 logRecordWithUid(
3574 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003575 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3576 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003577 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003578 new Session(
3579 accounts,
3580 response,
3581 accountType,
3582 expectActivityLaunch,
3583 true /* stripAuthTokenFromResult */,
3584 null /* accountName */,
3585 false /* authDetailsRequired */,
3586 true /* updateLastAuthenticationTime */) {
3587 @Override
3588 public void run() throws RemoteException {
3589 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3590 }
3591
3592 @Override
3593 protected String toDebugString(long now) {
3594 return super.toDebugString(now)
3595 + ", finishSession"
3596 + ", accountType " + accountType;
3597 }
3598 }.bind();
3599 } finally {
3600 restoreCallingIdentity(identityToken);
3601 }
3602 }
3603
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003604 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003605 final DevicePolicyManagerInternal dpmi =
3606 LocalServices.getService(DevicePolicyManagerInternal.class);
3607 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003608 if (dpmi == null) {
3609 intent = getDefaultCantAddAccountIntent(errorCode);
3610 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003611 intent = dpmi.createUserRestrictionSupportIntent(userId,
3612 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3613 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3614 intent = dpmi.createShowAdminSupportIntent(userId, false);
3615 }
3616 if (intent == null) {
3617 intent = getDefaultCantAddAccountIntent(errorCode);
3618 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003619 long identityToken = clearCallingIdentity();
3620 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003621 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003622 } finally {
3623 restoreCallingIdentity(identityToken);
3624 }
3625 }
3626
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003627 /**
3628 * Called when we don't know precisely who is preventing us from adding an account.
3629 */
3630 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3631 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3632 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3633 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3634 return cantAddAccount;
3635 }
3636
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003637 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003638 public void confirmCredentialsAsUser(
3639 IAccountManagerResponse response,
3640 final Account account,
3641 final Bundle options,
3642 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003643 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003644 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003645 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003646 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3647 Log.v(TAG, "confirmCredentials: " + account
3648 + ", response " + response
3649 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003650 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003651 + ", pid " + Binder.getCallingPid());
3652 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003653 // Only allow the system process to read accounts of other users
3654 if (isCrossUser(callingUid, userId)) {
3655 throw new SecurityException(
3656 String.format(
3657 "User %s trying to confirm account credentials for %s" ,
3658 UserHandle.getCallingUserId(),
3659 userId));
3660 }
Fred Quintana382601f2010-03-25 12:25:10 -07003661 if (response == null) throw new IllegalArgumentException("response is null");
3662 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003663 long identityToken = clearCallingIdentity();
3664 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003665 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003666 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003667 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003668 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003669 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003670 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003671 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003672 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003673 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003674 protected String toDebugString(long now) {
3675 return super.toDebugString(now) + ", confirmCredentials"
Hui Yu139c2482018-08-10 15:37:51 -07003676 + ", " + account.toSafeString();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003677 }
3678 }.bind();
3679 } finally {
3680 restoreCallingIdentity(identityToken);
3681 }
Fred Quintana60307342009-03-24 22:48:12 -07003682 }
3683
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003684 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003685 public void updateCredentials(IAccountManagerResponse response, final Account account,
3686 final String authTokenType, final boolean expectActivityLaunch,
3687 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003688 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003689 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3690 Log.v(TAG, "updateCredentials: " + account
3691 + ", response " + response
3692 + ", authTokenType " + authTokenType
3693 + ", expectActivityLaunch " + expectActivityLaunch
3694 + ", caller's uid " + Binder.getCallingUid()
3695 + ", pid " + Binder.getCallingPid());
3696 }
Fred Quintana382601f2010-03-25 12:25:10 -07003697 if (response == null) throw new IllegalArgumentException("response is null");
3698 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003699 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003700 long identityToken = clearCallingIdentity();
3701 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003702 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003703 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003704 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003705 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003706 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003707 public void run() throws RemoteException {
3708 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3709 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003710 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003711 protected String toDebugString(long now) {
3712 if (loginOptions != null) loginOptions.keySet();
3713 return super.toDebugString(now) + ", updateCredentials"
Hui Yu139c2482018-08-10 15:37:51 -07003714 + ", " + account.toSafeString()
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003715 + ", authTokenType " + authTokenType
3716 + ", loginOptions " + loginOptions;
3717 }
3718 }.bind();
3719 } finally {
3720 restoreCallingIdentity(identityToken);
3721 }
Fred Quintana60307342009-03-24 22:48:12 -07003722 }
3723
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003724 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003725 public void startUpdateCredentialsSession(
3726 IAccountManagerResponse response,
3727 final Account account,
3728 final String authTokenType,
3729 final boolean expectActivityLaunch,
3730 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003731 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003732 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3733 Log.v(TAG,
3734 "startUpdateCredentialsSession: " + account + ", response " + response
3735 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3736 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3737 + ", pid " + Binder.getCallingPid());
3738 }
3739 if (response == null) {
3740 throw new IllegalArgumentException("response is null");
3741 }
3742 if (account == null) {
3743 throw new IllegalArgumentException("account is null");
3744 }
Sandra Kwana578d112015-12-16 16:01:43 -08003745
3746 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003747 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003748
3749 // Check to see if the Password should be included to the caller.
3750 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07003751 boolean isPasswordForwardingAllowed = checkPermissionAndNote(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003752 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003753
Sandra Kwane68c37e2015-11-12 17:11:49 -08003754 long identityToken = clearCallingIdentity();
3755 try {
3756 UserAccounts accounts = getUserAccounts(userId);
3757 new StartAccountSession(
3758 accounts,
3759 response,
3760 account.type,
3761 expectActivityLaunch,
3762 account.name,
3763 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003764 true /* updateLastCredentialTime */,
3765 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003766 @Override
3767 public void run() throws RemoteException {
3768 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3769 loginOptions);
3770 }
3771
3772 @Override
3773 protected String toDebugString(long now) {
3774 if (loginOptions != null)
3775 loginOptions.keySet();
3776 return super.toDebugString(now)
3777 + ", startUpdateCredentialsSession"
Hui Yu139c2482018-08-10 15:37:51 -07003778 + ", " + account.toSafeString()
Sandra Kwane68c37e2015-11-12 17:11:49 -08003779 + ", authTokenType " + authTokenType
3780 + ", loginOptions " + loginOptions;
3781 }
3782 }.bind();
3783 } finally {
3784 restoreCallingIdentity(identityToken);
3785 }
3786 }
3787
3788 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003789 public void isCredentialsUpdateSuggested(
3790 IAccountManagerResponse response,
3791 final Account account,
3792 final String statusToken) {
3793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3794 Log.v(TAG,
3795 "isCredentialsUpdateSuggested: " + account + ", response " + response
3796 + ", caller's uid " + Binder.getCallingUid()
3797 + ", pid " + Binder.getCallingPid());
3798 }
3799 if (response == null) {
3800 throw new IllegalArgumentException("response is null");
3801 }
3802 if (account == null) {
3803 throw new IllegalArgumentException("account is null");
3804 }
3805 if (TextUtils.isEmpty(statusToken)) {
3806 throw new IllegalArgumentException("status token is empty");
3807 }
3808
Sandra Kwan390c9d22016-01-12 14:13:37 -08003809 int usrId = UserHandle.getCallingUserId();
3810 long identityToken = clearCallingIdentity();
3811 try {
3812 UserAccounts accounts = getUserAccounts(usrId);
3813 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3814 false /* stripAuthTokenFromResult */, account.name,
3815 false /* authDetailsRequired */) {
3816 @Override
3817 protected String toDebugString(long now) {
3818 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
Hui Yu139c2482018-08-10 15:37:51 -07003819 + ", " + account.toSafeString();
Sandra Kwan390c9d22016-01-12 14:13:37 -08003820 }
3821
3822 @Override
3823 public void run() throws RemoteException {
3824 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3825 }
3826
3827 @Override
3828 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003829 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003830 IAccountManagerResponse response = getResponseAndClose();
3831 if (response == null) {
3832 return;
3833 }
3834
3835 if (result == null) {
3836 sendErrorResponse(
3837 response,
3838 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3839 "null bundle");
3840 return;
3841 }
3842
3843 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3844 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3845 + response);
3846 }
3847 // Check to see if an error occurred. We know if an error occurred because all
3848 // error codes are greater than 0.
3849 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3850 sendErrorResponse(response,
3851 result.getInt(AccountManager.KEY_ERROR_CODE),
3852 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3853 return;
3854 }
3855 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3856 sendErrorResponse(
3857 response,
3858 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3859 "no result in response");
3860 return;
3861 }
3862 final Bundle newResult = new Bundle();
3863 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3864 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3865 sendResponse(response, newResult);
3866 }
3867 }.bind();
3868 } finally {
3869 restoreCallingIdentity(identityToken);
3870 }
3871 }
3872
3873 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003874 public void editProperties(IAccountManagerResponse response, final String accountType,
3875 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003876 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003877 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3878 Log.v(TAG, "editProperties: accountType " + accountType
3879 + ", response " + response
3880 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003881 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003882 + ", pid " + Binder.getCallingPid());
3883 }
Fred Quintana382601f2010-03-25 12:25:10 -07003884 if (response == null) throw new IllegalArgumentException("response is null");
3885 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003886 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003887 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3888 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003889 String msg = String.format(
3890 "uid %s cannot edit authenticator properites for account type: %s",
3891 callingUid,
3892 accountType);
3893 throw new SecurityException(msg);
3894 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003895 long identityToken = clearCallingIdentity();
3896 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003897 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003898 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003899 true /* stripAuthTokenFromResult */, null /* accountName */,
3900 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003901 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003902 public void run() throws RemoteException {
3903 mAuthenticator.editProperties(this, mAccountType);
3904 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003905 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003906 protected String toDebugString(long now) {
3907 return super.toDebugString(now) + ", editProperties"
3908 + ", accountType " + accountType;
3909 }
3910 }.bind();
3911 } finally {
3912 restoreCallingIdentity(identityToken);
3913 }
Fred Quintana60307342009-03-24 22:48:12 -07003914 }
3915
Amith Yamasani12747872015-12-07 14:19:49 -08003916 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003917 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3918 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003919 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003920 throw new SecurityException("Can be called only by system UID");
3921 }
3922 Preconditions.checkNotNull(account, "account cannot be null");
3923 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3924 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3925
3926 final int userId = userHandle.getIdentifier();
3927
3928 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3929
3930 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003931 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003932 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003933 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003934 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003935 return false;
3936 }
3937 }
3938
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003939 // Returns package with oldest target SDK for given UID.
3940 private String getPackageNameForUid(int uid) {
3941 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3942 if (ArrayUtils.isEmpty(packageNames)) {
3943 return null;
3944 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003945 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003946 if (packageNames.length == 1) {
3947 return packageName;
3948 }
3949 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003950 int oldestVersion = Integer.MAX_VALUE;
3951 for (String name : packageNames) {
3952 try {
3953 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3954 if (applicationInfo != null) {
3955 int version = applicationInfo.targetSdkVersion;
3956 if (version < oldestVersion) {
3957 oldestVersion = version;
3958 packageName = name;
3959 }
3960 }
3961 } catch (NameNotFoundException e) {
3962 // skip
3963 }
3964 }
3965 return packageName;
3966 }
3967
Svet Ganovf6d424f12016-09-20 20:18:53 -07003968 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3969 int uid) {
3970 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003971 packageName = getPackageNameForUid(uid);
3972 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07003973 return false;
3974 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003975 }
3976
3977 // Use null token which means any token. Having a token means the package
3978 // is trusted by the authenticator, hence it is fine to access the account.
3979 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
3980 return true;
3981 }
3982 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003983 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07003984
Dmitry Dementyeve366f822017-01-31 10:25:10 -08003985 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003986 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003987 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003988 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003989 }
3990
3991 @Override
3992 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3993 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003994 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003995 throw new SecurityException("Can be called only by system UID");
3996 }
3997
3998 Preconditions.checkNotNull(account, "account cannot be null");
3999 Preconditions.checkNotNull(packageName, "packageName cannot be null");
4000 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
4001
4002 final int userId = userHandle.getIdentifier();
4003
4004 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
4005
4006 final int uid;
4007 try {
4008 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
4009 } catch (NameNotFoundException e) {
4010 Slog.e(TAG, "Unknown package " + packageName);
4011 return null;
4012 }
4013
4014 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
4015
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07004016 final long identity = Binder.clearCallingIdentity();
4017 try {
4018 return PendingIntent.getActivityAsUser(
4019 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
4020 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
4021 null, new UserHandle(userId)).getIntentSender();
4022 } finally {
4023 Binder.restoreCallingIdentity(identity);
4024 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004025 }
4026
4027 private Intent newRequestAccountAccessIntent(Account account, String packageName,
4028 int uid, RemoteCallback callback) {
4029 return newGrantCredentialsPermissionIntent(account, packageName, uid,
4030 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
4031 @Override
4032 public void onResult(Bundle value) throws RemoteException {
4033 handleAuthenticatorResponse(true);
4034 }
4035
4036 @Override
4037 public void onRequestContinued() {
4038 /* ignore */
4039 }
4040
4041 @Override
4042 public void onError(int errorCode, String errorMessage) throws RemoteException {
4043 handleAuthenticatorResponse(false);
4044 }
4045
4046 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
4047 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07004048 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004049 UserHandle.getUserHandleForUid(uid));
4050 if (callback != null) {
4051 Bundle result = new Bundle();
4052 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
4053 callback.sendResult(result);
4054 }
4055 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004056 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004057 }
4058
4059 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08004060 public boolean someUserHasAccount(@NonNull final Account account) {
4061 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
4062 throw new SecurityException("Only system can check for accounts across users");
4063 }
4064 final long token = Binder.clearCallingIdentity();
4065 try {
4066 AccountAndUser[] allAccounts = getAllAccounts();
4067 for (int i = allAccounts.length - 1; i >= 0; i--) {
4068 if (allAccounts[i].account.equals(account)) {
4069 return true;
4070 }
4071 }
4072 return false;
4073 } finally {
4074 Binder.restoreCallingIdentity(token);
4075 }
4076 }
4077
Fred Quintana33269202009-04-20 16:05:10 -07004078 private class GetAccountsByTypeAndFeatureSession extends Session {
4079 private final String[] mFeatures;
4080 private volatile Account[] mAccountsOfType = null;
4081 private volatile ArrayList<Account> mAccountsWithFeatures = null;
4082 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004083 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004084 private final String mPackageName;
sunjianf29d5492017-05-11 15:42:31 -07004085 private final boolean mIncludeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004086
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004087 public GetAccountsByTypeAndFeatureSession(
4088 UserAccounts accounts,
4089 IAccountManagerResponse response,
4090 String type,
4091 String[] features,
4092 int callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004093 String packageName,
4094 boolean includeManagedNotVisible) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004095 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004096 true /* stripAuthTokenFromResult */, null /* accountName */,
4097 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004098 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07004099 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004100 mPackageName = packageName;
sunjianf29d5492017-05-11 15:42:31 -07004101 mIncludeManagedNotVisible = includeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004102 }
4103
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004104 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004105 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004106 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
sunjianf29d5492017-05-11 15:42:31 -07004107 mCallingUid, mPackageName, mIncludeManagedNotVisible);
Fred Quintana33269202009-04-20 16:05:10 -07004108 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07004109 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07004110 mCurrentAccount = 0;
4111
4112 checkAccount();
4113 }
4114
4115 public void checkAccount() {
4116 if (mCurrentAccount >= mAccountsOfType.length) {
4117 sendResult();
4118 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07004119 }
Fred Quintana33269202009-04-20 16:05:10 -07004120
Fred Quintana29e94b82010-03-10 12:11:51 -08004121 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
4122 if (accountAuthenticator == null) {
4123 // It is possible that the authenticator has died, which is indicated by
4124 // mAuthenticator being set to null. If this happens then just abort.
4125 // There is no need to send back a result or error in this case since
4126 // that already happened when mAuthenticator was cleared.
4127 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4128 Log.v(TAG, "checkAccount: aborting session since we are no longer"
4129 + " connected to the authenticator, " + toDebugString());
4130 }
4131 return;
4132 }
Fred Quintana33269202009-04-20 16:05:10 -07004133 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08004134 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07004135 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004136 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07004137 }
4138 }
4139
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004140 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004141 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004142 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07004143 mNumResults++;
4144 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004145 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07004146 return;
4147 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004148 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07004149 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
4150 }
4151 mCurrentAccount++;
4152 checkAccount();
4153 }
4154
4155 public void sendResult() {
4156 IAccountManagerResponse response = getResponseAndClose();
4157 if (response != null) {
4158 try {
4159 Account[] accounts = new Account[mAccountsWithFeatures.size()];
4160 for (int i = 0; i < accounts.length; i++) {
4161 accounts[i] = mAccountsWithFeatures.get(i);
4162 }
Fred Quintana56285a62010-12-02 14:20:51 -08004163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4164 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
4165 + response);
4166 }
Fred Quintana33269202009-04-20 16:05:10 -07004167 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004168 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004169 response.onResult(result);
4170 } catch (RemoteException e) {
4171 // if the caller is dead then there is no one to care about remote exceptions
4172 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4173 Log.v(TAG, "failure while notifying response", e);
4174 }
4175 }
4176 }
4177 }
4178
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004179 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004180 protected String toDebugString(long now) {
4181 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4182 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4183 }
4184 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004185
Amith Yamasani04e0d262012-02-14 11:50:53 -08004186 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004187 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004188 * @hide
4189 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004190 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004191 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004192 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004193 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004194 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4195 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004196 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004197 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004198 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004199 long identityToken = clearCallingIdentity();
4200 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004201 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004202 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004203 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004204 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004205 opPackageName,
4206 visibleAccountTypes,
4207 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004208 } finally {
4209 restoreCallingIdentity(identityToken);
4210 }
4211 }
4212
Amith Yamasanif29f2362012-04-05 18:29:52 -07004213 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004214 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004215 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004216 * @hide
4217 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004218 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004219 public AccountAndUser[] getRunningAccounts() {
4220 final int[] runningUserIds;
4221 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004222 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004223 } catch (RemoteException e) {
4224 // Running in system_server; should never happen
4225 throw new RuntimeException(e);
4226 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004227 return getAccounts(runningUserIds);
4228 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004229
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004230 /**
4231 * Returns accounts for all users, ignores visibility values.
4232 *
4233 * @hide
4234 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004235 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004236 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004237 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004238 final int[] userIds = new int[users.size()];
4239 for (int i = 0; i < userIds.length; i++) {
4240 userIds[i] = users.get(i).id;
4241 }
4242 return getAccounts(userIds);
4243 }
4244
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004245 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004246 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004247 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004248 for (int userId : userIds) {
4249 UserAccounts userAccounts = getUserAccounts(userId);
4250 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004251 Account[] accounts = getAccountsFromCache(
4252 userAccounts,
4253 null /* type */,
4254 Binder.getCallingUid(),
4255 null /* packageName */,
4256 false /* include managed not visible*/);
4257 for (Account account : accounts) {
4258 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004259 }
4260 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004261
4262 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4263 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004264 }
4265
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004266 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004267 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004268 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004269 int callingUid = Binder.getCallingUid();
4270 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004271 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004272 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004273 }
4274
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004275 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004276 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004277 String type,
4278 int userId,
4279 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004280 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004281 String opPackageName,
4282 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004283 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004284 // Only allow the system process to read accounts of other users
4285 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004286 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004287 && mContext.checkCallingOrSelfPermission(
4288 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4289 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004290 throw new SecurityException("User " + UserHandle.getCallingUserId()
4291 + " trying to get account for " + userId);
4292 }
4293
Fred Quintana56285a62010-12-02 14:20:51 -08004294 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4295 Log.v(TAG, "getAccounts: accountType " + type
4296 + ", caller's uid " + Binder.getCallingUid()
4297 + ", pid " + Binder.getCallingPid());
4298 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004299
4300 // If the original calling app was using account choosing activity
4301 // provided by the framework or authenticator we'll passing in
4302 // the original caller's uid here, which is what should be used for filtering.
4303 List<String> managedTypes =
4304 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4305 if (packageUid != -1 &&
4306 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4307 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004308 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004309 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004310 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004311 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4312 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004313 if (visibleAccountTypes.isEmpty()
4314 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004315 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004316 } else if (visibleAccountTypes.contains(type)) {
4317 // Prune the list down to just the requested type.
4318 visibleAccountTypes = new ArrayList<>();
4319 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004320 } // else aggregate all the visible accounts (it won't matter if the
4321 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004322
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004323 long identityToken = clearCallingIdentity();
4324 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004325 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004326 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004327 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004328 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004329 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004330 visibleAccountTypes,
4331 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004332 } finally {
4333 restoreCallingIdentity(identityToken);
4334 }
4335 }
4336
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004337 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004338 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004339 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004340 int callingUid,
4341 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004342 List<String> visibleAccountTypes,
4343 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004344 ArrayList<Account> visibleAccounts = new ArrayList<>();
4345 for (String visibleType : visibleAccountTypes) {
4346 Account[] accountsForType = getAccountsFromCache(
4347 userAccounts, visibleType, callingUid, callingPackage,
4348 includeUserManagedNotVisible);
4349 if (accountsForType != null) {
4350 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004351 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004352 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004353 Account[] result = new Account[visibleAccounts.size()];
4354 for (int i = 0; i < visibleAccounts.size(); i++) {
4355 result[i] = visibleAccounts.get(i);
4356 }
4357 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004358 }
4359
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004360 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004361 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4362 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004363 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004364 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004365 for (Account account : accounts) {
4366 addSharedAccountAsUser(account, userId);
4367 }
4368 }
4369
4370 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004371 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004372 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004373 accounts.accountsDb.deleteSharedAccount(account);
4374 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004375 if (accountId < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07004376 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Amith Yamasani67df64b2012-12-14 12:09:36 -08004377 + ", skipping the DB insert failed");
4378 return false;
4379 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004380 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4381 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004382 return true;
4383 }
4384
4385 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004386 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4387 userId = handleIncomingUser(userId);
4388 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004389 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4390 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004391 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004392 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004393 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004394 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004395 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004396 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004397 }
4398 return r > 0;
4399 }
4400
4401 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004402 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004403 return removeSharedAccountAsUser(account, userId, getCallingUid());
4404 }
4405
4406 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004407 userId = handleIncomingUser(userId);
4408 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004409 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4410 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004411 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004412 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004413 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004414 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004415 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004416 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004417 }
4418
4419 @Override
4420 public Account[] getSharedAccountsAsUser(int userId) {
4421 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004422 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004423 synchronized (accounts.dbLock) {
4424 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4425 Account[] accountArray = new Account[accountList.size()];
4426 accountList.toArray(accountArray);
4427 return accountArray;
4428 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004429 }
4430
4431 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004432 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004433 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004434 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004435 }
4436
Amith Yamasani27db4682013-03-30 17:07:47 -07004437 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004438 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004439 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004440 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004441 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004442 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004443 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4444 + callingUid + " with uid=" + uid);
4445 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004446 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004447 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004448 }
4449
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004450 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004451 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004452 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4453 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004454 int callingUid = Binder.getCallingUid();
4455 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004456 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004457 int packageUid = -1;
4458 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004459 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4460 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004461 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004462 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004463 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004464 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004465 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4466 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004467 }
sunjiand62dc392017-06-01 12:05:59 -07004468 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) && type == null) {
4469 return getAccountsAsUserForPackage(type, userId,
4470 packageName, packageUid, opPackageName, false /* includeUserManagedNotVisible */);
4471 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004472 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004473 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004474 }
4475
sunjianf29d5492017-05-11 15:42:31 -07004476 private boolean needToStartChooseAccountActivity(Account[] accounts, String callingPackage) {
4477 if (accounts.length < 1) return false;
4478 if (accounts.length > 1) return true;
4479 Account account = accounts[0];
4480 UserAccounts userAccounts = getUserAccounts(UserHandle.getCallingUserId());
4481 int visibility = resolveAccountVisibility(account, callingPackage, userAccounts);
4482 if (visibility == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE) return true;
4483 return false;
4484 }
4485
4486 private void startChooseAccountActivityWithAccounts(
sunjianbdabd402017-06-06 17:54:07 -07004487 IAccountManagerResponse response, Account[] accounts, String callingPackage) {
sunjianf29d5492017-05-11 15:42:31 -07004488 Intent intent = new Intent(mContext, ChooseAccountActivity.class);
4489 intent.putExtra(AccountManager.KEY_ACCOUNTS, accounts);
4490 intent.putExtra(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE,
4491 new AccountManagerResponse(response));
sunjianbdabd402017-06-06 17:54:07 -07004492 intent.putExtra(AccountManager.KEY_ANDROID_PACKAGE_NAME, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004493
4494 mContext.startActivityAsUser(intent, UserHandle.of(UserHandle.getCallingUserId()));
4495 }
4496
4497 private void handleGetAccountsResult(
4498 IAccountManagerResponse response,
4499 Account[] accounts,
4500 String callingPackage) {
4501
4502 if (needToStartChooseAccountActivity(accounts, callingPackage)) {
sunjianbdabd402017-06-06 17:54:07 -07004503 startChooseAccountActivityWithAccounts(response, accounts, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004504 return;
4505 }
4506 if (accounts.length == 1) {
4507 Bundle bundle = new Bundle();
4508 bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accounts[0].name);
4509 bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accounts[0].type);
4510 onResult(response, bundle);
4511 return;
4512 }
4513 // No qualified account exists, return an empty Bundle.
4514 onResult(response, new Bundle());
4515 }
4516
4517 @Override
4518 public void getAccountByTypeAndFeatures(
4519 IAccountManagerResponse response,
4520 String accountType,
4521 String[] features,
4522 String opPackageName) {
4523
4524 int callingUid = Binder.getCallingUid();
4525 mAppOpsManager.checkPackage(callingUid, opPackageName);
4526 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4527 Log.v(TAG, "getAccount: accountType " + accountType
4528 + ", response " + response
4529 + ", features " + Arrays.toString(features)
4530 + ", caller's uid " + callingUid
4531 + ", pid " + Binder.getCallingPid());
4532 }
4533 if (response == null) throw new IllegalArgumentException("response is null");
4534 if (accountType == null) throw new IllegalArgumentException("accountType is null");
4535
4536 int userId = UserHandle.getCallingUserId();
4537
4538 long identityToken = clearCallingIdentity();
4539 try {
4540 UserAccounts userAccounts = getUserAccounts(userId);
4541 if (ArrayUtils.isEmpty(features)) {
4542 Account[] accountsWithManagedNotVisible = getAccountsFromCache(
4543 userAccounts, accountType, callingUid, opPackageName,
4544 true /* include managed not visible */);
4545 handleGetAccountsResult(
4546 response, accountsWithManagedNotVisible, opPackageName);
4547 return;
4548 }
4549
4550 IAccountManagerResponse retrieveAccountsResponse =
4551 new IAccountManagerResponse.Stub() {
4552 @Override
4553 public void onResult(Bundle value) throws RemoteException {
4554 Parcelable[] parcelables = value.getParcelableArray(
4555 AccountManager.KEY_ACCOUNTS);
4556 Account[] accounts = new Account[parcelables.length];
4557 for (int i = 0; i < parcelables.length; i++) {
4558 accounts[i] = (Account) parcelables[i];
4559 }
4560 handleGetAccountsResult(
4561 response, accounts, opPackageName);
4562 }
4563
4564 @Override
4565 public void onError(int errorCode, String errorMessage)
4566 throws RemoteException {
4567 // Will not be called in this case.
4568 }
4569 };
4570 new GetAccountsByTypeAndFeatureSession(
4571 userAccounts,
4572 retrieveAccountsResponse,
4573 accountType,
4574 features,
4575 callingUid,
4576 opPackageName,
4577 true /* include managed not visible */).bind();
4578 } finally {
4579 restoreCallingIdentity(identityToken);
4580 }
4581 }
4582
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004583 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004584 public void getAccountsByFeatures(
4585 IAccountManagerResponse response,
4586 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004587 String[] features,
4588 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004589 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004590 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004591 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4592 Log.v(TAG, "getAccounts: accountType " + type
4593 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004594 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004595 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004596 + ", pid " + Binder.getCallingPid());
4597 }
Fred Quintana382601f2010-03-25 12:25:10 -07004598 if (response == null) throw new IllegalArgumentException("response is null");
4599 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004600 int userId = UserHandle.getCallingUserId();
4601
Svetoslavf3f02ac2015-09-08 14:36:35 -07004602 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4603 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004604 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004605 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004606 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004607 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004608 try {
4609 response.onResult(result);
4610 } catch (RemoteException e) {
4611 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4612 }
4613 return;
4614 }
sunjianf29d5492017-05-11 15:42:31 -07004615
Fred Quintana33269202009-04-20 16:05:10 -07004616 long identityToken = clearCallingIdentity();
4617 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004618 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004619 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004620 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4621 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004622 Bundle result = new Bundle();
4623 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4624 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004625 return;
4626 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004627 new GetAccountsByTypeAndFeatureSession(
4628 userAccounts,
4629 response,
4630 type,
4631 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004632 callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004633 opPackageName,
4634 false /* include managed not visible */).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004635 } finally {
4636 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004637 }
4638 }
4639
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004640 @Override
4641 public void onAccountAccessed(String token) throws RemoteException {
4642 final int uid = Binder.getCallingUid();
4643 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4644 return;
4645 }
4646 final int userId = UserHandle.getCallingUserId();
4647 final long identity = Binder.clearCallingIdentity();
4648 try {
4649 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4650 if (Objects.equals(account.getAccessId(), token)) {
4651 // An app just accessed the account. At this point it knows about
4652 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004653 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004654 if (!hasAccountAccess(account, null, uid)) {
4655 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4656 uid, true);
4657 }
4658 }
4659 }
4660 } finally {
4661 Binder.restoreCallingIdentity(identity);
4662 }
4663 }
4664
Hongming Jin8e2bfc12018-05-30 11:01:06 -07004665 @Override
4666 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4667 FileDescriptor err, String[] args, ShellCallback callback,
4668 ResultReceiver resultReceiver) {
4669 new AccountManagerServiceShellCommand(this).exec(this, in, out, err, args,
4670 callback, resultReceiver);
4671 }
4672
Fred Quintanaa698f422009-04-08 19:14:54 -07004673 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004674 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004675 IAccountManagerResponse mResponse;
4676 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004677 final boolean mExpectActivityLaunch;
4678 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004679 final String mAccountName;
4680 // Indicates if we need to add auth details(like last credential time)
4681 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004682 // If set, we need to update the last authenticated time. This is
4683 // currently
4684 // used on
4685 // successful confirming credentials.
4686 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004687
Fred Quintana33269202009-04-20 16:05:10 -07004688 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004689 private int mNumRequestContinued = 0;
4690 private int mNumErrors = 0;
4691
Fred Quintana60307342009-03-24 22:48:12 -07004692 IAccountAuthenticator mAuthenticator = null;
4693
Fred Quintana8570f742010-02-18 10:32:54 -08004694 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004695 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004696
Amith Yamasani04e0d262012-02-14 11:50:53 -08004697 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004698 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4699 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004700 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4701 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4702 }
4703
4704 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4705 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4706 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004707 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004708 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004709 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004710 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004711 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004712 mResponse = response;
4713 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004714 mExpectActivityLaunch = expectActivityLaunch;
4715 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004716 mAccountName = accountName;
4717 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004718 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004719
Fred Quintanaa698f422009-04-08 19:14:54 -07004720 synchronized (mSessions) {
4721 mSessions.put(toString(), this);
4722 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004723 if (response != null) {
4724 try {
4725 response.asBinder().linkToDeath(this, 0 /* flags */);
4726 } catch (RemoteException e) {
4727 mResponse = null;
4728 binderDied();
4729 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004730 }
Fred Quintana60307342009-03-24 22:48:12 -07004731 }
4732
Fred Quintanaa698f422009-04-08 19:14:54 -07004733 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004734 if (mResponse == null) {
4735 // this session has already been closed
4736 return null;
4737 }
Fred Quintana60307342009-03-24 22:48:12 -07004738 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004739 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004740 return response;
4741 }
4742
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004743 /**
4744 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4745 * security policy.
4746 *
4747 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004748 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004749 * supplied entries in the system Settings app.
4750 */
tiansiminga8868bf2017-09-20 13:59:13 +08004751 protected boolean checkKeyIntent(int authUid, Intent intent) {
Jeff Sharkeyd722e782017-06-12 17:33:07 -06004752 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION
4753 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
4754 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4755 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION));
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004756 long bid = Binder.clearCallingIdentity();
4757 try {
4758 PackageManager pm = mContext.getPackageManager();
4759 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
tiansiminga8868bf2017-09-20 13:59:13 +08004760 if (resolveInfo == null) {
4761 return false;
4762 }
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004763 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4764 int targetUid = targetActivityInfo.applicationInfo.uid;
Dan Cashman303c4bb2018-04-10 07:41:16 -07004765 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004766 if (!isExportedSystemActivity(targetActivityInfo)
Dan Cashman303c4bb2018-04-10 07:41:16 -07004767 && !pmi.hasSignatureCapability(
4768 targetUid, authUid,
4769 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004770 String pkgName = targetActivityInfo.packageName;
4771 String activityName = targetActivityInfo.name;
4772 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4773 + "does not share a signature with the supplying authenticator (%s).";
tiansiminga8868bf2017-09-20 13:59:13 +08004774 Log.e(TAG, String.format(tmpl, activityName, pkgName, mAccountType));
4775 return false;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004776 }
tiansiminga8868bf2017-09-20 13:59:13 +08004777 return true;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004778 } finally {
4779 Binder.restoreCallingIdentity(bid);
4780 }
4781 }
4782
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004783 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4784 String className = activityInfo.name;
4785 return "android".equals(activityInfo.packageName) &&
4786 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4787 || CantAddAccountActivity.class.getName().equals(className));
4788 }
4789
Fred Quintanaa698f422009-04-08 19:14:54 -07004790 private void close() {
4791 synchronized (mSessions) {
4792 if (mSessions.remove(toString()) == null) {
4793 // the session was already closed, so bail out now
4794 return;
4795 }
4796 }
4797 if (mResponse != null) {
4798 // stop listening for response deaths
4799 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4800
4801 // clear this so that we don't accidentally send any further results
4802 mResponse = null;
4803 }
4804 cancelTimeout();
4805 unbind();
4806 }
4807
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004808 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004809 public void binderDied() {
4810 mResponse = null;
4811 close();
4812 }
4813
4814 protected String toDebugString() {
4815 return toDebugString(SystemClock.elapsedRealtime());
4816 }
4817
4818 protected String toDebugString(long now) {
4819 return "Session: expectLaunch " + mExpectActivityLaunch
4820 + ", connected " + (mAuthenticator != null)
4821 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4822 + "/" + mNumErrors + ")"
4823 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4824 }
4825
Fred Quintana60307342009-03-24 22:48:12 -07004826 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004827 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4828 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4829 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004830 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004831 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004832 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004833 }
4834 }
4835
4836 private void unbind() {
4837 if (mAuthenticator != null) {
4838 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004839 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004840 }
4841 }
4842
Fred Quintana60307342009-03-24 22:48:12 -07004843 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004844 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004845 }
4846
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004847 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004848 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004849 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004850 try {
4851 run();
4852 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004853 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004854 "remote exception");
4855 }
Fred Quintana60307342009-03-24 22:48:12 -07004856 }
4857
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004858 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004859 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004860 mAuthenticator = null;
4861 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004862 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004863 try {
4864 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4865 "disconnected");
4866 } catch (RemoteException e) {
4867 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4868 Log.v(TAG, "Session.onServiceDisconnected: "
4869 + "caught RemoteException while responding", e);
4870 }
4871 }
Fred Quintana60307342009-03-24 22:48:12 -07004872 }
4873 }
4874
Fred Quintanab839afc2009-10-14 15:57:28 -07004875 public abstract void run() throws RemoteException;
4876
Fred Quintana60307342009-03-24 22:48:12 -07004877 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004878 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004879 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004880 try {
4881 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4882 "timeout");
4883 } catch (RemoteException e) {
4884 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4885 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4886 e);
4887 }
4888 }
Fred Quintana60307342009-03-24 22:48:12 -07004889 }
4890 }
4891
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004892 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004893 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004894 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004895 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004896 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004897 if (result != null) {
4898 boolean isSuccessfulConfirmCreds = result.getBoolean(
4899 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004900 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004901 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4902 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004903 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004904 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4905 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004906 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004907 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004908 if (needUpdate || mAuthDetailsRequired) {
4909 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4910 if (needUpdate && accountPresent) {
4911 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4912 }
4913 if (mAuthDetailsRequired) {
4914 long lastAuthenticatedTime = -1;
4915 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004916 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004917 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004918 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004919 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004920 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004921 lastAuthenticatedTime);
4922 }
4923 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004924 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004925 if (result != null
4926 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
tiansiminga8868bf2017-09-20 13:59:13 +08004927 if (!checkKeyIntent(
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004928 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08004929 intent)) {
4930 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
4931 "invalid intent in bundle returned");
4932 return;
4933 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004934 }
4935 if (result != null
4936 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004937 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4938 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004939 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4940 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004941 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4942 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004943 }
Fred Quintana60307342009-03-24 22:48:12 -07004944 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004945 IAccountManagerResponse response;
4946 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004947 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004948 response = mResponse;
4949 } else {
4950 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004951 }
Fred Quintana60307342009-03-24 22:48:12 -07004952 if (response != null) {
4953 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004954 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004955 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4956 Log.v(TAG, getClass().getSimpleName()
4957 + " calling onError() on response " + response);
4958 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004959 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004960 "null bundle returned");
4961 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004962 if (mStripAuthTokenFromResult) {
4963 result.remove(AccountManager.KEY_AUTHTOKEN);
4964 }
Fred Quintana56285a62010-12-02 14:20:51 -08004965 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4966 Log.v(TAG, getClass().getSimpleName()
4967 + " calling onResult() on response " + response);
4968 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004969 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4970 (intent == null)) {
4971 // All AccountManager error codes are greater than 0
4972 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4973 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4974 } else {
4975 response.onResult(result);
4976 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004977 }
Fred Quintana60307342009-03-24 22:48:12 -07004978 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004979 // if the caller is dead then there is no one to care about remote exceptions
4980 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4981 Log.v(TAG, "failure while notifying response", e);
4982 }
Fred Quintana60307342009-03-24 22:48:12 -07004983 }
4984 }
4985 }
Fred Quintana60307342009-03-24 22:48:12 -07004986
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004987 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004988 public void onRequestContinued() {
4989 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004990 }
4991
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004992 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004993 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004994 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004995 IAccountManagerResponse response = getResponseAndClose();
4996 if (response != null) {
4997 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004998 Log.v(TAG, getClass().getSimpleName()
4999 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07005000 }
5001 try {
5002 response.onError(errorCode, errorMessage);
5003 } catch (RemoteException e) {
5004 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5005 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
5006 }
5007 }
5008 } else {
5009 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5010 Log.v(TAG, "Session.onError: already closed");
5011 }
Fred Quintana60307342009-03-24 22:48:12 -07005012 }
5013 }
Fred Quintanab839afc2009-10-14 15:57:28 -07005014
5015 /**
5016 * find the component name for the authenticator and initiate a bind
5017 * if no authenticator or the bind fails then return false, otherwise return true
5018 */
5019 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005020 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
5021 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
5022 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07005023 if (authenticatorInfo == null) {
5024 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5025 Log.v(TAG, "there is no authenticator for " + authenticatorType
5026 + ", bailing out");
5027 }
5028 return false;
5029 }
5030
Jeff Sharkeyce18c812016-04-27 16:00:41 -06005031 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06005032 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07005033 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
5034 + " which isn't encryption aware");
5035 return false;
5036 }
5037
Fred Quintanab839afc2009-10-14 15:57:28 -07005038 Intent intent = new Intent();
5039 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
5040 intent.setComponent(authenticatorInfo.componentName);
5041 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5042 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
5043 }
Hongming Jin8e2bfc12018-05-30 11:01:06 -07005044 int flags = Context.BIND_AUTO_CREATE;
5045 if (mAuthenticatorCache.getBindInstantServiceAllowed(mAccounts.userId)) {
5046 flags |= Context.BIND_ALLOW_INSTANT;
5047 }
5048 if (!mContext.bindServiceAsUser(intent, this, flags, UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07005049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5050 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
5051 }
5052 return false;
5053 }
5054
Fred Quintanab839afc2009-10-14 15:57:28 -07005055 return true;
5056 }
Fred Quintana60307342009-03-24 22:48:12 -07005057 }
5058
Svet Ganov5d09c992016-09-07 09:57:41 -07005059 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07005060 MessageHandler(Looper looper) {
5061 super(looper);
5062 }
Costin Manolache3348f142009-09-29 18:58:36 -07005063
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07005064 @Override
Fred Quintana60307342009-03-24 22:48:12 -07005065 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07005066 switch (msg.what) {
5067 case MESSAGE_TIMED_OUT:
5068 Session session = (Session)msg.obj;
5069 session.onTimedOut();
5070 break;
5071
Amith Yamasani5be347b2013-03-31 17:44:31 -07005072 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00005073 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07005074 break;
5075
Fred Quintana60307342009-03-24 22:48:12 -07005076 default:
5077 throw new IllegalStateException("unhandled message: " + msg.what);
5078 }
5079 }
5080 }
5081
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005082 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005083 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005084 }
5085
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005086 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005087 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005088 }
5089
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005090 /*
5091 * This function receives an opened writable database.
5092 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005093 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005094 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005095 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005096 }
5097
5098 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005099 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005100 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005101 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005102 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005103
5104 class LogRecordTask implements Runnable {
5105 private final String action;
5106 private final String tableName;
5107 private final long accountId;
5108 private final UserAccounts userAccount;
5109 private final int callingUid;
5110 private final long userDebugDbInsertionPoint;
5111
5112 LogRecordTask(final String action,
5113 final String tableName,
5114 final long accountId,
5115 final UserAccounts userAccount,
5116 final int callingUid,
5117 final long userDebugDbInsertionPoint) {
5118 this.action = action;
5119 this.tableName = tableName;
5120 this.accountId = accountId;
5121 this.userAccount = userAccount;
5122 this.callingUid = callingUid;
5123 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
5124 }
5125
Andrew Scullc7770d62017-05-22 17:49:58 +01005126 @Override
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005127 public void run() {
Dmitry Dementyev47443192018-10-24 13:31:59 -07005128 synchronized (userAccount.accountsDb.mDebugStatementLock) {
5129 SQLiteStatement logStatement = userAccount.accountsDb.getStatementForLogging();
5130 if (logStatement == null) {
5131 return; // Can't log.
5132 }
5133 logStatement.bindLong(1, accountId);
5134 logStatement.bindString(2, action);
5135 logStatement.bindString(3, mDateFormat.format(new Date()));
5136 logStatement.bindLong(4, callingUid);
5137 logStatement.bindString(5, tableName);
5138 logStatement.bindLong(6, userDebugDbInsertionPoint);
5139 try {
5140 logStatement.execute();
5141 } catch (IllegalStateException e) {
5142 // Guard against crash, DB can already be closed
5143 // since this statement is executed on a handler thread
5144 Slog.w(TAG, "Failed to insert a log record. accountId=" + accountId
5145 + " action=" + action + " tableName=" + tableName + " Error: " + e);
5146 } finally {
5147 logStatement.clearBindings();
5148 }
Tetsutoki Shiozawabe2d96a2017-10-24 18:44:00 +09005149 }
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005150 }
5151 }
Dmitry Dementyev47443192018-10-24 13:31:59 -07005152 long insertionPoint = userAccount.accountsDb.reserveDebugDbInsertionPoint();
5153 if (insertionPoint != -1) {
5154 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
5155 callingUid, insertionPoint);
5156 mHandler.post(logTask);
5157 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005158 }
5159
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005160 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005161 return asBinder();
5162 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005163
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005164 /**
5165 * Searches array of arguments for the specified string
5166 * @param args array of argument strings
5167 * @param value value to search for
5168 * @return true if the value is contained in the array
5169 */
5170 private static boolean scanArgs(String[] args, String value) {
5171 if (args != null) {
5172 for (String arg : args) {
5173 if (value.equals(arg)) {
5174 return true;
5175 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005176 }
5177 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005178 return false;
5179 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005180
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005181 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005182 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005183 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005184 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005185 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005186
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005187 final List<UserInfo> users = getUserManager().getUsers();
5188 for (UserInfo user : users) {
5189 ipw.println("User " + user + ":");
5190 ipw.increaseIndent();
5191 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5192 ipw.println();
5193 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005194 }
5195 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005196
Amith Yamasani04e0d262012-02-14 11:50:53 -08005197 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5198 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005199 if (isCheckinRequest) {
5200 // This is a checkin request. *Only* upload the account types and the count of
5201 // each.
5202 synchronized (userAccounts.dbLock) {
5203 userAccounts.accountsDb.dumpDeAccountsTable(fout);
5204 }
5205 } else {
5206 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
5207 Process.SYSTEM_UID, null /* packageName */, false);
5208 fout.println("Accounts: " + accounts.length);
5209 for (Account account : accounts) {
Makoto Onukib9425222019-01-23 11:35:43 -08005210 fout.println(" " + account.toString());
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005211 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005212
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005213 // Add debug information.
5214 fout.println();
5215 synchronized (userAccounts.dbLock) {
5216 userAccounts.accountsDb.dumpDebugTable(fout);
5217 }
5218 fout.println();
5219 synchronized (mSessions) {
5220 final long now = SystemClock.elapsedRealtime();
5221 fout.println("Active Sessions: " + mSessions.size());
5222 for (Session session : mSessions.values()) {
5223 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005224 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005225 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005226
5227 fout.println();
5228 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Tony Mak6d14d772017-07-13 17:49:46 +08005229
5230 boolean isUserUnlocked;
5231 synchronized (mUsers) {
5232 isUserUnlocked = isLocalUnlockedUser(userAccounts.userId);
5233 }
5234 // Following logs are printed only when user is unlocked.
5235 if (!isUserUnlocked) {
5236 return;
5237 }
5238 fout.println();
5239 synchronized (userAccounts.dbLock) {
5240 Map<Account, Map<String, Integer>> allVisibilityValues =
5241 userAccounts.accountsDb.findAllVisibilityValues();
5242 fout.println("Account visibility:");
5243 for (Account account : allVisibilityValues.keySet()) {
5244 fout.println(" " + account.name);
5245 Map<String, Integer> visibilities = allVisibilityValues.get(account);
5246 for (Entry<String, Integer> entry : visibilities.entrySet()) {
5247 fout.println(" " + entry.getKey() + ", " + entry.getValue());
5248 }
5249 }
5250 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005251 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005252 }
5253
Amith Yamasani04e0d262012-02-14 11:50:53 -08005254 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005255 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005256 long identityToken = clearCallingIdentity();
5257 try {
5258 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5259 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5260 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005261
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005262 if (intent.getComponent() != null &&
5263 GrantCredentialsPermissionActivity.class.getName().equals(
5264 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005265 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005266 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005267 Context contextForUser = getContextForUser(new UserHandle(userId));
Chris Wren717a8812017-03-31 15:34:39 -04005268 final NotificationId id = getSigninRequiredNotificationId(accounts, account);
5269 intent.addCategory(id.mTag);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005270
Fred Quintana33f889a2009-09-14 17:31:26 -07005271 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005272 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05005273 Notification n =
5274 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005275 .setWhen(0)
5276 .setSmallIcon(android.R.drawable.stat_sys_warning)
5277 .setColor(contextForUser.getColor(
5278 com.android.internal.R.color.system_notification_accent_color))
5279 .setContentTitle(String.format(notificationTitleFormat, account.name))
5280 .setContentText(message)
5281 .setContentIntent(PendingIntent.getActivityAsUser(
5282 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005283 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005284 .build();
Chris Wren717a8812017-03-31 15:34:39 -04005285 installNotification(id, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005286 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005287 } finally {
5288 restoreCallingIdentity(identityToken);
5289 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005290 }
5291
Chris Wren717a8812017-03-31 15:34:39 -04005292 private void installNotification(NotificationId id, final Notification notification,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005293 String packageName, int userId) {
5294 final long token = clearCallingIdentity();
5295 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005296 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005297 try {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04005298 // The calling uid must match either the package or op package, so use an op
5299 // package that matches the cleared calling identity.
5300 notificationManager.enqueueNotificationWithTag(packageName, "android",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04005301 id.mTag, id.mId, notification, userId);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005302 } catch (RemoteException e) {
5303 /* ignore - local call */
5304 }
5305 } finally {
5306 Binder.restoreCallingIdentity(token);
5307 }
Fred Quintana56285a62010-12-02 14:20:51 -08005308 }
5309
Chris Wren717a8812017-03-31 15:34:39 -04005310 private void cancelNotification(NotificationId id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005311 cancelNotification(id, mContext.getPackageName(), user);
5312 }
5313
Chris Wren717a8812017-03-31 15:34:39 -04005314 private void cancelNotification(NotificationId id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005315 long identityToken = clearCallingIdentity();
5316 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005317 INotificationManager service = mInjector.getNotificationManager();
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005318 service.cancelNotificationWithTag(
5319 packageName, "android", id.mTag, id.mId, user.getIdentifier());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005320 } catch (RemoteException e) {
5321 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005322 } finally {
5323 restoreCallingIdentity(identityToken);
5324 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005325 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005326
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005327 private boolean isPermittedForPackage(String packageName, int userId, String... permissions) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005328 final long identity = Binder.clearCallingIdentity();
5329 try {
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005330 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005331 IPackageManager pm = ActivityThread.getPackageManager();
5332 for (String perm : permissions) {
5333 if (pm.checkPermission(perm, packageName, userId)
5334 == PackageManager.PERMISSION_GRANTED) {
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005335 // Checks runtime permission revocation.
5336 final int opCode = AppOpsManager.permissionToOpCode(perm);
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005337 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.checkOpNoThrow(
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005338 opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
5339 return true;
5340 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005341 }
5342 }
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005343 } catch (NameNotFoundException | RemoteException e) {
5344 // Assume permission is not granted if an error accrued.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005345 } finally {
5346 Binder.restoreCallingIdentity(identity);
5347 }
5348 return false;
5349 }
5350
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005351 /**
5352 * Checks that package has at least one of given permissions and makes note of app
5353 * performing the action.
5354 */
5355 private boolean checkPermissionAndNote(String opPackageName, int callingUid,
5356 String... permissions) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005357 for (String perm : permissions) {
5358 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5359 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5360 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5361 }
5362 final int opCode = AppOpsManager.permissionToOpCode(perm);
Tony Mak58f28152017-09-20 21:23:48 +01005363 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOpNoThrow(
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005364 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5365 return true;
5366 }
5367 }
5368 }
5369 return false;
5370 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005371
Amith Yamasani67df64b2012-12-14 12:09:36 -08005372 private int handleIncomingUser(int userId) {
5373 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005374 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005375 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5376 } catch (RemoteException re) {
5377 // Shouldn't happen, local.
5378 }
5379 return userId;
5380 }
5381
Christopher Tateccbf84f2013-05-08 15:25:41 -07005382 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005383 String[] packages;
5384 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005385 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005386 packages = mPackageManager.getPackagesForUid(callingUid);
sunjian9ae597b62017-08-14 15:45:04 -07005387 if (packages == null) {
5388 Log.d(TAG, "No packages for callingUid " + callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005389 return false;
5390 }
sunjian9ae597b62017-08-14 15:45:04 -07005391 for (String name : packages) {
5392 try {
5393 PackageInfo packageInfo =
5394 mPackageManager.getPackageInfo(name, 0 /* flags */);
5395 if (packageInfo != null
5396 && (packageInfo.applicationInfo.privateFlags
5397 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5398 return true;
5399 }
5400 } catch (PackageManager.NameNotFoundException e) {
5401 Log.d(TAG, "Package not found " + e.getMessage());
5402 }
5403 }
5404 } finally {
5405 Binder.restoreCallingIdentity(identityToken);
Fred Quintana7be59642009-08-24 18:29:25 -07005406 }
5407 return false;
5408 }
5409
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005410 private boolean permissionIsGranted(
5411 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005412 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5413 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5414 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5415 }
5416 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005417 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005418
5419 if (isPrivileged(callerUid)) {
5420 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5421 Log.v(TAG, "Access to " + account + " granted calling uid "
5422 + callerUid + " privileged");
5423 }
5424 return true;
5425 }
5426 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5427 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5428 Log.v(TAG, "Access to " + account + " granted calling uid "
5429 + callerUid + " manages the account");
5430 }
5431 return true;
5432 }
5433 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5434 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5435 Log.v(TAG, "Access to " + account + " granted calling uid "
5436 + callerUid + " user granted access");
5437 }
5438 return true;
5439 }
5440
5441 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5442 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5443 }
5444
5445 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005446 }
5447
Svetoslavf3f02ac2015-09-08 14:36:35 -07005448 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5449 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005450 if (accountType == null) {
5451 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005452 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005453 return getTypesVisibleToCaller(callingUid, userId,
5454 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005455 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005456 }
5457
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005458 // Method checks visibility for applications targeing API level below {@link
5459 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005460 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005461 private boolean checkGetAccountsPermission(String packageName, int userId) {
5462 return isPermittedForPackage(packageName, userId, Manifest.permission.GET_ACCOUNTS,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005463 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5464 }
5465
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005466 private boolean checkReadContactsPermission(String packageName, int userId) {
5467 return isPermittedForPackage(packageName, userId, Manifest.permission.READ_CONTACTS);
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005468 }
5469
5470 // Heuristic to check that account type may be associated with some contacts data and
5471 // therefore READ_CONTACTS permission grants the access to account by default.
5472 private boolean accountTypeManagesContacts(String accountType, int userId) {
5473 if (accountType == null) {
5474 return false;
5475 }
5476 long identityToken = Binder.clearCallingIdentity();
5477 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5478 try {
5479 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5480 } finally {
5481 Binder.restoreCallingIdentity(identityToken);
5482 }
5483 // Check contacts related permissions for authenticator.
5484 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5485 : serviceInfos) {
5486 if (accountType.equals(serviceInfo.type.type)) {
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005487 return isPermittedForPackage(serviceInfo.type.packageName, userId,
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005488 Manifest.permission.WRITE_CONTACTS);
5489 }
5490 }
5491 return false;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005492 }
5493
5494 /**
5495 * Method checks package uid and signature with Authenticator which manages accountType.
5496 *
5497 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5498 * SIGNATURE_CHECK_MISMATCH otherwise.
5499 */
5500 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5501 if (accountType == null) {
5502 return SIGNATURE_CHECK_MISMATCH;
5503 }
5504
5505 long identityToken = Binder.clearCallingIdentity();
5506 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5507 try {
5508 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5509 } finally {
5510 Binder.restoreCallingIdentity(identityToken);
5511 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005512 // Check for signature match with Authenticator.LocalServices.getService(PackageManagerInternal.class);
5513 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005514 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5515 : serviceInfos) {
5516 if (accountType.equals(serviceInfo.type.type)) {
5517 if (serviceInfo.uid == callingUid) {
5518 return SIGNATURE_CHECK_UID_MATCH;
5519 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005520 if (pmi.hasSignatureCapability(
5521 serviceInfo.uid, callingUid,
5522 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005523 return SIGNATURE_CHECK_MATCH;
5524 }
5525 }
5526 }
5527 return SIGNATURE_CHECK_MISMATCH;
5528 }
5529
5530 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005531 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5532 if (accountType == null) {
5533 return false;
5534 } else {
5535 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5536 }
5537 }
5538
Svetoslavf3f02ac2015-09-08 14:36:35 -07005539 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5540 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005541 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005542 }
5543
5544 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005545 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005546 }
5547
5548 private List<String> getTypesForCaller(
5549 int callingUid, int userId, boolean isOtherwisePermitted) {
5550 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005551 long identityToken = Binder.clearCallingIdentity();
5552 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5553 try {
5554 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5555 } finally {
5556 Binder.restoreCallingIdentity(identityToken);
5557 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005558
5559 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005560 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005561 serviceInfos) {
Dan Cashman303c4bb2018-04-10 07:41:16 -07005562 if (isOtherwisePermitted || pmi.hasSignatureCapability(
5563 serviceInfo.uid, callingUid,
5564 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005565 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005566 }
5567 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005568 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005569 }
5570
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005571 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5572 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5573 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5574 if (account.name.equals(accountName)) {
5575 return true;
5576 }
5577 }
5578 }
5579 return false;
5580 }
5581
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005582 private static void checkManageUsersPermission(String message) {
5583 if (ActivityManager.checkComponentPermission(
5584 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5585 != PackageManager.PERMISSION_GRANTED) {
5586 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5587 }
5588 }
5589
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005590 private static void checkManageOrCreateUsersPermission(String message) {
5591 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5592 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5593 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5594 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5595 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5596 + message);
5597 }
5598 }
5599
Amith Yamasani04e0d262012-02-14 11:50:53 -08005600 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5601 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005602 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005603 return true;
5604 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005605 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005606 synchronized (accounts.dbLock) {
5607 synchronized (accounts.cacheLock) {
5608 long grantsCount;
5609 if (authTokenType != null) {
5610 grantsCount = accounts.accountsDb
5611 .findMatchingGrantsCount(callerUid, authTokenType, account);
5612 } else {
5613 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5614 account);
5615 }
5616 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005617
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005618 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5619 // TODO: Skip this check when running automated tests. Replace this
5620 // with a more general solution.
Hui Yu139c2482018-08-10 15:37:51 -07005621 Log.d(TAG, "no credentials permission for usage of "
5622 + account.toSafeString() + ", "
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005623 + authTokenType + " by uid " + callerUid
5624 + " but ignoring since device is in test harness.");
5625 return true;
5626 }
5627 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005628 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005629 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005630 }
5631
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005632 private boolean isSystemUid(int callingUid) {
5633 String[] packages = null;
5634 long ident = Binder.clearCallingIdentity();
5635 try {
5636 packages = mPackageManager.getPackagesForUid(callingUid);
Alex Chau81a47cd2018-01-02 16:49:14 +00005637 if (packages != null) {
5638 for (String name : packages) {
5639 try {
5640 PackageInfo packageInfo =
5641 mPackageManager.getPackageInfo(name, 0 /* flags */);
5642 if (packageInfo != null
5643 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5644 != 0) {
5645 return true;
5646 }
5647 } catch (NameNotFoundException e) {
5648 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5649 }
5650 }
5651 } else {
5652 Log.w(TAG, "No known packages with uid " + callingUid);
5653 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005654 } finally {
5655 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005656 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005657 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005658 }
5659
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005660 /** Succeeds if any of the specified permissions are granted. */
5661 private void checkReadAccountsPermitted(
5662 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005663 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005664 int userId,
5665 String opPackageName) {
5666 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005667 String msg = String.format(
5668 "caller uid %s cannot access %s accounts",
5669 callingUid,
5670 accountType);
5671 Log.w(TAG, " " + msg);
5672 throw new SecurityException(msg);
5673 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005674 }
5675
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005676 private boolean canUserModifyAccounts(int userId, int callingUid) {
5677 // the managing app can always modify accounts
5678 if (isProfileOwner(callingUid)) {
5679 return true;
5680 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005681 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5682 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5683 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005684 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005685 return true;
5686 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005687
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005688 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5689 // the managing app can always modify accounts
5690 if (isProfileOwner(callingUid)) {
5691 return true;
5692 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005693 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5694 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005695 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005696 if (typesArray == null) {
5697 return true;
5698 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005699 for (String forbiddenType : typesArray) {
5700 if (forbiddenType.equals(accountType)) {
5701 return false;
5702 }
5703 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005704 return true;
5705 }
5706
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005707 private boolean isProfileOwner(int uid) {
5708 final DevicePolicyManagerInternal dpmi =
5709 LocalServices.getService(DevicePolicyManagerInternal.class);
5710 return (dpmi != null)
5711 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5712 }
5713
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005714 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005715 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5716 throws RemoteException {
5717 final int callingUid = getCallingUid();
5718
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005719 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005720 throw new SecurityException();
5721 }
5722
5723 if (value) {
5724 grantAppPermission(account, authTokenType, uid);
5725 } else {
5726 revokeAppPermission(account, authTokenType, uid);
5727 }
5728 }
5729
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005730 /**
5731 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5732 * <p>
5733 * Although this is public it can only be accessed via the AccountManagerService object
5734 * which is in the system. This means we don't need to protect it with permissions.
5735 * @hide
5736 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005737 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005738 if (account == null || authTokenType == null) {
5739 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005740 return;
5741 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005742 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005743 synchronized (accounts.dbLock) {
5744 synchronized (accounts.cacheLock) {
5745 long accountId = accounts.accountsDb.findDeAccountId(account);
5746 if (accountId >= 0) {
5747 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5748 }
5749 cancelNotification(
5750 getCredentialPermissionNotificationId(account, authTokenType, uid),
5751 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005752
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005753 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5754 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005755 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005756
5757 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5758 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5759 : mAppPermissionChangeListeners) {
5760 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5761 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005762 }
5763
5764 /**
5765 * Don't allow callers with the given uid permission to get credentials for
5766 * account/authTokenType.
5767 * <p>
5768 * Although this is public it can only be accessed via the AccountManagerService object
5769 * which is in the system. This means we don't need to protect it with permissions.
5770 * @hide
5771 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005772 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005773 if (account == null || authTokenType == null) {
5774 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005775 return;
5776 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005777 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005778 synchronized (accounts.dbLock) {
5779 synchronized (accounts.cacheLock) {
5780 accounts.accountsDb.beginTransaction();
5781 try {
5782 long accountId = accounts.accountsDb.findDeAccountId(account);
5783 if (accountId >= 0) {
5784 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5785 accountId, authTokenType, uid);
5786 accounts.accountsDb.setTransactionSuccessful();
5787 }
5788 } finally {
5789 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005790 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005791
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005792 cancelNotification(
5793 getCredentialPermissionNotificationId(account, authTokenType, uid),
5794 UserHandle.of(accounts.userId));
5795 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005796 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005797
5798 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5799 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5800 : mAppPermissionChangeListeners) {
5801 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5802 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005803 }
Fred Quintana56285a62010-12-02 14:20:51 -08005804
Amith Yamasani04e0d262012-02-14 11:50:53 -08005805 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5806 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005807 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005808 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005809 for (Account curAccount : oldAccountsForType) {
5810 if (!curAccount.equals(account)) {
5811 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005812 }
5813 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005814 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005815 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005816 } else {
5817 Account[] newAccountsForType = new Account[newAccountsList.size()];
5818 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005819 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005820 }
Fred Quintana56285a62010-12-02 14:20:51 -08005821 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005822 accounts.userDataCache.remove(account);
5823 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005824 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005825 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005826 }
5827
5828 /**
5829 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005830 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5831 * processes and if you will return this account to apps you should return the result.
5832 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005833 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005834 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005835 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005836 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5837 Account[] newAccountsForType = new Account[oldLength + 1];
5838 if (accountsForType != null) {
5839 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005840 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005841 String token = account.getAccessId() != null ? account.getAccessId()
5842 : UUID.randomUUID().toString();
5843 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005844 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005845 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005846 }
5847
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005848 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005849 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005850 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005851 String visibilityFilterPackage = callingPackage;
5852 if (visibilityFilterPackage == null) {
5853 visibilityFilterPackage = getPackageNameForUid(callingUid);
5854 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005855 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005856 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005857 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005858 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5859 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5860 || (includeManagedNotVisible
5861 && (visibility
5862 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5863 firstPass.put(account, visibility);
5864 }
5865 }
5866 Map<Account, Integer> secondPass =
5867 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5868
5869 Account[] filtered = new Account[secondPass.size()];
5870 filtered = secondPass.keySet().toArray(filtered);
5871 return filtered;
5872 }
5873
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005874 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005875 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005876 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005877 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005878 // first part is to filter shared accounts.
5879 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005880 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005881 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005882 return unfiltered;
5883 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005884 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005885 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005886 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005887 if (packages == null) {
5888 packages = new String[] {};
5889 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005890 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005891 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005892 // This might be a temporary way to specify a visible list
5893 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005894 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5895 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005896 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005897 return unfiltered;
5898 }
5899 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005900 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005901 if (ArrayUtils.isEmpty(sharedAccounts)) {
5902 return unfiltered;
5903 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005904 String requiredAccountType = "";
5905 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005906 // If there's an explicit callingPackage specified, check if that package
5907 // opted in to see restricted accounts.
5908 if (callingPackage != null) {
5909 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005910 if (pi != null && pi.restrictedAccountType != null) {
5911 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005912 }
5913 } else {
5914 // Otherwise check if the callingUid has a package that has opted in
5915 for (String packageName : packages) {
5916 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5917 if (pi != null && pi.restrictedAccountType != null) {
5918 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005919 break;
5920 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005921 }
5922 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005923 } catch (NameNotFoundException e) {
5924 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005925 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005926 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005927 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5928 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005929 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005930 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005931 } else {
5932 boolean found = false;
5933 for (Account shared : sharedAccounts) {
5934 if (shared.equals(account)) {
5935 found = true;
5936 break;
5937 }
5938 }
5939 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005940 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005941 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005942 }
5943 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005944 return filtered;
5945 } else {
5946 return unfiltered;
5947 }
5948 }
5949
Amith Yamasani27db4682013-03-30 17:07:47 -07005950 /*
5951 * packageName can be null. If not null, it should be used to filter out restricted accounts
5952 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005953 *
5954 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5955 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005956 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005957 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005958 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005959 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005960 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5961 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005962 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005963 Account[] accounts;
5964 synchronized (userAccounts.cacheLock) {
5965 accounts = userAccounts.accountCache.get(accountType);
5966 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005967 if (accounts == null) {
5968 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005969 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005970 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5971 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005972 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005973 } else {
5974 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005975 Account[] accountsArray;
5976 synchronized (userAccounts.cacheLock) {
5977 for (Account[] accounts : userAccounts.accountCache.values()) {
5978 totalLength += accounts.length;
5979 }
5980 if (totalLength == 0) {
5981 return EMPTY_ACCOUNT_ARRAY;
5982 }
5983 accountsArray = new Account[totalLength];
5984 totalLength = 0;
5985 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5986 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
5987 accountsOfType.length);
5988 totalLength += accountsOfType.length;
5989 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005990 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005991 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005992 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005993 }
5994 }
5995
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005996 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005997 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005998 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005999 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006000 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006001 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08006002 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006003 }
6004 if (value == null) {
6005 userDataForAccount.remove(key);
6006 } else {
6007 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08006008 }
6009 }
6010
Carlos Valdivia91979be2015-05-22 14:11:35 -07006011 protected String readCachedTokenInternal(
6012 UserAccounts accounts,
6013 Account account,
6014 String tokenType,
6015 String callingPackage,
6016 byte[] pkgSigDigest) {
Dmitry Dementyev18f0ca92017-06-12 17:56:47 -07006017 synchronized (accounts.cacheLock) {
6018 return accounts.accountTokenCaches.get(
6019 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07006020 }
6021 }
6022
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07006023 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006024 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08006025 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006026 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006027 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006028 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08006029 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006030 }
6031 if (value == null) {
6032 authTokensForAccount.remove(key);
6033 } else {
6034 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08006035 }
6036 }
6037
Amith Yamasani04e0d262012-02-14 11:50:53 -08006038 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
6039 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07006040 // Fast path - check if account is already cached
6041 synchronized (accounts.cacheLock) {
6042 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
6043 if (authTokensForAccount != null) {
6044 return authTokensForAccount.get(authTokenType);
6045 }
6046 }
6047 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07006048 synchronized (accounts.dbLock) {
6049 synchronized (accounts.cacheLock) {
6050 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
6051 if (authTokensForAccount == null) {
6052 // need to populate the cache for this account
6053 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
6054 accounts.authTokenCache.put(account, authTokensForAccount);
6055 }
6056 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08006057 }
Fred Quintana56285a62010-12-02 14:20:51 -08006058 }
6059 }
6060
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006061 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
6062 Map<String, String> userDataForAccount;
6063 // Fast path - check if data is already cached
6064 synchronized (accounts.cacheLock) {
6065 userDataForAccount = accounts.userDataCache.get(account);
6066 }
6067 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00006068 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006069 synchronized (accounts.dbLock) {
6070 synchronized (accounts.cacheLock) {
6071 userDataForAccount = accounts.userDataCache.get(account);
6072 if (userDataForAccount == null) {
6073 // need to populate the cache for this account
6074 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
6075 accounts.userDataCache.put(account, userDataForAccount);
6076 }
6077 }
6078 }
Fred Quintana56285a62010-12-02 14:20:51 -08006079 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00006080 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08006081 }
6082
Kenny Guy07ad8dc2014-09-01 20:56:12 +01006083 private Context getContextForUser(UserHandle user) {
6084 try {
6085 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
6086 } catch (NameNotFoundException e) {
6087 // Default to mContext, not finding the package system is running as is unlikely.
6088 return mContext;
6089 }
6090 }
Sandra Kwan78812282015-11-04 11:19:47 -08006091
6092 private void sendResponse(IAccountManagerResponse response, Bundle result) {
6093 try {
6094 response.onResult(result);
6095 } catch (RemoteException e) {
6096 // if the caller is dead then there is no one to care about remote
6097 // exceptions
6098 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6099 Log.v(TAG, "failure while notifying response", e);
6100 }
6101 }
6102 }
6103
6104 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
6105 String errorMessage) {
6106 try {
6107 response.onError(errorCode, errorMessage);
6108 } catch (RemoteException e) {
6109 // if the caller is dead then there is no one to care about remote
6110 // exceptions
6111 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6112 Log.v(TAG, "failure while notifying response", e);
6113 }
6114 }
6115 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006116
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006117 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07006118 private final Object mLock = new Object();
6119
6120 @GuardedBy("mLock")
6121 private AccountManagerBackupHelper mBackupHelper;
6122
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006123 @Override
6124 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
6125 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
6126 if (account == null) {
6127 Slog.w(TAG, "account cannot be null");
6128 return;
6129 }
6130 if (packageName == null) {
6131 Slog.w(TAG, "packageName cannot be null");
6132 return;
6133 }
6134 if (userId < UserHandle.USER_SYSTEM) {
6135 Slog.w(TAG, "user id must be concrete");
6136 return;
6137 }
6138 if (callback == null) {
6139 Slog.w(TAG, "callback cannot be null");
6140 return;
6141 }
6142
Dmitry Dementyev7b3ea132017-05-10 12:45:02 -07006143 int visibility =
6144 resolveAccountVisibility(account, packageName, getUserAccounts(userId));
6145 if (visibility == AccountManager.VISIBILITY_NOT_VISIBLE) {
6146 Slog.w(TAG, "requestAccountAccess: account is hidden");
6147 return;
6148 }
6149
Svet Ganovf6d424f12016-09-20 20:18:53 -07006150 if (AccountManagerService.this.hasAccountAccess(account, packageName,
6151 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006152 Bundle result = new Bundle();
6153 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
6154 callback.sendResult(result);
6155 return;
6156 }
6157
6158 final int uid;
6159 try {
Dmitry Dementyev940b7602018-10-09 16:40:06 -07006160 long identityToken = clearCallingIdentity();
6161 try {
6162 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
6163 } finally {
6164 restoreCallingIdentity(identityToken);
6165 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006166 } catch (NameNotFoundException e) {
6167 Slog.e(TAG, "Unknown package " + packageName);
6168 return;
6169 }
6170
6171 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006172 final UserAccounts userAccounts;
6173 synchronized (mUsers) {
6174 userAccounts = mUsers.get(userId);
6175 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04006176 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006177 doNotification(userAccounts, account, null, intent, packageName, userId);
6178 }
6179
6180 @Override
6181 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
6182 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
6183 mAppPermissionChangeListeners.add(listener);
6184 }
6185
6186 @Override
6187 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
6188 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006189 }
Svet Ganov5d09c992016-09-07 09:57:41 -07006190
6191 @Override
6192 public byte[] backupAccountAccessPermissions(int userId) {
6193 synchronized (mLock) {
6194 if (mBackupHelper == null) {
6195 mBackupHelper = new AccountManagerBackupHelper(
6196 AccountManagerService.this, this);
6197 }
6198 return mBackupHelper.backupAccountAccessPermissions(userId);
6199 }
6200 }
6201
6202 @Override
6203 public void restoreAccountAccessPermissions(byte[] data, int userId) {
6204 synchronized (mLock) {
6205 if (mBackupHelper == null) {
6206 mBackupHelper = new AccountManagerBackupHelper(
6207 AccountManagerService.this, this);
6208 }
6209 mBackupHelper.restoreAccountAccessPermissions(data, userId);
6210 }
6211 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006212 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07006213
6214 @VisibleForTesting
6215 static class Injector {
6216 private final Context mContext;
6217
6218 public Injector(Context context) {
6219 mContext = context;
6220 }
6221
6222 Looper getMessageHandlerLooper() {
6223 ServiceThread serviceThread = new ServiceThread(TAG,
6224 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
6225 serviceThread.start();
6226 return serviceThread.getLooper();
6227 }
6228
6229 Context getContext() {
6230 return mContext;
6231 }
6232
6233 void addLocalService(AccountManagerInternal service) {
6234 LocalServices.addService(AccountManagerInternal.class, service);
6235 }
6236
6237 String getDeDatabaseName(int userId) {
6238 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
6239 AccountsDb.DE_DATABASE_NAME);
6240 return databaseFile.getPath();
6241 }
6242
6243 String getCeDatabaseName(int userId) {
6244 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
6245 AccountsDb.CE_DATABASE_NAME);
6246 return databaseFile.getPath();
6247 }
6248
6249 String getPreNDatabaseName(int userId) {
6250 File systemDir = Environment.getDataSystemDirectory();
6251 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
6252 PRE_N_DATABASE_NAME);
6253 if (userId == 0) {
6254 // Migrate old file, if it exists, to the new location.
6255 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006256 // accidentally created in the old location,
6257 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07006258 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
6259 if (oldFile.exists() && !databaseFile.exists()) {
6260 // Check for use directory; create if it doesn't exist, else renameTo will fail
6261 File userDir = Environment.getUserSystemDirectory(userId);
6262 if (!userDir.exists()) {
6263 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006264 throw new IllegalStateException(
6265 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006266 }
6267 }
6268 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006269 throw new IllegalStateException(
6270 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006271 }
6272 }
6273 }
6274 return databaseFile.getPath();
6275 }
6276
6277 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
6278 return new AccountAuthenticatorCache(mContext);
6279 }
6280
6281 INotificationManager getNotificationManager() {
6282 return NotificationManager.getService();
6283 }
6284 }
Chris Wren717a8812017-03-31 15:34:39 -04006285
Andrew Scullc7770d62017-05-22 17:49:58 +01006286 private static class NotificationId {
Chris Wren717a8812017-03-31 15:34:39 -04006287 final String mTag;
6288 private final int mId;
6289
6290 NotificationId(String tag, int type) {
6291 mTag = tag;
6292 mId = type;
6293 }
6294 }
Fred Quintana60307342009-03-24 22:48:12 -07006295}