blob: 5996b7d848ea6ffaf422502c334e4021dfeff9ef [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) {
Felipe Lemebc215de2019-12-05 15:23:16 -08001292 try {
1293 return getUserAccountsNotChecked(userId);
1294 } catch (RuntimeException e) {
1295 if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
1296 // Let it go...
1297 throw e;
1298 }
1299 // User accounts database is corrupted, we must wipe out the whole user, otherwise the
1300 // system will crash indefinitely
1301 Slog.wtf(TAG, "Removing user " + userId + " due to exception (" + e + ") reading its "
1302 + "account database");
1303 if (userId == ActivityManager.getCurrentUser() && userId != UserHandle.USER_SYSTEM) {
1304 Slog.i(TAG, "Switching to system user first");
1305 try {
1306 ActivityManager.getService().switchUser(UserHandle.USER_SYSTEM);
1307 } catch (RemoteException re) {
1308 Slog.e(TAG, "Could not switch to " + UserHandle.USER_SYSTEM + ": " + re);
1309 }
1310 }
1311 if (!getUserManager().removeUserEvenWhenDisallowed(userId)) {
1312 Slog.e(TAG, "could not remove user " + userId);
1313 }
1314 throw e;
1315 }
1316 }
1317
1318 private UserAccounts getUserAccountsNotChecked(int userId) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001319 synchronized (mUsers) {
1320 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001321 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001322 if (accounts == null) {
Fyodor Kupolovda993802016-09-21 14:47:10 -07001323 File preNDbFile = new File(mInjector.getPreNDatabaseName(userId));
1324 File deDbFile = new File(mInjector.getDeDatabaseName(userId));
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001325 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001326 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001327 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001328 validateAccounts = true;
1329 }
1330 // open CE database if necessary
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001331 if (!accounts.accountsDb.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001332 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001333 synchronized (accounts.dbLock) {
1334 synchronized (accounts.cacheLock) {
1335 File ceDatabaseFile = new File(mInjector.getCeDatabaseName(userId));
1336 accounts.accountsDb.attachCeDatabase(ceDatabaseFile);
1337 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001338 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001339 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001340 }
1341 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001342 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001343 }
1344 return accounts;
1345 }
1346 }
1347
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001348 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1349 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001350 List<Account> accountsToRemove = accounts.accountsDb.findCeAccountsNotInDe();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001351 if (!accountsToRemove.isEmpty()) {
Hui Yu139c2482018-08-10 15:37:51 -07001352 Slog.i(TAG, accountsToRemove.size()
1353 + " accounts were previously deleted while user "
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001354 + accounts.userId + " was locked. Removing accounts from CE tables");
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001355 logRecord(accounts, AccountsDb.DEBUG_ACTION_SYNC_DE_CE_ACCOUNTS,
1356 AccountsDb.TABLE_ACCOUNTS);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001357
1358 for (Account account : accountsToRemove) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001359 removeAccountInternal(accounts, account, Process.SYSTEM_UID);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001360 }
1361 }
1362 }
1363
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001364 private void purgeOldGrantsAll() {
1365 synchronized (mUsers) {
1366 for (int i = 0; i < mUsers.size(); i++) {
1367 purgeOldGrants(mUsers.valueAt(i));
1368 }
1369 }
1370 }
1371
1372 private void purgeOldGrants(UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001373 synchronized (accounts.dbLock) {
1374 synchronized (accounts.cacheLock) {
1375 List<Integer> uids = accounts.accountsDb.findAllUidGrants();
1376 for (int uid : uids) {
1377 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1378 if (packageExists) {
1379 continue;
1380 }
1381 Log.d(TAG, "deleting grants for UID " + uid
1382 + " because its package is no longer installed");
1383 accounts.accountsDb.deleteGrantsByUid(uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001384 }
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001385 }
1386 }
1387 }
1388
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001389 private void removeVisibilityValuesForPackage(String packageName) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001390 if (isSpecialPackageKey(packageName)) {
1391 return;
1392 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001393 synchronized (mUsers) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001394 int numberOfUsers = mUsers.size();
1395 for (int i = 0; i < numberOfUsers; i++) {
1396 UserAccounts accounts = mUsers.valueAt(i);
1397 try {
1398 mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
1399 } catch (NameNotFoundException e) {
1400 // package does not exist - remove visibility values
1401 accounts.accountsDb.deleteAccountVisibilityForPackage(packageName);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001402 synchronized (accounts.dbLock) {
1403 synchronized (accounts.cacheLock) {
1404 for (Account account : accounts.visibilityCache.keySet()) {
1405 Map<String, Integer> accountVisibility =
1406 getPackagesAndVisibilityForAccountLocked(account, accounts);
1407 accountVisibility.remove(packageName);
1408 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001409 }
1410 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001411 }
1412 }
1413 }
1414 }
1415
Fyodor Kupolov945c97e2017-06-21 17:45:19 -07001416 private void purgeUserData(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001417 UserAccounts accounts;
1418 synchronized (mUsers) {
1419 accounts = mUsers.get(userId);
1420 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001421 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001422 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001423 if (accounts != null) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001424 synchronized (accounts.dbLock) {
1425 synchronized (accounts.cacheLock) {
Dmitry Dementyev47443192018-10-24 13:31:59 -07001426 accounts.accountsDb.closeDebugStatement();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001427 accounts.accountsDb.close();
1428 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001429 }
Amith Yamasani13593602012-03-22 16:16:17 -07001430 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001431 }
1432
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001433 @VisibleForTesting
1434 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001435 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1436 }
1437
1438 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001439 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1440 Log.v(TAG, "onUserUnlocked " + userId);
1441 }
1442 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001443 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001444 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001445 if (userId < 1) return;
Fyodor Kupolov2bc895d2017-12-19 11:53:47 -08001446 mHandler.post(() -> syncSharedAccounts(userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001447 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001448
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001449 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001450 // Check if there's a shared account that needs to be created as an account
1451 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1452 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001453 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001454 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001455 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001456 : UserHandle.USER_SYSTEM;
1457 if (parentUserId < 0) {
1458 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1459 return;
1460 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001461 for (Account sa : sharedAccounts) {
1462 if (ArrayUtils.contains(accounts, sa)) continue;
1463 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001464 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001465 }
1466 }
1467
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001468 @Override
1469 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Dmitry Dementyevc3e913b2019-07-11 11:32:16 -07001470 UserInfo user = getUserManager().getUserInfo(userId);
1471 if (user == null) {
1472 Log.w(TAG, "onServiceChanged: ignore removed user " + userId);
1473 return;
1474 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001475 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001476 }
1477
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001478 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001479 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001480 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001481 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1482 Log.v(TAG, "getPassword: " + account
1483 + ", caller's uid " + Binder.getCallingUid()
1484 + ", pid " + Binder.getCallingPid());
1485 }
Fred Quintana382601f2010-03-25 12:25:10 -07001486 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001487 int userId = UserHandle.getCallingUserId();
1488 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001489 String msg = String.format(
1490 "uid %s cannot get secrets for accounts of type: %s",
1491 callingUid,
1492 account.type);
1493 throw new SecurityException(msg);
1494 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001495 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001496 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001497 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001498 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001499 } finally {
1500 restoreCallingIdentity(identityToken);
1501 }
1502 }
1503
Amith Yamasani04e0d262012-02-14 11:50:53 -08001504 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001505 if (account == null) {
1506 return null;
1507 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001508 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001509 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1510 return null;
1511 }
Fred Quintana31957f12009-10-21 13:43:10 -07001512
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001513 synchronized (accounts.dbLock) {
1514 synchronized (accounts.cacheLock) {
1515 return accounts.accountsDb
1516 .findAccountPasswordByNameAndType(account.name, account.type);
1517 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001518 }
1519 }
1520
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001521 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001522 public String getPreviousName(Account account) {
1523 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1524 Log.v(TAG, "getPreviousName: " + account
1525 + ", caller's uid " + Binder.getCallingUid()
1526 + ", pid " + Binder.getCallingPid());
1527 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001528 Preconditions.checkNotNull(account, "account cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001529 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001530 long identityToken = clearCallingIdentity();
1531 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001532 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001533 return readPreviousNameInternal(accounts, account);
1534 } finally {
1535 restoreCallingIdentity(identityToken);
1536 }
1537 }
1538
1539 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1540 if (account == null) {
1541 return null;
1542 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001543 synchronized (accounts.dbLock) {
1544 synchronized (accounts.cacheLock) {
1545 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1546 if (previousNameRef == null) {
1547 String previousName = accounts.accountsDb.findDeAccountPreviousName(account);
1548 previousNameRef = new AtomicReference<>(previousName);
1549 accounts.previousNameCache.put(account, previousNameRef);
1550 return previousName;
1551 } else {
1552 return previousNameRef.get();
1553 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001554 }
1555 }
1556 }
1557
1558 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001559 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001560 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001561 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001562 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1563 account, key, callingUid, Binder.getCallingPid());
1564 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001565 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001566 Preconditions.checkNotNull(account, "account cannot be null");
1567 Preconditions.checkNotNull(key, "key cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001568 int userId = UserHandle.getCallingUserId();
1569 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001570 String msg = String.format(
1571 "uid %s cannot get user data for accounts of type: %s",
1572 callingUid,
1573 account.type);
1574 throw new SecurityException(msg);
1575 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001576 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001577 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1578 return null;
1579 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001580 long identityToken = clearCallingIdentity();
1581 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001582 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001583 if (!accountExistsCache(accounts, account)) {
1584 return null;
Simranjit Kohli858511c2016-03-10 18:36:11 +00001585 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001586 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001587 } finally {
1588 restoreCallingIdentity(identityToken);
1589 }
1590 }
1591
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001592 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001593 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001594 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001595 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1596 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001597 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001598 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001599 + ", pid " + Binder.getCallingPid());
1600 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001601 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001602 if (isCrossUser(callingUid, userId)) {
1603 throw new SecurityException(
1604 String.format(
1605 "User %s tying to get authenticator types for %s" ,
1606 UserHandle.getCallingUserId(),
1607 userId));
1608 }
1609
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001610 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001611 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001612 return getAuthenticatorTypesInternal(userId);
1613
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001614 } finally {
1615 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001616 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001617 }
1618
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001619 /**
1620 * Should only be called inside of a clearCallingIdentity block.
1621 */
1622 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
Fyodor Kupolov81446482016-08-24 11:27:49 -07001623 mAuthenticatorCache.updateServices(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001624 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1625 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1626 AuthenticatorDescription[] types =
1627 new AuthenticatorDescription[authenticatorCollection.size()];
1628 int i = 0;
1629 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1630 : authenticatorCollection) {
1631 types[i] = authenticator.type;
1632 i++;
1633 }
1634 return types;
1635 }
1636
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001637 private boolean isCrossUser(int callingUid, int userId) {
1638 return (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001639 && callingUid != Process.SYSTEM_UID
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001640 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001641 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1642 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001643 }
1644
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001645 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001646 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001647 return addAccountExplicitlyWithVisibility(account, password, extras, null);
Fred Quintana60307342009-03-24 22:48:12 -07001648 }
1649
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001650 @Override
1651 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001652 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001653 int callingUid = Binder.getCallingUid();
1654 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1655 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001656 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001657 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001658 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1659 final UserAccounts toAccounts = getUserAccounts(userTo);
1660 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001661 if (response != null) {
1662 Bundle result = new Bundle();
1663 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1664 try {
1665 response.onResult(result);
1666 } catch (RemoteException e) {
1667 Slog.w(TAG, "Failed to report error back to the client." + e);
1668 }
1669 }
1670 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001671 }
1672
Hui Yu139c2482018-08-10 15:37:51 -07001673 Slog.d(TAG, "Copying account " + account.toSafeString()
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001674 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001675 long identityToken = clearCallingIdentity();
1676 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001677 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001678 false /* stripAuthTokenFromResult */, account.name,
1679 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001680 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001681 protected String toDebugString(long now) {
1682 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1683 + ", " + account.type;
1684 }
1685
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001686 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001687 public void run() throws RemoteException {
1688 mAuthenticator.getAccountCredentialsForCloning(this, account);
1689 }
1690
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001691 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001692 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001693 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001694 if (result != null
1695 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1696 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001697 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001698 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001699 super.onResult(result);
1700 }
1701 }
1702 }.bind();
1703 } finally {
1704 restoreCallingIdentity(identityToken);
1705 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001706 }
1707
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001708 @Override
1709 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001710 final int callingUid = Binder.getCallingUid();
1711 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1712 String msg = String.format(
1713 "accountAuthenticated( account: %s, callerUid: %s)",
1714 account,
1715 callingUid);
1716 Log.v(TAG, msg);
1717 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001718 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001719 int userId = UserHandle.getCallingUserId();
1720 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001721 String msg = String.format(
1722 "uid %s cannot notify authentication for accounts of type: %s",
1723 callingUid,
1724 account.type);
1725 throw new SecurityException(msg);
1726 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001727
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001728 if (!canUserModifyAccounts(userId, callingUid) ||
1729 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001730 return false;
1731 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001732
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001733 long identityToken = clearCallingIdentity();
1734 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001735 UserAccounts accounts = getUserAccounts(userId);
1736 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001737 } finally {
1738 restoreCallingIdentity(identityToken);
1739 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001740 }
1741
1742 private boolean updateLastAuthenticatedTime(Account account) {
1743 final UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001744 synchronized (accounts.dbLock) {
1745 synchronized (accounts.cacheLock) {
1746 return accounts.accountsDb.updateAccountLastAuthenticatedTime(account);
1747 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001748 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001749 }
1750
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001751 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001752 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1753 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001754 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001755 long id = clearCallingIdentity();
1756 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001757 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001758 false /* stripAuthTokenFromResult */, account.name,
1759 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001760 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001761 protected String toDebugString(long now) {
1762 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1763 + ", " + account.type;
1764 }
1765
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001766 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001767 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001768 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov16bedd42017-03-30 10:00:49 -07001769 for (Account acc : getAccounts(parentUserId, mContext.getOpPackageName())) {
1770 if (acc.equals(account)) {
1771 mAuthenticator.addAccountFromCredentials(
1772 this, account, accountCredentials);
1773 break;
Amith Yamasani5be347b2013-03-31 17:44:31 -07001774 }
1775 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001776 }
1777
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001778 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001779 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001780 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001781 // TODO: Anything to do if if succedded?
1782 // TODO: If it failed: Show error notification? Should we remove the shadow
1783 // account to avoid retries?
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001784 // TODO: what we do with the visibility?
1785
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001786 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001787 }
1788
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001789 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001790 public void onError(int errorCode, String errorMessage) {
1791 super.onError(errorCode, errorMessage);
1792 // TODO: Show error notification to user
1793 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1794 }
1795
1796 }.bind();
1797 } finally {
1798 restoreCallingIdentity(id);
1799 }
1800 }
1801
Amith Yamasani04e0d262012-02-14 11:50:53 -08001802 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001803 Bundle extras, int callingUid, Map<String, Integer> packageToVisibility) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001804 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001805 if (account == null) {
1806 return false;
1807 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001808 if (!isLocalUnlockedUser(accounts.userId)) {
Hui Yu139c2482018-08-10 15:37:51 -07001809 Log.w(TAG, "Account " + account.toSafeString() + " cannot be added - user "
1810 + accounts.userId + " is locked. callingUid=" + callingUid);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001811 return false;
1812 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001813 synchronized (accounts.dbLock) {
1814 synchronized (accounts.cacheLock) {
1815 accounts.accountsDb.beginTransaction();
1816 try {
1817 if (accounts.accountsDb.findCeAccountId(account) >= 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001818 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001819 + ", skipping since the account already exists");
1820 return false;
1821 }
1822 long accountId = accounts.accountsDb.insertCeAccount(account, password);
1823 if (accountId < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001824 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001825 + ", skipping the DB insert failed");
1826 return false;
1827 }
1828 // Insert into DE table
1829 if (accounts.accountsDb.insertDeAccount(account, accountId) < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001830 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001831 + ", skipping the DB insert failed");
1832 return false;
1833 }
1834 if (extras != null) {
1835 for (String key : extras.keySet()) {
1836 final String value = extras.getString(key);
1837 if (accounts.accountsDb.insertExtra(accountId, key, value) < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07001838 Log.w(TAG, "insertAccountIntoDatabase: "
1839 + account.toSafeString()
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001840 + ", skipping since insertExtra failed for key " + key);
1841 return false;
1842 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001843 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001844 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001845
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001846 if (packageToVisibility != null) {
1847 for (Entry<String, Integer> entry : packageToVisibility.entrySet()) {
1848 setAccountVisibility(account, entry.getKey() /* package */,
1849 entry.getValue() /* visibility */, false /* notify */,
1850 accounts);
1851 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001852 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001853 accounts.accountsDb.setTransactionSuccessful();
1854
1855 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
1856 accountId,
1857 accounts, callingUid);
1858
1859 insertAccountIntoCacheLocked(accounts, account);
1860 } finally {
1861 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001862 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001863 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001864 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001865 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1866 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001867 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001868
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001869 sendNotificationAccountUpdated(account, accounts);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001870 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1871 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001872
Amith Yamasani5be347b2013-03-31 17:44:31 -07001873 return true;
1874 }
1875
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001876 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001877 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001878 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001879 }
1880 }
1881
Amith Yamasani5be347b2013-03-31 17:44:31 -07001882 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001883 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001884 * running, then clone the account too.
1885 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001886 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001887 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001888 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001889 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001890 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001891 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001892 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001893 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07001894 mHandler.sendMessage(mHandler.obtainMessage(
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001895 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001896 }
1897 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001898 }
1899 }
1900
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001901 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001902 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001903 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001904 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001905 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08001906 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1907 Log.v(TAG, "hasFeatures: " + account
1908 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001909 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001910 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001911 + ", pid " + Binder.getCallingPid());
1912 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001913 Preconditions.checkArgument(account != null, "account cannot be null");
1914 Preconditions.checkArgument(response != null, "response cannot be null");
1915 Preconditions.checkArgument(features != null, "features cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001916 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001917 checkReadAccountsPermitted(callingUid, account.type, userId,
1918 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001919
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001920 long identityToken = clearCallingIdentity();
1921 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001922 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001923 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001924 } finally {
1925 restoreCallingIdentity(identityToken);
1926 }
1927 }
1928
1929 private class TestFeaturesSession extends Session {
1930 private final String[] mFeatures;
1931 private final Account mAccount;
1932
Amith Yamasani04e0d262012-02-14 11:50:53 -08001933 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001934 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001935 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001936 true /* stripAuthTokenFromResult */, account.name,
1937 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001938 mFeatures = features;
1939 mAccount = account;
1940 }
1941
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001942 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001943 public void run() throws RemoteException {
1944 try {
1945 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1946 } catch (RemoteException e) {
1947 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1948 }
1949 }
1950
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001951 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001952 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001953 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001954 IAccountManagerResponse response = getResponseAndClose();
1955 if (response != null) {
1956 try {
1957 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001958 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001959 return;
1960 }
Fred Quintana56285a62010-12-02 14:20:51 -08001961 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1962 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1963 + response);
1964 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001965 final Bundle newResult = new Bundle();
1966 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1967 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1968 response.onResult(newResult);
1969 } catch (RemoteException e) {
1970 // if the caller is dead then there is no one to care about remote exceptions
1971 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1972 Log.v(TAG, "failure while notifying response", e);
1973 }
1974 }
1975 }
1976 }
1977
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001978 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001979 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001980 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001981 + ", " + mAccount
1982 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1983 }
1984 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001985
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001986 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001987 public void renameAccount(
1988 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001989 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001990 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1991 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001992 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001993 + ", pid " + Binder.getCallingPid());
1994 }
1995 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001996 int userId = UserHandle.getCallingUserId();
1997 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001998 String msg = String.format(
1999 "uid %s cannot rename accounts of type: %s",
2000 callingUid,
2001 accountToRename.type);
2002 throw new SecurityException(msg);
2003 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002004 long identityToken = clearCallingIdentity();
2005 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002006 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002007 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002008 Bundle result = new Bundle();
2009 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
2010 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002011 result.putString(AccountManager.KEY_ACCOUNT_ACCESS_ID,
2012 resultingAccount.getAccessId());
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002013 try {
2014 response.onResult(result);
2015 } catch (RemoteException e) {
2016 Log.w(TAG, e.getMessage());
2017 }
2018 } finally {
2019 restoreCallingIdentity(identityToken);
2020 }
2021 }
2022
2023 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002024 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002025 Account resultAccount = null;
2026 /*
2027 * Cancel existing notifications. Let authenticators
2028 * re-post notifications as required. But we don't know if
2029 * the authenticators have bound their notifications to
2030 * now stale account name data.
2031 *
2032 * With a rename api, we might not need to do this anymore but it
2033 * shouldn't hurt.
2034 */
2035 cancelNotification(
2036 getSigninRequiredNotificationId(accounts, accountToRename),
Chris Wren717a8812017-03-31 15:34:39 -04002037 new UserHandle(accounts.userId));
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002038 synchronized(accounts.credentialsPermissionNotificationIds) {
2039 for (Pair<Pair<Account, String>, Integer> pair:
2040 accounts.credentialsPermissionNotificationIds.keySet()) {
2041 if (accountToRename.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002042 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002043 cancelNotification(id, new UserHandle(accounts.userId));
2044 }
2045 }
2046 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002047 synchronized (accounts.dbLock) {
2048 synchronized (accounts.cacheLock) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002049 List<String> accountRemovedReceivers =
2050 getAccountRemovedReceivers(accountToRename, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002051 accounts.accountsDb.beginTransaction();
2052 Account renamedAccount = new Account(newName, accountToRename.type);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002053 try {
chengangf2d081c2017-12-27 17:17:32 +08002054 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
2055 Log.e(TAG, "renameAccount failed - account with new name already exists");
2056 return null;
2057 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002058 final long accountId = accounts.accountsDb.findDeAccountId(accountToRename);
2059 if (accountId >= 0) {
2060 accounts.accountsDb.renameCeAccount(accountId, newName);
2061 if (accounts.accountsDb.renameDeAccount(
2062 accountId, newName, accountToRename.name)) {
2063 accounts.accountsDb.setTransactionSuccessful();
2064 } else {
2065 Log.e(TAG, "renameAccount failed");
2066 return null;
2067 }
2068 } else {
2069 Log.e(TAG, "renameAccount failed - old account does not exist");
2070 return null;
2071 }
2072 } finally {
2073 accounts.accountsDb.endTransaction();
2074 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002075 /*
2076 * Database transaction was successful. Clean up cached
2077 * data associated with the account in the user profile.
2078 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002079 renamedAccount = insertAccountIntoCacheLocked(accounts, renamedAccount);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002080 /*
2081 * Extract the data and token caches before removing the
2082 * old account to preserve the user data associated with
2083 * the account.
2084 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002085 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
2086 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
2087 Map<String, Integer> tmpVisibility = accounts.visibilityCache.get(accountToRename);
2088 removeAccountFromCacheLocked(accounts, accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002089 /*
2090 * Update the cached data associated with the renamed
2091 * account.
2092 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002093 accounts.userDataCache.put(renamedAccount, tmpData);
2094 accounts.authTokenCache.put(renamedAccount, tmpTokens);
2095 accounts.visibilityCache.put(renamedAccount, tmpVisibility);
2096 accounts.previousNameCache.put(
2097 renamedAccount,
2098 new AtomicReference<>(accountToRename.name));
2099 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002100
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002101 int parentUserId = accounts.userId;
2102 if (canHaveProfile(parentUserId)) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002103 /*
2104 * Owner or system user account was renamed, rename the account for
2105 * those users with which the account was shared.
2106 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002107 List<UserInfo> users = getUserManager().getUsers(true);
2108 for (UserInfo user : users) {
2109 if (user.isRestricted()
2110 && (user.restrictedProfileParentId == parentUserId)) {
2111 renameSharedAccountAsUser(accountToRename, newName, user.id);
2112 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002113 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002114 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002115
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002116 sendNotificationAccountUpdated(resultAccount, accounts);
2117 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002118 for (String packageName : accountRemovedReceivers) {
2119 sendAccountRemovedBroadcast(accountToRename, packageName, accounts.userId);
2120 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002121 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002122 }
2123 return resultAccount;
2124 }
2125
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002126 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002127 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002128 return userInfo != null && userInfo.canHaveProfile();
2129 }
2130
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002131 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002132 public void removeAccount(IAccountManagerResponse response, Account account,
2133 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002134 removeAccountAsUser(
2135 response,
2136 account,
2137 expectActivityLaunch,
2138 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002139 }
2140
2141 @Override
2142 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002143 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002144 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002145 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2146 Log.v(TAG, "removeAccount: " + account
2147 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002148 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002149 + ", pid " + Binder.getCallingPid()
2150 + ", for user id " + userId);
2151 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002152 Preconditions.checkArgument(account != null, "account cannot be null");
2153 Preconditions.checkArgument(response != null, "response cannot be null");
2154
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002155 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002156 if (isCrossUser(callingUid, userId)) {
2157 throw new SecurityException(
2158 String.format(
2159 "User %s tying remove account for %s" ,
2160 UserHandle.getCallingUserId(),
2161 userId));
2162 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002163 /*
Alex Chauf788f9c2017-12-08 15:16:46 +00002164 * Only the system, authenticator or profile owner should be allowed to remove accounts for
2165 * that authenticator. This will let users remove accounts (via Settings in the system) but
2166 * not arbitrary applications (like competing authenticators).
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002167 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002168 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00002169 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
Alex Chauf788f9c2017-12-08 15:16:46 +00002170 && !isSystemUid(callingUid)
2171 && !isProfileOwner(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002172 String msg = String.format(
2173 "uid %s cannot remove accounts of type: %s",
2174 callingUid,
2175 account.type);
2176 throw new SecurityException(msg);
2177 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002178 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002179 try {
2180 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2181 "User cannot modify accounts");
2182 } catch (RemoteException re) {
2183 }
2184 return;
2185 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002186 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002187 try {
2188 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2189 "User cannot modify accounts of this type (policy).");
2190 } catch (RemoteException re) {
2191 }
2192 return;
2193 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002194 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002195 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002196 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002197 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002198 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002199 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002200 if (account.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002201 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002202 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002203 }
2204 }
2205 }
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002206 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002207 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002208 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2209 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002210 accountId,
2211 accounts,
2212 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002213 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002214 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2215 } finally {
2216 restoreCallingIdentity(identityToken);
2217 }
2218 }
2219
2220 @Override
2221 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002222 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002223 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2224 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002225 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002226 + ", pid " + Binder.getCallingPid());
2227 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002228 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002229 if (account == null) {
2230 /*
2231 * Null accounts should result in returning false, as per
2232 * AccountManage.addAccountExplicitly(...) java doc.
2233 */
2234 Log.e(TAG, "account is null");
2235 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002236 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002237 String msg = String.format(
Brandon Weeks9e4e96d2017-08-24 15:24:16 -07002238 "uid %s cannot explicitly remove accounts of type: %s",
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002239 callingUid,
2240 account.type);
2241 throw new SecurityException(msg);
2242 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002243 UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002244 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002245 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002246 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2247 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002248 accountId,
2249 accounts,
2250 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002251 long identityToken = clearCallingIdentity();
2252 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002253 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002254 } finally {
2255 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002256 }
Fred Quintana60307342009-03-24 22:48:12 -07002257 }
2258
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002259 private class RemoveAccountSession extends Session {
2260 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002261 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002262 Account account, boolean expectActivityLaunch) {
2263 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002264 true /* stripAuthTokenFromResult */, account.name,
2265 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002266 mAccount = account;
2267 }
2268
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002269 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002270 protected String toDebugString(long now) {
2271 return super.toDebugString(now) + ", removeAccount"
2272 + ", account " + mAccount;
2273 }
2274
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002275 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002276 public void run() throws RemoteException {
2277 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2278 }
2279
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002280 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002281 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002282 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002283 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2284 && !result.containsKey(AccountManager.KEY_INTENT)) {
2285 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002286 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002287 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002288 }
2289 IAccountManagerResponse response = getResponseAndClose();
2290 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002291 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2292 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2293 + response);
2294 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002295 try {
tiansiming5330b5a2017-10-13 10:57:25 +08002296 response.onResult(result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002297 } catch (RemoteException e) {
tiansiming5330b5a2017-10-13 10:57:25 +08002298 Slog.e(TAG, "Error calling onResult()", e);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002299 }
2300 }
2301 }
2302 super.onResult(result);
2303 }
2304 }
2305
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002306 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002307 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002308 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002309 }
2310
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002311 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002312 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002313 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002314 if (!userUnlocked) {
Hui Yu139c2482018-08-10 15:37:51 -07002315 Slog.i(TAG, "Removing account " + account.toSafeString()
2316 + " while user " + accounts.userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002317 + " is still locked. CE data will be removed later");
2318 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002319 synchronized (accounts.dbLock) {
2320 synchronized (accounts.cacheLock) {
2321 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2322 accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002323 List<String> accountRemovedReceivers =
2324 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002325 accounts.accountsDb.beginTransaction();
2326 // Set to a dummy value, this will only be used if the database
2327 // transaction succeeds.
2328 long accountId = -1;
2329 try {
2330 accountId = accounts.accountsDb.findDeAccountId(account);
2331 if (accountId >= 0) {
2332 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002333 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002334 // always delete from CE table if CE storage is available
2335 // DE account could be removed while CE was locked
2336 if (userUnlocked) {
2337 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2338 if (ceAccountId >= 0) {
2339 accounts.accountsDb.deleteCeAccount(ceAccountId);
2340 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002341 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002342 accounts.accountsDb.setTransactionSuccessful();
2343 } finally {
2344 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002345 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002346 if (isChanged) {
2347 removeAccountFromCacheLocked(accounts, account);
2348 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2349 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002350 if ((packageToVisibility.getValue() == AccountManager.VISIBILITY_VISIBLE)
2351 || (packageToVisibility.getValue()
2352 == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002353 notifyPackage(packageToVisibility.getKey(), accounts);
2354 }
2355 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002356
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002357 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2358 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002359 for (String packageName : accountRemovedReceivers) {
2360 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
2361 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002362 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2363 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2364 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2365 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002366 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002367 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002368 long id = Binder.clearCallingIdentity();
2369 try {
2370 int parentUserId = accounts.userId;
2371 if (canHaveProfile(parentUserId)) {
2372 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002373 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002374 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002375 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002376 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002377 }
2378 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002379 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002380 } finally {
2381 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002382 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002383
2384 if (isChanged) {
2385 synchronized (accounts.credentialsPermissionNotificationIds) {
2386 for (Pair<Pair<Account, String>, Integer> key
2387 : accounts.credentialsPermissionNotificationIds.keySet()) {
2388 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002389 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002390 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002391 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002392 account, uid, false));
2393 }
2394 }
2395 }
2396 }
2397
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002398 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002399 }
2400
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002401 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002402 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002403 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002404 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2405 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002406 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2407 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002408 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002409 + ", pid " + Binder.getCallingPid());
2410 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002411 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002412 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002413 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002414 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002415 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002416 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002417 accounts.accountsDb.beginTransaction();
2418 try {
2419 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2420 accounts.accountsDb.setTransactionSuccessful();
2421 } finally {
2422 accounts.accountsDb.endTransaction();
2423 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002424 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002425 for (Pair<Account, String> tokenInfo : deletedTokens) {
2426 Account act = tokenInfo.first;
2427 String tokenType = tokenInfo.second;
2428 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002429 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002430 // wipe out cached token in memory.
2431 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002432 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002433 }
Fred Quintana60307342009-03-24 22:48:12 -07002434 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002435 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002436 }
2437 }
2438
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002439 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002440 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002441 // TODO Move to AccountsDB
2442 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002443 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002444
Fred Quintana33269202009-04-20 16:05:10 -07002445 try {
2446 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002447 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002448 String accountName = cursor.getString(1);
2449 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002450 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002451 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002452 }
Fred Quintana33269202009-04-20 16:05:10 -07002453 } finally {
2454 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002455 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002456 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002457 }
2458
Carlos Valdivia91979be2015-05-22 14:11:35 -07002459 private void saveCachedToken(
2460 UserAccounts accounts,
2461 Account account,
2462 String callerPkg,
2463 byte[] callerSigDigest,
2464 String tokenType,
2465 String token,
2466 long expiryMillis) {
2467
2468 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2469 return;
2470 }
2471 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002472 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002473 synchronized (accounts.cacheLock) {
2474 accounts.accountTokenCaches.put(
2475 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002476 }
2477 }
2478
Amith Yamasani04e0d262012-02-14 11:50:53 -08002479 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2480 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002481 if (account == null || type == null) {
2482 return false;
2483 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002484 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002485 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002486 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002487 accounts.accountsDb.beginTransaction();
2488 boolean updateCache = false;
2489 try {
2490 long accountId = accounts.accountsDb.findDeAccountId(account);
2491 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002492 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002493 }
2494 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2495 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2496 accounts.accountsDb.setTransactionSuccessful();
2497 updateCache = true;
2498 return true;
2499 }
2500 return false;
2501 } finally {
2502 accounts.accountsDb.endTransaction();
2503 if (updateCache) {
2504 synchronized (accounts.cacheLock) {
2505 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2506 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002507 }
Fred Quintana33269202009-04-20 16:05:10 -07002508 }
Fred Quintana60307342009-03-24 22:48:12 -07002509 }
2510 }
2511
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002512 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002513 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002514 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002515 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2516 Log.v(TAG, "peekAuthToken: " + account
2517 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002518 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002519 + ", pid " + Binder.getCallingPid());
2520 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002521 Preconditions.checkNotNull(account, "account cannot be null");
2522 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002523 int userId = UserHandle.getCallingUserId();
2524 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002525 String msg = String.format(
2526 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2527 callingUid,
2528 account.type);
2529 throw new SecurityException(msg);
2530 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002531 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002532 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2533 + callingUid);
2534 return null;
2535 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002536 long identityToken = clearCallingIdentity();
2537 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002538 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002539 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002540 } finally {
2541 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002542 }
Fred Quintana60307342009-03-24 22:48:12 -07002543 }
2544
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002545 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002546 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002547 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002548 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2549 Log.v(TAG, "setAuthToken: " + account
2550 + ", authTokenType " + authTokenType
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");
2555 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002556 int userId = UserHandle.getCallingUserId();
2557 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002558 String msg = String.format(
2559 "uid %s cannot set auth tokens associated with accounts of type: %s",
2560 callingUid,
2561 account.type);
2562 throw new SecurityException(msg);
2563 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002564 long identityToken = clearCallingIdentity();
2565 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002566 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002567 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002568 } finally {
2569 restoreCallingIdentity(identityToken);
2570 }
Fred Quintana60307342009-03-24 22:48:12 -07002571 }
2572
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002573 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002574 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002575 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002576 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2577 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002578 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002579 + ", pid " + Binder.getCallingPid());
2580 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002581 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002582 int userId = UserHandle.getCallingUserId();
2583 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002584 String msg = String.format(
2585 "uid %s cannot set secrets for accounts of type: %s",
2586 callingUid,
2587 account.type);
2588 throw new SecurityException(msg);
2589 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002590 long identityToken = clearCallingIdentity();
2591 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002592 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002593 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002594 } finally {
2595 restoreCallingIdentity(identityToken);
2596 }
Fred Quintana60307342009-03-24 22:48:12 -07002597 }
2598
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002599 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2600 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002601 if (account == null) {
2602 return;
2603 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002604 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002605 synchronized (accounts.dbLock) {
2606 synchronized (accounts.cacheLock) {
2607 accounts.accountsDb.beginTransaction();
2608 try {
2609 final long accountId = accounts.accountsDb.findDeAccountId(account);
2610 if (accountId >= 0) {
2611 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2612 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2613 accounts.authTokenCache.remove(account);
2614 accounts.accountTokenCaches.remove(account);
2615 accounts.accountsDb.setTransactionSuccessful();
2616 // If there is an account whose password will be updated and the database
2617 // transactions succeed, then we say that a change has occured. Even if the
2618 // new password is the same as the old and there were no authtokens to
2619 // delete.
2620 isChanged = true;
2621 String action = (password == null || password.length() == 0) ?
2622 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2623 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2624 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2625 callingUid);
2626 }
2627 } finally {
2628 accounts.accountsDb.endTransaction();
2629 if (isChanged) {
2630 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2631 sendNotificationAccountUpdated(account, accounts);
2632 sendAccountsChangedBroadcast(accounts.userId);
2633 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002634 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002635 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002636 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002637 }
2638
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002639 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002640 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002641 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2643 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002644 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002645 + ", pid " + Binder.getCallingPid());
2646 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002647 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002648 int userId = UserHandle.getCallingUserId();
2649 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002650 String msg = String.format(
2651 "uid %s cannot clear passwords for accounts of type: %s",
2652 callingUid,
2653 account.type);
2654 throw new SecurityException(msg);
2655 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002656 long identityToken = clearCallingIdentity();
2657 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002658 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002659 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002660 } finally {
2661 restoreCallingIdentity(identityToken);
2662 }
Fred Quintana60307342009-03-24 22:48:12 -07002663 }
2664
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002665 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002666 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002667 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002668 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2669 Log.v(TAG, "setUserData: " + account
2670 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002671 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002672 + ", pid " + Binder.getCallingPid());
2673 }
Fred Quintana382601f2010-03-25 12:25:10 -07002674 if (key == null) throw new IllegalArgumentException("key is null");
2675 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002676 int userId = UserHandle.getCallingUserId();
2677 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002678 String msg = String.format(
2679 "uid %s cannot set user data for accounts of type: %s",
2680 callingUid,
2681 account.type);
2682 throw new SecurityException(msg);
2683 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002684 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002685 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002686 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002687 if (!accountExistsCache(accounts, account)) {
2688 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002689 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002690 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002691 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002692 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002693 }
2694 }
2695
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002696 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2697 synchronized (accounts.cacheLock) {
2698 if (accounts.accountCache.containsKey(account.type)) {
2699 for (Account acc : accounts.accountCache.get(account.type)) {
2700 if (acc.name.equals(account.name)) {
2701 return true;
2702 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002703 }
2704 }
2705 }
2706 return false;
2707 }
2708
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002709 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002710 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002711 synchronized (accounts.dbLock) {
2712 accounts.accountsDb.beginTransaction();
2713 try {
2714 long accountId = accounts.accountsDb.findDeAccountId(account);
2715 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002716 return;
2717 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002718 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2719 if (extrasId < 0) {
2720 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2721 if (extrasId < 0) {
2722 return;
2723 }
2724 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2725 return;
2726 }
2727 accounts.accountsDb.setTransactionSuccessful();
2728 } finally {
2729 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002730 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002731 synchronized (accounts.cacheLock) {
2732 writeUserDataIntoCacheLocked(accounts, account, key, value);
2733 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002734 }
2735 }
2736
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002737 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002738 if (result == null) {
2739 Log.e(TAG, "the result is unexpectedly null", new Exception());
2740 }
2741 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2742 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2743 + response);
2744 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002745 try {
2746 response.onResult(result);
2747 } catch (RemoteException e) {
2748 // if the caller is dead then there is no one to care about remote
2749 // exceptions
2750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2751 Log.v(TAG, "failure while notifying response", e);
2752 }
2753 }
2754 }
2755
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002756 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002757 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2758 final String authTokenType)
2759 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002760 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2761 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002762
Fred Quintanad9640ec2012-05-23 12:37:00 -07002763 final int callingUid = getCallingUid();
2764 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002765 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002766 throw new SecurityException("can only call from system");
2767 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002768 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002769 long identityToken = clearCallingIdentity();
2770 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002771 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002772 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2773 false /* stripAuthTokenFromResult */, null /* accountName */,
2774 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002775 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002776 protected String toDebugString(long now) {
2777 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002778 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002779 + ", authTokenType " + authTokenType;
2780 }
2781
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002782 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002783 public void run() throws RemoteException {
2784 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2785 }
2786
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002787 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002788 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002789 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002790 if (result != null) {
2791 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2792 Bundle bundle = new Bundle();
2793 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2794 super.onResult(bundle);
2795 return;
2796 } else {
2797 super.onResult(result);
2798 }
2799 }
2800 }.bind();
2801 } finally {
2802 restoreCallingIdentity(identityToken);
2803 }
2804 }
2805
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002806 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002807 public void getAuthToken(
2808 IAccountManagerResponse response,
2809 final Account account,
2810 final String authTokenType,
2811 final boolean notifyOnAuthFailure,
2812 final boolean expectActivityLaunch,
2813 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002814 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002815 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2816 Log.v(TAG, "getAuthToken: " + account
2817 + ", response " + response
2818 + ", authTokenType " + authTokenType
2819 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2820 + ", expectActivityLaunch " + expectActivityLaunch
2821 + ", caller's uid " + Binder.getCallingUid()
2822 + ", pid " + Binder.getCallingPid());
2823 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002824 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002825 try {
2826 if (account == null) {
2827 Slog.w(TAG, "getAuthToken called with null account");
2828 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2829 return;
2830 }
2831 if (authTokenType == null) {
2832 Slog.w(TAG, "getAuthToken called with null authTokenType");
2833 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2834 return;
2835 }
2836 } catch (RemoteException e) {
2837 Slog.w(TAG, "Failed to report error back to the client." + e);
2838 return;
2839 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002840 int userId = UserHandle.getCallingUserId();
2841 long ident = Binder.clearCallingIdentity();
2842 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002843 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002844 try {
2845 accounts = getUserAccounts(userId);
2846 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2847 AuthenticatorDescription.newKey(account.type), accounts.userId);
2848 } finally {
2849 Binder.restoreCallingIdentity(ident);
2850 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002851
Costin Manolachea40c6302010-12-13 14:50:45 -08002852 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002853 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002854
2855 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002856 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002857 final boolean permissionGranted =
2858 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002859
Carlos Valdivia91979be2015-05-22 14:11:35 -07002860 // Get the calling package. We will use it for the purpose of caching.
2861 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002862 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002863 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002864 try {
2865 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2866 } finally {
2867 Binder.restoreCallingIdentity(ident);
2868 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002869 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2870 String msg = String.format(
2871 "Uid %s is attempting to illegally masquerade as package %s!",
2872 callerUid,
2873 callerPkg);
2874 throw new SecurityException(msg);
2875 }
2876
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002877 // let authenticator know the identity of the caller
2878 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2879 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002880
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002881 if (notifyOnAuthFailure) {
2882 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002883 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002884
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002885 long identityToken = clearCallingIdentity();
2886 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002887 // Distill the caller's package signatures into a single digest.
2888 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2889
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002890 // if the caller has permission, do the peek. otherwise go the more expensive
2891 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002892 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002893 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002894 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002895 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002896 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2897 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2898 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002899 onResult(response, result);
2900 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002901 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002902 }
2903
Carlos Valdivia91979be2015-05-22 14:11:35 -07002904 if (customTokens) {
2905 /*
2906 * Look up tokens in the new cache only if the loginOptions don't have parameters
2907 * outside of those expected to be injected by the AccountManager, e.g.
2908 * ANDORID_PACKAGE_NAME.
2909 */
2910 String token = readCachedTokenInternal(
2911 accounts,
2912 account,
2913 authTokenType,
2914 callerPkg,
2915 callerPkgSigDigest);
2916 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002917 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2918 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2919 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002920 Bundle result = new Bundle();
2921 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2922 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2923 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2924 onResult(response, result);
2925 return;
2926 }
2927 }
2928
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002929 new Session(
2930 accounts,
2931 response,
2932 account.type,
2933 expectActivityLaunch,
2934 false /* stripAuthTokenFromResult */,
2935 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002936 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002937 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002938 protected String toDebugString(long now) {
2939 if (loginOptions != null) loginOptions.keySet();
2940 return super.toDebugString(now) + ", getAuthToken"
Hui Yu139c2482018-08-10 15:37:51 -07002941 + ", " + account.toSafeString()
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002942 + ", authTokenType " + authTokenType
2943 + ", loginOptions " + loginOptions
2944 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2945 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002946
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002947 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002948 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002949 // If the caller doesn't have permission then create and return the
2950 // "grant permission" intent instead of the "getAuthToken" intent.
2951 if (!permissionGranted) {
2952 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2953 } else {
2954 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2955 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002956 }
2957
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002958 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002959 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002960 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002961 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002962 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002963 Intent intent = newGrantCredentialsPermissionIntent(
2964 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002965 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002966 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002967 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002968 authTokenType,
2969 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002970 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002971 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002972 onResult(bundle);
2973 return;
2974 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002975 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002976 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002977 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2978 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002979 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002980 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002981 "the type and name should not be empty");
2982 return;
2983 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002984 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002985 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002986 saveAuthTokenToDatabase(
2987 mAccounts,
2988 resultAccount,
2989 authTokenType,
2990 authToken);
2991 }
2992 long expiryMillis = result.getLong(
2993 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2994 if (customTokens
2995 && expiryMillis > System.currentTimeMillis()) {
2996 saveCachedToken(
2997 mAccounts,
2998 account,
2999 callerPkg,
3000 callerPkgSigDigest,
3001 authTokenType,
3002 authToken,
3003 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08003004 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003005 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003006
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003007 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08003008 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07003009 /*
3010 * Make sure that the supplied intent is owned by the authenticator
3011 * giving it to the system. Otherwise a malicious authenticator could
3012 * have users launching arbitrary activities by tricking users to
3013 * interact with malicious notifications.
3014 */
tiansiminga8868bf2017-09-20 13:59:13 +08003015 if (!checkKeyIntent(
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07003016 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08003017 intent)) {
3018 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
3019 "invalid intent in bundle returned");
3020 return;
3021 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003022 doNotification(
3023 mAccounts,
3024 account,
3025 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003026 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003027 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003028 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003029 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07003030 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003031 }.bind();
3032 } finally {
3033 restoreCallingIdentity(identityToken);
3034 }
Fred Quintana60307342009-03-24 22:48:12 -07003035 }
3036
Carlos Valdivia91979be2015-05-22 14:11:35 -07003037 private byte[] calculatePackageSignatureDigest(String callerPkg) {
3038 MessageDigest digester;
3039 try {
3040 digester = MessageDigest.getInstance("SHA-256");
3041 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3042 callerPkg, PackageManager.GET_SIGNATURES);
3043 for (Signature sig : pkgInfo.signatures) {
3044 digester.update(sig.toByteArray());
3045 }
3046 } catch (NoSuchAlgorithmException x) {
3047 Log.wtf(TAG, "SHA-256 should be available", x);
3048 digester = null;
3049 } catch (NameNotFoundException e) {
3050 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
3051 digester = null;
3052 }
3053 return (digester == null) ? null : digester.digest();
3054 }
3055
Dianne Hackborn41203752012-08-31 14:05:51 -07003056 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003057 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003058 int uid = intent.getIntExtra(
3059 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
3060 String authTokenType = intent.getStringExtra(
3061 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07003062 final String titleAndSubtitle =
3063 mContext.getString(R.string.permission_request_notification_with_subtitle,
3064 account.name);
3065 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07003066 String title = titleAndSubtitle;
3067 String subtitle = "";
3068 if (index > 0) {
3069 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04003070 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07003071 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07003072 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003073 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05003074 Notification n =
3075 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
3076 .setSmallIcon(android.R.drawable.stat_sys_warning)
3077 .setWhen(0)
3078 .setColor(contextForUser.getColor(
3079 com.android.internal.R.color.system_notification_accent_color))
3080 .setContentTitle(title)
3081 .setContentText(subtitle)
3082 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
3083 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
3084 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003085 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003086 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003087 }
3088
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003089 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
3090 int uid, AccountAuthenticatorResponse response, String authTokenType,
3091 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003092
3093 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003094
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003095 if (startInNewTask) {
3096 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
3097 // Since it was set in Eclair+ we can't change it without breaking apps using
3098 // the intent from a non-Activity context. This is the default behavior.
3099 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3100 }
Chris Wren717a8812017-03-31 15:34:39 -04003101 intent.addCategory(getCredentialPermissionNotificationId(account,
3102 authTokenType, uid).mTag + (packageName != null ? packageName : ""));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003103 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003104 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
3105 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003106 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003107
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003108 return intent;
3109 }
3110
Chris Wren717a8812017-03-31 15:34:39 -04003111 private NotificationId getCredentialPermissionNotificationId(Account account,
3112 String authTokenType, int uid) {
3113 NotificationId nId;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003114 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003115 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003116 final Pair<Pair<Account, String>, Integer> key =
3117 new Pair<Pair<Account, String>, Integer>(
3118 new Pair<Account, String>(account, authTokenType), uid);
Chris Wren717a8812017-03-31 15:34:39 -04003119 nId = accounts.credentialsPermissionNotificationIds.get(key);
3120 if (nId == null) {
3121 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION
3122 + ":" + account.hashCode() + ":" + authTokenType.hashCode();
3123 int id = SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION;
3124 nId = new NotificationId(tag, id);
3125 accounts.credentialsPermissionNotificationIds.put(key, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003126 }
3127 }
Chris Wren717a8812017-03-31 15:34:39 -04003128 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003129 }
3130
Chris Wren717a8812017-03-31 15:34:39 -04003131 private NotificationId getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
3132 NotificationId nId;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003133 synchronized (accounts.signinRequiredNotificationIds) {
Chris Wren717a8812017-03-31 15:34:39 -04003134 nId = accounts.signinRequiredNotificationIds.get(account);
3135 if (nId == null) {
3136 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN
3137 + ":" + account.hashCode();
3138 int id = SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN;
3139 nId = new NotificationId(tag, id);
3140 accounts.signinRequiredNotificationIds.put(account, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003141 }
3142 }
Chris Wren717a8812017-03-31 15:34:39 -04003143 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003144 }
3145
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003146 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07003147 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07003148 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003149 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003150 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003151 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3152 Log.v(TAG, "addAccount: accountType " + accountType
3153 + ", response " + response
3154 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003155 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08003156 + ", expectActivityLaunch " + expectActivityLaunch
3157 + ", caller's uid " + Binder.getCallingUid()
3158 + ", pid " + Binder.getCallingPid());
3159 }
Fred Quintana382601f2010-03-25 12:25:10 -07003160 if (response == null) throw new IllegalArgumentException("response is null");
3161 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003162
Amith Yamasani71e6c692013-03-24 17:39:28 -07003163 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003164 final int uid = Binder.getCallingUid();
3165 final int userId = UserHandle.getUserId(uid);
3166 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003167 try {
3168 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3169 "User is not allowed to add an account!");
3170 } catch (RemoteException re) {
3171 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003172 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003173 return;
3174 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003175 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003176 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003177 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3178 "User cannot modify accounts of this type (policy).");
3179 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003180 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003181 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3182 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003183 return;
3184 }
3185
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003186 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003187 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3188 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3189 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3190
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003191 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003192 long identityToken = clearCallingIdentity();
3193 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003194 UserAccounts accounts = getUserAccounts(usrId);
3195 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003196 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3197 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003198 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003199 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003200 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003201 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003202 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003203 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003204 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003205 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003206
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003207 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003208 protected String toDebugString(long now) {
3209 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003210 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003211 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003212 }
3213 }.bind();
3214 } finally {
3215 restoreCallingIdentity(identityToken);
3216 }
Fred Quintana60307342009-03-24 22:48:12 -07003217 }
3218
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003219 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003220 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3221 final String authTokenType, final String[] requiredFeatures,
3222 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003223 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003224 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003225 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3226 Log.v(TAG, "addAccount: accountType " + accountType
3227 + ", response " + response
3228 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003229 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003230 + ", expectActivityLaunch " + expectActivityLaunch
3231 + ", caller's uid " + Binder.getCallingUid()
3232 + ", pid " + Binder.getCallingPid()
3233 + ", for user id " + userId);
3234 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003235 Preconditions.checkArgument(response != null, "response cannot be null");
3236 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003237 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003238 if (isCrossUser(callingUid, userId)) {
3239 throw new SecurityException(
3240 String.format(
3241 "User %s trying to add account for %s" ,
3242 UserHandle.getCallingUserId(),
3243 userId));
3244 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003245
3246 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003247 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003248 try {
3249 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3250 "User is not allowed to add an account!");
3251 } catch (RemoteException re) {
3252 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003253 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003254 return;
3255 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003256 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003257 try {
3258 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3259 "User cannot modify accounts of this type (policy).");
3260 } catch (RemoteException re) {
3261 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003262 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3263 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003264 return;
3265 }
3266
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003267 final int pid = Binder.getCallingPid();
3268 final int uid = Binder.getCallingUid();
3269 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3270 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3271 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3272
3273 long identityToken = clearCallingIdentity();
3274 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003275 UserAccounts accounts = getUserAccounts(userId);
3276 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003277 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
Valentin Iftime0e7f5bb2019-10-30 19:29:33 +01003278 uid);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003279 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003280 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003281 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003282 @Override
3283 public void run() throws RemoteException {
3284 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3285 options);
3286 }
3287
3288 @Override
3289 protected String toDebugString(long now) {
3290 return super.toDebugString(now) + ", addAccount"
3291 + ", accountType " + accountType
3292 + ", requiredFeatures "
3293 + (requiredFeatures != null
3294 ? TextUtils.join(",", requiredFeatures)
3295 : null);
3296 }
3297 }.bind();
3298 } finally {
3299 restoreCallingIdentity(identityToken);
3300 }
3301 }
3302
Sandra Kwan78812282015-11-04 11:19:47 -08003303 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003304 public void startAddAccountSession(
3305 final IAccountManagerResponse response,
3306 final String accountType,
3307 final String authTokenType,
3308 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003309 final boolean expectActivityLaunch,
3310 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003311 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003312 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3313 Log.v(TAG,
3314 "startAddAccountSession: accountType " + accountType
3315 + ", response " + response
3316 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003317 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003318 + ", expectActivityLaunch " + expectActivityLaunch
3319 + ", caller's uid " + Binder.getCallingUid()
3320 + ", pid " + Binder.getCallingPid());
3321 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003322 Preconditions.checkArgument(response != null, "response cannot be null");
3323 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003324
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003325 final int uid = Binder.getCallingUid();
3326 final int userId = UserHandle.getUserId(uid);
3327 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003328 try {
3329 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3330 "User is not allowed to add an account!");
3331 } catch (RemoteException re) {
3332 }
3333 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3334 return;
3335 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003336 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003337 try {
3338 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3339 "User cannot modify accounts of this type (policy).");
3340 } catch (RemoteException re) {
3341 }
3342 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3343 userId);
3344 return;
3345 }
Sandra Kwan78812282015-11-04 11:19:47 -08003346 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003347 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3348 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3349 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3350
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003351 // Check to see if the Password should be included to the caller.
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07003352 String callerPkg = options.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3353 boolean isPasswordForwardingAllowed = checkPermissionAndNote(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003354 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003355
Sandra Kwan78812282015-11-04 11:19:47 -08003356 long identityToken = clearCallingIdentity();
3357 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003358 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003359 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3360 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003361 new StartAccountSession(
3362 accounts,
3363 response,
3364 accountType,
3365 expectActivityLaunch,
3366 null /* accountName */,
3367 false /* authDetailsRequired */,
3368 true /* updateLastAuthenticationTime */,
3369 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003370 @Override
3371 public void run() throws RemoteException {
3372 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3373 requiredFeatures, options);
3374 }
3375
3376 @Override
3377 protected String toDebugString(long now) {
3378 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3379 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3380 + accountType + ", requiredFeatures "
3381 + (requiredFeatures != null ? requiredFeaturesStr : null);
3382 }
3383 }.bind();
3384 } finally {
3385 restoreCallingIdentity(identityToken);
3386 }
3387 }
3388
3389 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3390 private abstract class StartAccountSession extends Session {
3391
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003392 private final boolean mIsPasswordForwardingAllowed;
3393
3394 public StartAccountSession(
3395 UserAccounts accounts,
3396 IAccountManagerResponse response,
3397 String accountType,
3398 boolean expectActivityLaunch,
3399 String accountName,
3400 boolean authDetailsRequired,
3401 boolean updateLastAuthenticationTime,
3402 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003403 super(accounts, response, accountType, expectActivityLaunch,
3404 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3405 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003406 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003407 }
3408
3409 @Override
3410 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003411 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003412 mNumResults++;
3413 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003414 if (result != null
3415 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
tiansiminga8868bf2017-09-20 13:59:13 +08003416 if (!checkKeyIntent(
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003417 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08003418 intent)) {
3419 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
3420 "invalid intent in bundle returned");
3421 return;
3422 }
Sandra Kwan78812282015-11-04 11:19:47 -08003423 }
Sandra Kwan78812282015-11-04 11:19:47 -08003424 IAccountManagerResponse response;
3425 if (mExpectActivityLaunch && result != null
3426 && result.containsKey(AccountManager.KEY_INTENT)) {
3427 response = mResponse;
3428 } else {
3429 response = getResponseAndClose();
3430 }
3431 if (response == null) {
3432 return;
3433 }
3434 if (result == null) {
3435 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3436 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3437 + response);
3438 }
3439 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3440 "null bundle returned");
3441 return;
3442 }
3443
3444 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3445 // All AccountManager error codes are greater
3446 // than 0
3447 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3448 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3449 return;
3450 }
3451
Hongming Jin368aa192016-07-29 14:29:54 -07003452 // Omit passwords if the caller isn't permitted to see them.
3453 if (!mIsPasswordForwardingAllowed) {
3454 result.remove(AccountManager.KEY_PASSWORD);
3455 }
3456
Sandra Kwan78812282015-11-04 11:19:47 -08003457 // Strip auth token from result.
3458 result.remove(AccountManager.KEY_AUTHTOKEN);
3459
3460 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3461 Log.v(TAG,
3462 getClass().getSimpleName() + " calling onResult() on response " + response);
3463 }
3464
3465 // Get the session bundle created by authenticator. The
3466 // bundle contains data necessary for finishing the session
3467 // later. The session bundle will be encrypted here and
3468 // decrypted later when trying to finish the session.
3469 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3470 if (sessionBundle != null) {
3471 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3472 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003473 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003474 Log.w(TAG, "Account type in session bundle doesn't match request.");
3475 }
3476 // Add accountType info to session bundle. This will
3477 // override any value set by authenticator.
3478 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3479
3480 // Encrypt session bundle before returning to caller.
3481 try {
3482 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3483 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3484 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3485 } catch (GeneralSecurityException e) {
3486 if (Log.isLoggable(TAG, Log.DEBUG)) {
3487 Log.v(TAG, "Failed to encrypt session bundle!", e);
3488 }
3489 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3490 "failed to encrypt session bundle");
3491 return;
3492 }
3493 }
3494
3495 sendResponse(response, result);
3496 }
3497 }
3498
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003499 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003500 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003501 @NonNull Bundle sessionBundle,
3502 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003503 Bundle appInfo,
3504 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003505 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003506 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003507 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3508 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003509 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003510 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003511 + ", caller's uid " + callingUid
3512 + ", caller's user id " + UserHandle.getCallingUserId()
3513 + ", pid " + Binder.getCallingPid()
3514 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003515 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003516 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003517 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3518 // Account type is added to it before encryption.
3519 if (sessionBundle == null || sessionBundle.size() == 0) {
3520 throw new IllegalArgumentException("sessionBundle is empty");
3521 }
3522
Dmitry Dementyev52745472016-12-02 10:27:45 -08003523 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003524 if (isCrossUser(callingUid, userId)) {
3525 throw new SecurityException(
3526 String.format(
3527 "User %s trying to finish session for %s without cross user permission",
3528 UserHandle.getCallingUserId(),
3529 userId));
3530 }
3531
Sandra Kwan0b84b452016-01-20 15:25:42 -08003532 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003533 sendErrorResponse(response,
3534 AccountManager.ERROR_CODE_USER_RESTRICTED,
3535 "User is not allowed to add an account!");
3536 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3537 return;
3538 }
3539
3540 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003541 final Bundle decryptedBundle;
3542 final String accountType;
3543 // First decrypt session bundle to get account type for checking permission.
3544 try {
3545 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3546 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3547 if (decryptedBundle == null) {
3548 sendErrorResponse(
3549 response,
3550 AccountManager.ERROR_CODE_BAD_REQUEST,
3551 "failed to decrypt session bundle");
3552 return;
3553 }
3554 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3555 // Account type cannot be null. This should not happen if session bundle was created
3556 // properly by #StartAccountSession.
3557 if (TextUtils.isEmpty(accountType)) {
3558 sendErrorResponse(
3559 response,
3560 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3561 "accountType is empty");
3562 return;
3563 }
3564
3565 // If by any chances, decryptedBundle contains colliding keys with
3566 // system info
3567 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3568 // update credentials flow, we should replace with the new values of the current call.
3569 if (appInfo != null) {
3570 decryptedBundle.putAll(appInfo);
3571 }
3572
3573 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003574 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003575 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3576 } catch (GeneralSecurityException e) {
3577 if (Log.isLoggable(TAG, Log.DEBUG)) {
3578 Log.v(TAG, "Failed to decrypt session bundle!", e);
3579 }
3580 sendErrorResponse(
3581 response,
3582 AccountManager.ERROR_CODE_BAD_REQUEST,
3583 "failed to decrypt session bundle");
3584 return;
3585 }
3586
Sandra Kwan0b84b452016-01-20 15:25:42 -08003587 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003588 sendErrorResponse(
3589 response,
3590 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3591 "User cannot modify accounts of this type (policy).");
3592 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3593 userId);
3594 return;
3595 }
3596
3597 long identityToken = clearCallingIdentity();
3598 try {
3599 UserAccounts accounts = getUserAccounts(userId);
3600 logRecordWithUid(
3601 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003602 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3603 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003604 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003605 new Session(
3606 accounts,
3607 response,
3608 accountType,
3609 expectActivityLaunch,
3610 true /* stripAuthTokenFromResult */,
3611 null /* accountName */,
3612 false /* authDetailsRequired */,
3613 true /* updateLastAuthenticationTime */) {
3614 @Override
3615 public void run() throws RemoteException {
3616 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3617 }
3618
3619 @Override
3620 protected String toDebugString(long now) {
3621 return super.toDebugString(now)
3622 + ", finishSession"
3623 + ", accountType " + accountType;
3624 }
3625 }.bind();
3626 } finally {
3627 restoreCallingIdentity(identityToken);
3628 }
3629 }
3630
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003631 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003632 final DevicePolicyManagerInternal dpmi =
3633 LocalServices.getService(DevicePolicyManagerInternal.class);
3634 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003635 if (dpmi == null) {
3636 intent = getDefaultCantAddAccountIntent(errorCode);
3637 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003638 intent = dpmi.createUserRestrictionSupportIntent(userId,
3639 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3640 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3641 intent = dpmi.createShowAdminSupportIntent(userId, false);
3642 }
3643 if (intent == null) {
3644 intent = getDefaultCantAddAccountIntent(errorCode);
3645 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003646 long identityToken = clearCallingIdentity();
3647 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003648 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003649 } finally {
3650 restoreCallingIdentity(identityToken);
3651 }
3652 }
3653
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003654 /**
3655 * Called when we don't know precisely who is preventing us from adding an account.
3656 */
3657 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3658 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3659 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3660 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3661 return cantAddAccount;
3662 }
3663
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003664 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003665 public void confirmCredentialsAsUser(
3666 IAccountManagerResponse response,
3667 final Account account,
3668 final Bundle options,
3669 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003670 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003671 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003672 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003673 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3674 Log.v(TAG, "confirmCredentials: " + account
3675 + ", response " + response
3676 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003677 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003678 + ", pid " + Binder.getCallingPid());
3679 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003680 // Only allow the system process to read accounts of other users
3681 if (isCrossUser(callingUid, userId)) {
3682 throw new SecurityException(
3683 String.format(
3684 "User %s trying to confirm account credentials for %s" ,
3685 UserHandle.getCallingUserId(),
3686 userId));
3687 }
Fred Quintana382601f2010-03-25 12:25:10 -07003688 if (response == null) throw new IllegalArgumentException("response is null");
3689 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003690 long identityToken = clearCallingIdentity();
3691 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003692 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003693 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003694 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003695 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003696 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003697 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003698 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003699 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003700 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003701 protected String toDebugString(long now) {
3702 return super.toDebugString(now) + ", confirmCredentials"
Hui Yu139c2482018-08-10 15:37:51 -07003703 + ", " + account.toSafeString();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003704 }
3705 }.bind();
3706 } finally {
3707 restoreCallingIdentity(identityToken);
3708 }
Fred Quintana60307342009-03-24 22:48:12 -07003709 }
3710
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003711 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003712 public void updateCredentials(IAccountManagerResponse response, final Account account,
3713 final String authTokenType, final boolean expectActivityLaunch,
3714 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003715 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003716 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3717 Log.v(TAG, "updateCredentials: " + account
3718 + ", response " + response
3719 + ", authTokenType " + authTokenType
3720 + ", expectActivityLaunch " + expectActivityLaunch
3721 + ", caller's uid " + Binder.getCallingUid()
3722 + ", pid " + Binder.getCallingPid());
3723 }
Fred Quintana382601f2010-03-25 12:25:10 -07003724 if (response == null) throw new IllegalArgumentException("response is null");
3725 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003726 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003727 long identityToken = clearCallingIdentity();
3728 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003729 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003730 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003731 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003732 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003733 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003734 public void run() throws RemoteException {
3735 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3736 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003737 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003738 protected String toDebugString(long now) {
3739 if (loginOptions != null) loginOptions.keySet();
3740 return super.toDebugString(now) + ", updateCredentials"
Hui Yu139c2482018-08-10 15:37:51 -07003741 + ", " + account.toSafeString()
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003742 + ", authTokenType " + authTokenType
3743 + ", loginOptions " + loginOptions;
3744 }
3745 }.bind();
3746 } finally {
3747 restoreCallingIdentity(identityToken);
3748 }
Fred Quintana60307342009-03-24 22:48:12 -07003749 }
3750
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003751 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003752 public void startUpdateCredentialsSession(
3753 IAccountManagerResponse response,
3754 final Account account,
3755 final String authTokenType,
3756 final boolean expectActivityLaunch,
3757 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003758 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003759 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3760 Log.v(TAG,
3761 "startUpdateCredentialsSession: " + account + ", response " + response
3762 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3763 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3764 + ", pid " + Binder.getCallingPid());
3765 }
3766 if (response == null) {
3767 throw new IllegalArgumentException("response is null");
3768 }
3769 if (account == null) {
3770 throw new IllegalArgumentException("account is null");
3771 }
Sandra Kwana578d112015-12-16 16:01:43 -08003772
3773 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003774 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003775
3776 // Check to see if the Password should be included to the caller.
3777 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07003778 boolean isPasswordForwardingAllowed = checkPermissionAndNote(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003779 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003780
Sandra Kwane68c37e2015-11-12 17:11:49 -08003781 long identityToken = clearCallingIdentity();
3782 try {
3783 UserAccounts accounts = getUserAccounts(userId);
3784 new StartAccountSession(
3785 accounts,
3786 response,
3787 account.type,
3788 expectActivityLaunch,
3789 account.name,
3790 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003791 true /* updateLastCredentialTime */,
3792 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003793 @Override
3794 public void run() throws RemoteException {
3795 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3796 loginOptions);
3797 }
3798
3799 @Override
3800 protected String toDebugString(long now) {
3801 if (loginOptions != null)
3802 loginOptions.keySet();
3803 return super.toDebugString(now)
3804 + ", startUpdateCredentialsSession"
Hui Yu139c2482018-08-10 15:37:51 -07003805 + ", " + account.toSafeString()
Sandra Kwane68c37e2015-11-12 17:11:49 -08003806 + ", authTokenType " + authTokenType
3807 + ", loginOptions " + loginOptions;
3808 }
3809 }.bind();
3810 } finally {
3811 restoreCallingIdentity(identityToken);
3812 }
3813 }
3814
3815 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003816 public void isCredentialsUpdateSuggested(
3817 IAccountManagerResponse response,
3818 final Account account,
3819 final String statusToken) {
3820 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3821 Log.v(TAG,
3822 "isCredentialsUpdateSuggested: " + account + ", response " + response
3823 + ", caller's uid " + Binder.getCallingUid()
3824 + ", pid " + Binder.getCallingPid());
3825 }
3826 if (response == null) {
3827 throw new IllegalArgumentException("response is null");
3828 }
3829 if (account == null) {
3830 throw new IllegalArgumentException("account is null");
3831 }
3832 if (TextUtils.isEmpty(statusToken)) {
3833 throw new IllegalArgumentException("status token is empty");
3834 }
3835
Sandra Kwan390c9d22016-01-12 14:13:37 -08003836 int usrId = UserHandle.getCallingUserId();
3837 long identityToken = clearCallingIdentity();
3838 try {
3839 UserAccounts accounts = getUserAccounts(usrId);
3840 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3841 false /* stripAuthTokenFromResult */, account.name,
3842 false /* authDetailsRequired */) {
3843 @Override
3844 protected String toDebugString(long now) {
3845 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
Hui Yu139c2482018-08-10 15:37:51 -07003846 + ", " + account.toSafeString();
Sandra Kwan390c9d22016-01-12 14:13:37 -08003847 }
3848
3849 @Override
3850 public void run() throws RemoteException {
3851 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3852 }
3853
3854 @Override
3855 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003856 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003857 IAccountManagerResponse response = getResponseAndClose();
3858 if (response == null) {
3859 return;
3860 }
3861
3862 if (result == null) {
3863 sendErrorResponse(
3864 response,
3865 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3866 "null bundle");
3867 return;
3868 }
3869
3870 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3871 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3872 + response);
3873 }
3874 // Check to see if an error occurred. We know if an error occurred because all
3875 // error codes are greater than 0.
3876 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3877 sendErrorResponse(response,
3878 result.getInt(AccountManager.KEY_ERROR_CODE),
3879 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3880 return;
3881 }
3882 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3883 sendErrorResponse(
3884 response,
3885 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3886 "no result in response");
3887 return;
3888 }
3889 final Bundle newResult = new Bundle();
3890 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3891 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3892 sendResponse(response, newResult);
3893 }
3894 }.bind();
3895 } finally {
3896 restoreCallingIdentity(identityToken);
3897 }
3898 }
3899
3900 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003901 public void editProperties(IAccountManagerResponse response, final String accountType,
3902 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003903 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003904 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3905 Log.v(TAG, "editProperties: accountType " + accountType
3906 + ", response " + response
3907 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003908 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003909 + ", pid " + Binder.getCallingPid());
3910 }
Fred Quintana382601f2010-03-25 12:25:10 -07003911 if (response == null) throw new IllegalArgumentException("response is null");
3912 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003913 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003914 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3915 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003916 String msg = String.format(
3917 "uid %s cannot edit authenticator properites for account type: %s",
3918 callingUid,
3919 accountType);
3920 throw new SecurityException(msg);
3921 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003922 long identityToken = clearCallingIdentity();
3923 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003924 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003925 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003926 true /* stripAuthTokenFromResult */, null /* accountName */,
3927 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003928 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003929 public void run() throws RemoteException {
3930 mAuthenticator.editProperties(this, mAccountType);
3931 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003932 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003933 protected String toDebugString(long now) {
3934 return super.toDebugString(now) + ", editProperties"
3935 + ", accountType " + accountType;
3936 }
3937 }.bind();
3938 } finally {
3939 restoreCallingIdentity(identityToken);
3940 }
Fred Quintana60307342009-03-24 22:48:12 -07003941 }
3942
Amith Yamasani12747872015-12-07 14:19:49 -08003943 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003944 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3945 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003946 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003947 throw new SecurityException("Can be called only by system UID");
3948 }
3949 Preconditions.checkNotNull(account, "account cannot be null");
3950 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3951 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3952
3953 final int userId = userHandle.getIdentifier();
3954
3955 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3956
3957 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003958 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003959 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003960 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003961 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003962 return false;
3963 }
3964 }
3965
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003966 // Returns package with oldest target SDK for given UID.
3967 private String getPackageNameForUid(int uid) {
3968 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3969 if (ArrayUtils.isEmpty(packageNames)) {
3970 return null;
3971 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003972 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003973 if (packageNames.length == 1) {
3974 return packageName;
3975 }
3976 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003977 int oldestVersion = Integer.MAX_VALUE;
3978 for (String name : packageNames) {
3979 try {
3980 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3981 if (applicationInfo != null) {
3982 int version = applicationInfo.targetSdkVersion;
3983 if (version < oldestVersion) {
3984 oldestVersion = version;
3985 packageName = name;
3986 }
3987 }
3988 } catch (NameNotFoundException e) {
3989 // skip
3990 }
3991 }
3992 return packageName;
3993 }
3994
Svet Ganovf6d424f12016-09-20 20:18:53 -07003995 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3996 int uid) {
3997 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003998 packageName = getPackageNameForUid(uid);
3999 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07004000 return false;
4001 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004002 }
4003
4004 // Use null token which means any token. Having a token means the package
4005 // is trusted by the authenticator, hence it is fine to access the account.
4006 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
4007 return true;
4008 }
4009 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004010 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07004011
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004012 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07004013 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004014 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07004015 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004016 }
4017
4018 @Override
4019 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
4020 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07004021 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004022 throw new SecurityException("Can be called only by system UID");
4023 }
4024
4025 Preconditions.checkNotNull(account, "account cannot be null");
4026 Preconditions.checkNotNull(packageName, "packageName cannot be null");
4027 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
4028
4029 final int userId = userHandle.getIdentifier();
4030
4031 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
4032
4033 final int uid;
4034 try {
4035 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
4036 } catch (NameNotFoundException e) {
4037 Slog.e(TAG, "Unknown package " + packageName);
4038 return null;
4039 }
4040
4041 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
4042
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07004043 final long identity = Binder.clearCallingIdentity();
4044 try {
4045 return PendingIntent.getActivityAsUser(
4046 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
4047 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
4048 null, new UserHandle(userId)).getIntentSender();
4049 } finally {
4050 Binder.restoreCallingIdentity(identity);
4051 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004052 }
4053
4054 private Intent newRequestAccountAccessIntent(Account account, String packageName,
4055 int uid, RemoteCallback callback) {
4056 return newGrantCredentialsPermissionIntent(account, packageName, uid,
4057 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
4058 @Override
4059 public void onResult(Bundle value) throws RemoteException {
4060 handleAuthenticatorResponse(true);
4061 }
4062
4063 @Override
4064 public void onRequestContinued() {
4065 /* ignore */
4066 }
4067
4068 @Override
4069 public void onError(int errorCode, String errorMessage) throws RemoteException {
4070 handleAuthenticatorResponse(false);
4071 }
4072
4073 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
4074 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07004075 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004076 UserHandle.getUserHandleForUid(uid));
4077 if (callback != null) {
4078 Bundle result = new Bundle();
4079 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
4080 callback.sendResult(result);
4081 }
4082 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004083 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004084 }
4085
4086 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08004087 public boolean someUserHasAccount(@NonNull final Account account) {
4088 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
4089 throw new SecurityException("Only system can check for accounts across users");
4090 }
4091 final long token = Binder.clearCallingIdentity();
4092 try {
4093 AccountAndUser[] allAccounts = getAllAccounts();
4094 for (int i = allAccounts.length - 1; i >= 0; i--) {
4095 if (allAccounts[i].account.equals(account)) {
4096 return true;
4097 }
4098 }
4099 return false;
4100 } finally {
4101 Binder.restoreCallingIdentity(token);
4102 }
4103 }
4104
Fred Quintana33269202009-04-20 16:05:10 -07004105 private class GetAccountsByTypeAndFeatureSession extends Session {
4106 private final String[] mFeatures;
4107 private volatile Account[] mAccountsOfType = null;
4108 private volatile ArrayList<Account> mAccountsWithFeatures = null;
4109 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004110 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004111 private final String mPackageName;
sunjianf29d5492017-05-11 15:42:31 -07004112 private final boolean mIncludeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004113
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004114 public GetAccountsByTypeAndFeatureSession(
4115 UserAccounts accounts,
4116 IAccountManagerResponse response,
4117 String type,
4118 String[] features,
4119 int callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004120 String packageName,
4121 boolean includeManagedNotVisible) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004122 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004123 true /* stripAuthTokenFromResult */, null /* accountName */,
4124 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004125 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07004126 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004127 mPackageName = packageName;
sunjianf29d5492017-05-11 15:42:31 -07004128 mIncludeManagedNotVisible = includeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004129 }
4130
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004131 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004132 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004133 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
sunjianf29d5492017-05-11 15:42:31 -07004134 mCallingUid, mPackageName, mIncludeManagedNotVisible);
Fred Quintana33269202009-04-20 16:05:10 -07004135 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07004136 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07004137 mCurrentAccount = 0;
4138
4139 checkAccount();
4140 }
4141
4142 public void checkAccount() {
4143 if (mCurrentAccount >= mAccountsOfType.length) {
4144 sendResult();
4145 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07004146 }
Fred Quintana33269202009-04-20 16:05:10 -07004147
Fred Quintana29e94b82010-03-10 12:11:51 -08004148 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
4149 if (accountAuthenticator == null) {
4150 // It is possible that the authenticator has died, which is indicated by
4151 // mAuthenticator being set to null. If this happens then just abort.
4152 // There is no need to send back a result or error in this case since
4153 // that already happened when mAuthenticator was cleared.
4154 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4155 Log.v(TAG, "checkAccount: aborting session since we are no longer"
4156 + " connected to the authenticator, " + toDebugString());
4157 }
4158 return;
4159 }
Fred Quintana33269202009-04-20 16:05:10 -07004160 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08004161 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07004162 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004163 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07004164 }
4165 }
4166
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004167 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004168 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004169 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07004170 mNumResults++;
4171 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004172 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07004173 return;
4174 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004175 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07004176 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
4177 }
4178 mCurrentAccount++;
4179 checkAccount();
4180 }
4181
4182 public void sendResult() {
4183 IAccountManagerResponse response = getResponseAndClose();
4184 if (response != null) {
4185 try {
4186 Account[] accounts = new Account[mAccountsWithFeatures.size()];
4187 for (int i = 0; i < accounts.length; i++) {
4188 accounts[i] = mAccountsWithFeatures.get(i);
4189 }
Fred Quintana56285a62010-12-02 14:20:51 -08004190 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4191 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
4192 + response);
4193 }
Fred Quintana33269202009-04-20 16:05:10 -07004194 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004195 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004196 response.onResult(result);
4197 } catch (RemoteException e) {
4198 // if the caller is dead then there is no one to care about remote exceptions
4199 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4200 Log.v(TAG, "failure while notifying response", e);
4201 }
4202 }
4203 }
4204 }
4205
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004206 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004207 protected String toDebugString(long now) {
4208 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4209 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4210 }
4211 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004212
Amith Yamasani04e0d262012-02-14 11:50:53 -08004213 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004214 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004215 * @hide
4216 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004217 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004218 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004219 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004220 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004221 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4222 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004223 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004224 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004225 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004226 long identityToken = clearCallingIdentity();
4227 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004228 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004229 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004230 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004231 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004232 opPackageName,
4233 visibleAccountTypes,
4234 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004235 } finally {
4236 restoreCallingIdentity(identityToken);
4237 }
4238 }
4239
Amith Yamasanif29f2362012-04-05 18:29:52 -07004240 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004241 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004242 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004243 * @hide
4244 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004245 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004246 public AccountAndUser[] getRunningAccounts() {
4247 final int[] runningUserIds;
4248 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004249 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004250 } catch (RemoteException e) {
4251 // Running in system_server; should never happen
4252 throw new RuntimeException(e);
4253 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004254 return getAccounts(runningUserIds);
4255 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004256
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004257 /**
4258 * Returns accounts for all users, ignores visibility values.
4259 *
4260 * @hide
4261 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004262 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004263 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004264 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004265 final int[] userIds = new int[users.size()];
4266 for (int i = 0; i < userIds.length; i++) {
4267 userIds[i] = users.get(i).id;
4268 }
4269 return getAccounts(userIds);
4270 }
4271
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004272 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004273 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004274 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004275 for (int userId : userIds) {
4276 UserAccounts userAccounts = getUserAccounts(userId);
4277 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004278 Account[] accounts = getAccountsFromCache(
4279 userAccounts,
4280 null /* type */,
4281 Binder.getCallingUid(),
4282 null /* packageName */,
4283 false /* include managed not visible*/);
4284 for (Account account : accounts) {
4285 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004286 }
4287 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004288
4289 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4290 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004291 }
4292
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004293 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004294 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004295 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004296 int callingUid = Binder.getCallingUid();
4297 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004298 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004299 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004300 }
4301
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004302 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004303 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004304 String type,
4305 int userId,
4306 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004307 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004308 String opPackageName,
4309 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004310 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004311 // Only allow the system process to read accounts of other users
4312 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004313 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004314 && mContext.checkCallingOrSelfPermission(
4315 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4316 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004317 throw new SecurityException("User " + UserHandle.getCallingUserId()
4318 + " trying to get account for " + userId);
4319 }
4320
Fred Quintana56285a62010-12-02 14:20:51 -08004321 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4322 Log.v(TAG, "getAccounts: accountType " + type
4323 + ", caller's uid " + Binder.getCallingUid()
4324 + ", pid " + Binder.getCallingPid());
4325 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004326
4327 // If the original calling app was using account choosing activity
4328 // provided by the framework or authenticator we'll passing in
4329 // the original caller's uid here, which is what should be used for filtering.
4330 List<String> managedTypes =
4331 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4332 if (packageUid != -1 &&
4333 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4334 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004335 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004336 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004337 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004338 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4339 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004340 if (visibleAccountTypes.isEmpty()
4341 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004342 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004343 } else if (visibleAccountTypes.contains(type)) {
4344 // Prune the list down to just the requested type.
4345 visibleAccountTypes = new ArrayList<>();
4346 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004347 } // else aggregate all the visible accounts (it won't matter if the
4348 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004349
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004350 long identityToken = clearCallingIdentity();
4351 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004352 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004353 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004354 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004355 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004356 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004357 visibleAccountTypes,
4358 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004359 } finally {
4360 restoreCallingIdentity(identityToken);
4361 }
4362 }
4363
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004364 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004365 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004366 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004367 int callingUid,
4368 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004369 List<String> visibleAccountTypes,
4370 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004371 ArrayList<Account> visibleAccounts = new ArrayList<>();
4372 for (String visibleType : visibleAccountTypes) {
4373 Account[] accountsForType = getAccountsFromCache(
4374 userAccounts, visibleType, callingUid, callingPackage,
4375 includeUserManagedNotVisible);
4376 if (accountsForType != null) {
4377 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004378 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004379 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004380 Account[] result = new Account[visibleAccounts.size()];
4381 for (int i = 0; i < visibleAccounts.size(); i++) {
4382 result[i] = visibleAccounts.get(i);
4383 }
4384 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004385 }
4386
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004387 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004388 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4389 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004390 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004391 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004392 for (Account account : accounts) {
4393 addSharedAccountAsUser(account, userId);
4394 }
4395 }
4396
4397 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004398 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004399 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004400 accounts.accountsDb.deleteSharedAccount(account);
4401 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004402 if (accountId < 0) {
Hui Yu139c2482018-08-10 15:37:51 -07004403 Log.w(TAG, "insertAccountIntoDatabase: " + account.toSafeString()
Amith Yamasani67df64b2012-12-14 12:09:36 -08004404 + ", skipping the DB insert failed");
4405 return false;
4406 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004407 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4408 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004409 return true;
4410 }
4411
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004412 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4413 userId = handleIncomingUser(userId);
4414 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004415 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4416 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004417 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004418 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004419 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004420 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004421 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004422 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004423 }
4424 return r > 0;
4425 }
4426
Amith Yamasani67df64b2012-12-14 12:09:36 -08004427 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004428 return removeSharedAccountAsUser(account, userId, getCallingUid());
4429 }
4430
4431 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004432 userId = handleIncomingUser(userId);
4433 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004434 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4435 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004436 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004437 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004438 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004439 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004440 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004441 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004442 }
4443
Amith Yamasani67df64b2012-12-14 12:09:36 -08004444 public Account[] getSharedAccountsAsUser(int userId) {
4445 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004446 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004447 synchronized (accounts.dbLock) {
4448 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4449 Account[] accountArray = new Account[accountList.size()];
4450 accountList.toArray(accountArray);
4451 return accountArray;
4452 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004453 }
4454
4455 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004456 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004457 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004458 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004459 }
4460
Amith Yamasani27db4682013-03-30 17:07:47 -07004461 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004462 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004463 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004464 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004465 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004466 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004467 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4468 + callingUid + " with uid=" + uid);
4469 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004470 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004471 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004472 }
4473
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004474 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004475 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004476 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4477 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004478 int callingUid = Binder.getCallingUid();
4479 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004480 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004481 int packageUid = -1;
4482 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004483 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4484 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004485 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004486 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004487 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004488 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004489 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4490 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004491 }
sunjiand62dc392017-06-01 12:05:59 -07004492 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) && type == null) {
4493 return getAccountsAsUserForPackage(type, userId,
4494 packageName, packageUid, opPackageName, false /* includeUserManagedNotVisible */);
4495 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004496 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004497 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004498 }
4499
sunjianf29d5492017-05-11 15:42:31 -07004500 private boolean needToStartChooseAccountActivity(Account[] accounts, String callingPackage) {
4501 if (accounts.length < 1) return false;
4502 if (accounts.length > 1) return true;
4503 Account account = accounts[0];
4504 UserAccounts userAccounts = getUserAccounts(UserHandle.getCallingUserId());
4505 int visibility = resolveAccountVisibility(account, callingPackage, userAccounts);
4506 if (visibility == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE) return true;
4507 return false;
4508 }
4509
4510 private void startChooseAccountActivityWithAccounts(
sunjianbdabd402017-06-06 17:54:07 -07004511 IAccountManagerResponse response, Account[] accounts, String callingPackage) {
sunjianf29d5492017-05-11 15:42:31 -07004512 Intent intent = new Intent(mContext, ChooseAccountActivity.class);
4513 intent.putExtra(AccountManager.KEY_ACCOUNTS, accounts);
4514 intent.putExtra(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE,
4515 new AccountManagerResponse(response));
sunjianbdabd402017-06-06 17:54:07 -07004516 intent.putExtra(AccountManager.KEY_ANDROID_PACKAGE_NAME, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004517
4518 mContext.startActivityAsUser(intent, UserHandle.of(UserHandle.getCallingUserId()));
4519 }
4520
4521 private void handleGetAccountsResult(
4522 IAccountManagerResponse response,
4523 Account[] accounts,
4524 String callingPackage) {
4525
4526 if (needToStartChooseAccountActivity(accounts, callingPackage)) {
sunjianbdabd402017-06-06 17:54:07 -07004527 startChooseAccountActivityWithAccounts(response, accounts, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004528 return;
4529 }
4530 if (accounts.length == 1) {
4531 Bundle bundle = new Bundle();
4532 bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accounts[0].name);
4533 bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accounts[0].type);
4534 onResult(response, bundle);
4535 return;
4536 }
4537 // No qualified account exists, return an empty Bundle.
4538 onResult(response, new Bundle());
4539 }
4540
4541 @Override
4542 public void getAccountByTypeAndFeatures(
4543 IAccountManagerResponse response,
4544 String accountType,
4545 String[] features,
4546 String opPackageName) {
4547
4548 int callingUid = Binder.getCallingUid();
4549 mAppOpsManager.checkPackage(callingUid, opPackageName);
4550 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4551 Log.v(TAG, "getAccount: accountType " + accountType
4552 + ", response " + response
4553 + ", features " + Arrays.toString(features)
4554 + ", caller's uid " + callingUid
4555 + ", pid " + Binder.getCallingPid());
4556 }
4557 if (response == null) throw new IllegalArgumentException("response is null");
4558 if (accountType == null) throw new IllegalArgumentException("accountType is null");
4559
4560 int userId = UserHandle.getCallingUserId();
4561
4562 long identityToken = clearCallingIdentity();
4563 try {
4564 UserAccounts userAccounts = getUserAccounts(userId);
4565 if (ArrayUtils.isEmpty(features)) {
4566 Account[] accountsWithManagedNotVisible = getAccountsFromCache(
4567 userAccounts, accountType, callingUid, opPackageName,
4568 true /* include managed not visible */);
4569 handleGetAccountsResult(
4570 response, accountsWithManagedNotVisible, opPackageName);
4571 return;
4572 }
4573
4574 IAccountManagerResponse retrieveAccountsResponse =
4575 new IAccountManagerResponse.Stub() {
4576 @Override
4577 public void onResult(Bundle value) throws RemoteException {
4578 Parcelable[] parcelables = value.getParcelableArray(
4579 AccountManager.KEY_ACCOUNTS);
4580 Account[] accounts = new Account[parcelables.length];
4581 for (int i = 0; i < parcelables.length; i++) {
4582 accounts[i] = (Account) parcelables[i];
4583 }
4584 handleGetAccountsResult(
4585 response, accounts, opPackageName);
4586 }
4587
4588 @Override
4589 public void onError(int errorCode, String errorMessage)
4590 throws RemoteException {
4591 // Will not be called in this case.
4592 }
4593 };
4594 new GetAccountsByTypeAndFeatureSession(
4595 userAccounts,
4596 retrieveAccountsResponse,
4597 accountType,
4598 features,
4599 callingUid,
4600 opPackageName,
4601 true /* include managed not visible */).bind();
4602 } finally {
4603 restoreCallingIdentity(identityToken);
4604 }
4605 }
4606
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004607 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004608 public void getAccountsByFeatures(
4609 IAccountManagerResponse response,
4610 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004611 String[] features,
4612 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004613 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004614 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004615 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4616 Log.v(TAG, "getAccounts: accountType " + type
4617 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004618 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004619 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004620 + ", pid " + Binder.getCallingPid());
4621 }
Fred Quintana382601f2010-03-25 12:25:10 -07004622 if (response == null) throw new IllegalArgumentException("response is null");
4623 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004624 int userId = UserHandle.getCallingUserId();
4625
Svetoslavf3f02ac2015-09-08 14:36:35 -07004626 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4627 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004628 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004629 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004630 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004631 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004632 try {
4633 response.onResult(result);
4634 } catch (RemoteException e) {
4635 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4636 }
4637 return;
4638 }
sunjianf29d5492017-05-11 15:42:31 -07004639
Fred Quintana33269202009-04-20 16:05:10 -07004640 long identityToken = clearCallingIdentity();
4641 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004642 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004643 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004644 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4645 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004646 Bundle result = new Bundle();
4647 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4648 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004649 return;
4650 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004651 new GetAccountsByTypeAndFeatureSession(
4652 userAccounts,
4653 response,
4654 type,
4655 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004656 callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004657 opPackageName,
4658 false /* include managed not visible */).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004659 } finally {
4660 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004661 }
4662 }
4663
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004664 @Override
4665 public void onAccountAccessed(String token) throws RemoteException {
4666 final int uid = Binder.getCallingUid();
4667 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4668 return;
4669 }
4670 final int userId = UserHandle.getCallingUserId();
4671 final long identity = Binder.clearCallingIdentity();
4672 try {
4673 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4674 if (Objects.equals(account.getAccessId(), token)) {
4675 // An app just accessed the account. At this point it knows about
4676 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004677 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004678 if (!hasAccountAccess(account, null, uid)) {
4679 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4680 uid, true);
4681 }
4682 }
4683 }
4684 } finally {
4685 Binder.restoreCallingIdentity(identity);
4686 }
4687 }
4688
Hongming Jin8e2bfc12018-05-30 11:01:06 -07004689 @Override
4690 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4691 FileDescriptor err, String[] args, ShellCallback callback,
4692 ResultReceiver resultReceiver) {
4693 new AccountManagerServiceShellCommand(this).exec(this, in, out, err, args,
4694 callback, resultReceiver);
4695 }
4696
Fred Quintanaa698f422009-04-08 19:14:54 -07004697 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004698 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004699 IAccountManagerResponse mResponse;
4700 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004701 final boolean mExpectActivityLaunch;
4702 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004703 final String mAccountName;
4704 // Indicates if we need to add auth details(like last credential time)
4705 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004706 // If set, we need to update the last authenticated time. This is
4707 // currently
4708 // used on
4709 // successful confirming credentials.
4710 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004711
Fred Quintana33269202009-04-20 16:05:10 -07004712 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004713 private int mNumRequestContinued = 0;
4714 private int mNumErrors = 0;
4715
Fred Quintana60307342009-03-24 22:48:12 -07004716 IAccountAuthenticator mAuthenticator = null;
4717
Fred Quintana8570f742010-02-18 10:32:54 -08004718 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004719 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004720
Amith Yamasani04e0d262012-02-14 11:50:53 -08004721 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004722 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4723 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004724 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4725 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4726 }
4727
4728 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4729 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4730 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004731 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004732 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004733 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004734 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004735 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004736 mResponse = response;
4737 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004738 mExpectActivityLaunch = expectActivityLaunch;
4739 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004740 mAccountName = accountName;
4741 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004742 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004743
Fred Quintanaa698f422009-04-08 19:14:54 -07004744 synchronized (mSessions) {
4745 mSessions.put(toString(), this);
4746 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004747 if (response != null) {
4748 try {
4749 response.asBinder().linkToDeath(this, 0 /* flags */);
4750 } catch (RemoteException e) {
4751 mResponse = null;
4752 binderDied();
4753 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004754 }
Fred Quintana60307342009-03-24 22:48:12 -07004755 }
4756
Fred Quintanaa698f422009-04-08 19:14:54 -07004757 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004758 if (mResponse == null) {
4759 // this session has already been closed
4760 return null;
4761 }
Fred Quintana60307342009-03-24 22:48:12 -07004762 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004763 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004764 return response;
4765 }
4766
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004767 /**
4768 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4769 * security policy.
4770 *
4771 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004772 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004773 * supplied entries in the system Settings app.
4774 */
tiansiminga8868bf2017-09-20 13:59:13 +08004775 protected boolean checkKeyIntent(int authUid, Intent intent) {
Jeff Sharkeyd722e782017-06-12 17:33:07 -06004776 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION
4777 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
4778 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4779 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION));
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004780 long bid = Binder.clearCallingIdentity();
4781 try {
4782 PackageManager pm = mContext.getPackageManager();
4783 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
tiansiminga8868bf2017-09-20 13:59:13 +08004784 if (resolveInfo == null) {
4785 return false;
4786 }
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004787 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4788 int targetUid = targetActivityInfo.applicationInfo.uid;
Dan Cashman303c4bb2018-04-10 07:41:16 -07004789 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004790 if (!isExportedSystemActivity(targetActivityInfo)
Dan Cashman303c4bb2018-04-10 07:41:16 -07004791 && !pmi.hasSignatureCapability(
4792 targetUid, authUid,
4793 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004794 String pkgName = targetActivityInfo.packageName;
4795 String activityName = targetActivityInfo.name;
4796 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4797 + "does not share a signature with the supplying authenticator (%s).";
tiansiminga8868bf2017-09-20 13:59:13 +08004798 Log.e(TAG, String.format(tmpl, activityName, pkgName, mAccountType));
4799 return false;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004800 }
tiansiminga8868bf2017-09-20 13:59:13 +08004801 return true;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004802 } finally {
4803 Binder.restoreCallingIdentity(bid);
4804 }
4805 }
4806
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004807 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4808 String className = activityInfo.name;
4809 return "android".equals(activityInfo.packageName) &&
4810 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4811 || CantAddAccountActivity.class.getName().equals(className));
4812 }
4813
Fred Quintanaa698f422009-04-08 19:14:54 -07004814 private void close() {
4815 synchronized (mSessions) {
4816 if (mSessions.remove(toString()) == null) {
4817 // the session was already closed, so bail out now
4818 return;
4819 }
4820 }
4821 if (mResponse != null) {
4822 // stop listening for response deaths
4823 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4824
4825 // clear this so that we don't accidentally send any further results
4826 mResponse = null;
4827 }
4828 cancelTimeout();
4829 unbind();
4830 }
4831
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004832 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004833 public void binderDied() {
4834 mResponse = null;
4835 close();
4836 }
4837
4838 protected String toDebugString() {
4839 return toDebugString(SystemClock.elapsedRealtime());
4840 }
4841
4842 protected String toDebugString(long now) {
4843 return "Session: expectLaunch " + mExpectActivityLaunch
4844 + ", connected " + (mAuthenticator != null)
4845 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4846 + "/" + mNumErrors + ")"
4847 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4848 }
4849
Fred Quintana60307342009-03-24 22:48:12 -07004850 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004851 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4852 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4853 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004854 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004855 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004856 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004857 }
4858 }
4859
4860 private void unbind() {
4861 if (mAuthenticator != null) {
4862 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004863 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004864 }
4865 }
4866
Fred Quintana60307342009-03-24 22:48:12 -07004867 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004868 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004869 }
4870
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004871 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004872 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004873 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004874 try {
4875 run();
4876 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004877 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004878 "remote exception");
4879 }
Fred Quintana60307342009-03-24 22:48:12 -07004880 }
4881
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004882 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004883 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004884 mAuthenticator = null;
4885 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004886 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004887 try {
4888 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4889 "disconnected");
4890 } catch (RemoteException e) {
4891 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4892 Log.v(TAG, "Session.onServiceDisconnected: "
4893 + "caught RemoteException while responding", e);
4894 }
4895 }
Fred Quintana60307342009-03-24 22:48:12 -07004896 }
4897 }
4898
Fred Quintanab839afc2009-10-14 15:57:28 -07004899 public abstract void run() throws RemoteException;
4900
Fred Quintana60307342009-03-24 22:48:12 -07004901 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004902 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004903 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004904 try {
4905 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4906 "timeout");
4907 } catch (RemoteException e) {
4908 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4909 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4910 e);
4911 }
4912 }
Fred Quintana60307342009-03-24 22:48:12 -07004913 }
4914 }
4915
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004916 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004917 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004918 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004919 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004920 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004921 if (result != null) {
4922 boolean isSuccessfulConfirmCreds = result.getBoolean(
4923 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004924 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004925 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4926 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004927 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004928 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4929 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004930 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004931 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004932 if (needUpdate || mAuthDetailsRequired) {
4933 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4934 if (needUpdate && accountPresent) {
4935 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4936 }
4937 if (mAuthDetailsRequired) {
4938 long lastAuthenticatedTime = -1;
4939 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004940 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004941 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004942 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004943 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004944 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004945 lastAuthenticatedTime);
4946 }
4947 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004948 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004949 if (result != null
4950 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
tiansiminga8868bf2017-09-20 13:59:13 +08004951 if (!checkKeyIntent(
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004952 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08004953 intent)) {
4954 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
4955 "invalid intent in bundle returned");
4956 return;
4957 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004958 }
4959 if (result != null
4960 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004961 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4962 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004963 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4964 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004965 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4966 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004967 }
Fred Quintana60307342009-03-24 22:48:12 -07004968 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004969 IAccountManagerResponse response;
4970 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004971 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004972 response = mResponse;
4973 } else {
4974 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004975 }
Fred Quintana60307342009-03-24 22:48:12 -07004976 if (response != null) {
4977 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004978 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004979 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4980 Log.v(TAG, getClass().getSimpleName()
4981 + " calling onError() on response " + response);
4982 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004983 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004984 "null bundle returned");
4985 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004986 if (mStripAuthTokenFromResult) {
4987 result.remove(AccountManager.KEY_AUTHTOKEN);
4988 }
Fred Quintana56285a62010-12-02 14:20:51 -08004989 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4990 Log.v(TAG, getClass().getSimpleName()
4991 + " calling onResult() on response " + response);
4992 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004993 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4994 (intent == null)) {
4995 // All AccountManager error codes are greater than 0
4996 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4997 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4998 } else {
4999 response.onResult(result);
5000 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005001 }
Fred Quintana60307342009-03-24 22:48:12 -07005002 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07005003 // if the caller is dead then there is no one to care about remote exceptions
5004 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5005 Log.v(TAG, "failure while notifying response", e);
5006 }
Fred Quintana60307342009-03-24 22:48:12 -07005007 }
5008 }
5009 }
Fred Quintana60307342009-03-24 22:48:12 -07005010
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005011 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07005012 public void onRequestContinued() {
5013 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07005014 }
5015
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005016 @Override
Fred Quintana60307342009-03-24 22:48:12 -07005017 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07005018 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07005019 IAccountManagerResponse response = getResponseAndClose();
5020 if (response != null) {
5021 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08005022 Log.v(TAG, getClass().getSimpleName()
5023 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07005024 }
5025 try {
5026 response.onError(errorCode, errorMessage);
5027 } catch (RemoteException e) {
5028 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5029 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
5030 }
5031 }
5032 } else {
5033 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5034 Log.v(TAG, "Session.onError: already closed");
5035 }
Fred Quintana60307342009-03-24 22:48:12 -07005036 }
5037 }
Fred Quintanab839afc2009-10-14 15:57:28 -07005038
5039 /**
5040 * find the component name for the authenticator and initiate a bind
5041 * if no authenticator or the bind fails then return false, otherwise return true
5042 */
5043 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005044 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
5045 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
5046 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07005047 if (authenticatorInfo == null) {
5048 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5049 Log.v(TAG, "there is no authenticator for " + authenticatorType
5050 + ", bailing out");
5051 }
5052 return false;
5053 }
5054
Jeff Sharkeyce18c812016-04-27 16:00:41 -06005055 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06005056 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07005057 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
5058 + " which isn't encryption aware");
5059 return false;
5060 }
5061
Fred Quintanab839afc2009-10-14 15:57:28 -07005062 Intent intent = new Intent();
5063 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
5064 intent.setComponent(authenticatorInfo.componentName);
5065 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5066 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
5067 }
Hongming Jin8e2bfc12018-05-30 11:01:06 -07005068 int flags = Context.BIND_AUTO_CREATE;
5069 if (mAuthenticatorCache.getBindInstantServiceAllowed(mAccounts.userId)) {
5070 flags |= Context.BIND_ALLOW_INSTANT;
5071 }
5072 if (!mContext.bindServiceAsUser(intent, this, flags, UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07005073 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5074 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
5075 }
5076 return false;
5077 }
5078
Fred Quintanab839afc2009-10-14 15:57:28 -07005079 return true;
5080 }
Fred Quintana60307342009-03-24 22:48:12 -07005081 }
5082
Svet Ganov5d09c992016-09-07 09:57:41 -07005083 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07005084 MessageHandler(Looper looper) {
5085 super(looper);
5086 }
Costin Manolache3348f142009-09-29 18:58:36 -07005087
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07005088 @Override
Fred Quintana60307342009-03-24 22:48:12 -07005089 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07005090 switch (msg.what) {
5091 case MESSAGE_TIMED_OUT:
5092 Session session = (Session)msg.obj;
5093 session.onTimedOut();
5094 break;
5095
Amith Yamasani5be347b2013-03-31 17:44:31 -07005096 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00005097 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07005098 break;
5099
Fred Quintana60307342009-03-24 22:48:12 -07005100 default:
5101 throw new IllegalStateException("unhandled message: " + msg.what);
5102 }
5103 }
5104 }
5105
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005106 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005107 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005108 }
5109
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005110 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005111 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005112 }
5113
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005114 /*
5115 * This function receives an opened writable database.
5116 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005117 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005118 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005119 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005120 }
5121
5122 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005123 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005124 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005125 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005126 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005127
5128 class LogRecordTask implements Runnable {
5129 private final String action;
5130 private final String tableName;
5131 private final long accountId;
5132 private final UserAccounts userAccount;
5133 private final int callingUid;
5134 private final long userDebugDbInsertionPoint;
5135
5136 LogRecordTask(final String action,
5137 final String tableName,
5138 final long accountId,
5139 final UserAccounts userAccount,
5140 final int callingUid,
5141 final long userDebugDbInsertionPoint) {
5142 this.action = action;
5143 this.tableName = tableName;
5144 this.accountId = accountId;
5145 this.userAccount = userAccount;
5146 this.callingUid = callingUid;
5147 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
5148 }
5149
Andrew Scullc7770d62017-05-22 17:49:58 +01005150 @Override
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005151 public void run() {
Dmitry Dementyev47443192018-10-24 13:31:59 -07005152 synchronized (userAccount.accountsDb.mDebugStatementLock) {
5153 SQLiteStatement logStatement = userAccount.accountsDb.getStatementForLogging();
5154 if (logStatement == null) {
5155 return; // Can't log.
5156 }
5157 logStatement.bindLong(1, accountId);
5158 logStatement.bindString(2, action);
5159 logStatement.bindString(3, mDateFormat.format(new Date()));
5160 logStatement.bindLong(4, callingUid);
5161 logStatement.bindString(5, tableName);
5162 logStatement.bindLong(6, userDebugDbInsertionPoint);
5163 try {
5164 logStatement.execute();
5165 } catch (IllegalStateException e) {
5166 // Guard against crash, DB can already be closed
5167 // since this statement is executed on a handler thread
5168 Slog.w(TAG, "Failed to insert a log record. accountId=" + accountId
5169 + " action=" + action + " tableName=" + tableName + " Error: " + e);
5170 } finally {
5171 logStatement.clearBindings();
5172 }
Tetsutoki Shiozawabe2d96a2017-10-24 18:44:00 +09005173 }
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005174 }
5175 }
Dmitry Dementyev47443192018-10-24 13:31:59 -07005176 long insertionPoint = userAccount.accountsDb.reserveDebugDbInsertionPoint();
5177 if (insertionPoint != -1) {
5178 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
5179 callingUid, insertionPoint);
5180 mHandler.post(logTask);
5181 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005182 }
5183
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005184 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005185 return asBinder();
5186 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005187
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005188 /**
5189 * Searches array of arguments for the specified string
5190 * @param args array of argument strings
5191 * @param value value to search for
5192 * @return true if the value is contained in the array
5193 */
5194 private static boolean scanArgs(String[] args, String value) {
5195 if (args != null) {
5196 for (String arg : args) {
5197 if (value.equals(arg)) {
5198 return true;
5199 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005200 }
5201 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005202 return false;
5203 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005204
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005205 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005206 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005207 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005208 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005209 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005210
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005211 final List<UserInfo> users = getUserManager().getUsers();
5212 for (UserInfo user : users) {
5213 ipw.println("User " + user + ":");
5214 ipw.increaseIndent();
5215 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5216 ipw.println();
5217 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005218 }
5219 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005220
Amith Yamasani04e0d262012-02-14 11:50:53 -08005221 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5222 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005223 if (isCheckinRequest) {
5224 // This is a checkin request. *Only* upload the account types and the count of
5225 // each.
5226 synchronized (userAccounts.dbLock) {
5227 userAccounts.accountsDb.dumpDeAccountsTable(fout);
5228 }
5229 } else {
5230 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
5231 Process.SYSTEM_UID, null /* packageName */, false);
5232 fout.println("Accounts: " + accounts.length);
5233 for (Account account : accounts) {
Makoto Onukib9425222019-01-23 11:35:43 -08005234 fout.println(" " + account.toString());
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005235 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005236
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005237 // Add debug information.
5238 fout.println();
5239 synchronized (userAccounts.dbLock) {
5240 userAccounts.accountsDb.dumpDebugTable(fout);
5241 }
5242 fout.println();
5243 synchronized (mSessions) {
5244 final long now = SystemClock.elapsedRealtime();
5245 fout.println("Active Sessions: " + mSessions.size());
5246 for (Session session : mSessions.values()) {
5247 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005248 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005249 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005250
5251 fout.println();
5252 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Tony Mak6d14d772017-07-13 17:49:46 +08005253
5254 boolean isUserUnlocked;
5255 synchronized (mUsers) {
5256 isUserUnlocked = isLocalUnlockedUser(userAccounts.userId);
5257 }
5258 // Following logs are printed only when user is unlocked.
5259 if (!isUserUnlocked) {
5260 return;
5261 }
5262 fout.println();
5263 synchronized (userAccounts.dbLock) {
5264 Map<Account, Map<String, Integer>> allVisibilityValues =
5265 userAccounts.accountsDb.findAllVisibilityValues();
5266 fout.println("Account visibility:");
5267 for (Account account : allVisibilityValues.keySet()) {
5268 fout.println(" " + account.name);
5269 Map<String, Integer> visibilities = allVisibilityValues.get(account);
5270 for (Entry<String, Integer> entry : visibilities.entrySet()) {
5271 fout.println(" " + entry.getKey() + ", " + entry.getValue());
5272 }
5273 }
5274 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005275 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005276 }
5277
Amith Yamasani04e0d262012-02-14 11:50:53 -08005278 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005279 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005280 long identityToken = clearCallingIdentity();
5281 try {
5282 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5283 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5284 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005285
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005286 if (intent.getComponent() != null &&
5287 GrantCredentialsPermissionActivity.class.getName().equals(
5288 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005289 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005290 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005291 Context contextForUser = getContextForUser(new UserHandle(userId));
Chris Wren717a8812017-03-31 15:34:39 -04005292 final NotificationId id = getSigninRequiredNotificationId(accounts, account);
5293 intent.addCategory(id.mTag);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005294
Fred Quintana33f889a2009-09-14 17:31:26 -07005295 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005296 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05005297 Notification n =
5298 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005299 .setWhen(0)
5300 .setSmallIcon(android.R.drawable.stat_sys_warning)
5301 .setColor(contextForUser.getColor(
5302 com.android.internal.R.color.system_notification_accent_color))
5303 .setContentTitle(String.format(notificationTitleFormat, account.name))
5304 .setContentText(message)
5305 .setContentIntent(PendingIntent.getActivityAsUser(
5306 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005307 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005308 .build();
Chris Wren717a8812017-03-31 15:34:39 -04005309 installNotification(id, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005310 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005311 } finally {
5312 restoreCallingIdentity(identityToken);
5313 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005314 }
5315
Chris Wren717a8812017-03-31 15:34:39 -04005316 private void installNotification(NotificationId id, final Notification notification,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005317 String packageName, int userId) {
5318 final long token = clearCallingIdentity();
5319 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005320 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005321 try {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04005322 // The calling uid must match either the package or op package, so use an op
5323 // package that matches the cleared calling identity.
5324 notificationManager.enqueueNotificationWithTag(packageName, "android",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04005325 id.mTag, id.mId, notification, userId);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005326 } catch (RemoteException e) {
5327 /* ignore - local call */
5328 }
5329 } finally {
5330 Binder.restoreCallingIdentity(token);
5331 }
Fred Quintana56285a62010-12-02 14:20:51 -08005332 }
5333
Chris Wren717a8812017-03-31 15:34:39 -04005334 private void cancelNotification(NotificationId id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005335 cancelNotification(id, mContext.getPackageName(), user);
5336 }
5337
Chris Wren717a8812017-03-31 15:34:39 -04005338 private void cancelNotification(NotificationId id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005339 long identityToken = clearCallingIdentity();
5340 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005341 INotificationManager service = mInjector.getNotificationManager();
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005342 service.cancelNotificationWithTag(
5343 packageName, "android", id.mTag, id.mId, user.getIdentifier());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005344 } catch (RemoteException e) {
5345 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005346 } finally {
5347 restoreCallingIdentity(identityToken);
5348 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005349 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005350
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005351 private boolean isPermittedForPackage(String packageName, int userId, String... permissions) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005352 final long identity = Binder.clearCallingIdentity();
5353 try {
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005354 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005355 IPackageManager pm = ActivityThread.getPackageManager();
5356 for (String perm : permissions) {
5357 if (pm.checkPermission(perm, packageName, userId)
5358 == PackageManager.PERMISSION_GRANTED) {
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005359 // Checks runtime permission revocation.
5360 final int opCode = AppOpsManager.permissionToOpCode(perm);
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005361 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.checkOpNoThrow(
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005362 opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
5363 return true;
5364 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005365 }
5366 }
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005367 } catch (NameNotFoundException | RemoteException e) {
5368 // Assume permission is not granted if an error accrued.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005369 } finally {
5370 Binder.restoreCallingIdentity(identity);
5371 }
5372 return false;
5373 }
5374
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005375 /**
5376 * Checks that package has at least one of given permissions and makes note of app
5377 * performing the action.
5378 */
5379 private boolean checkPermissionAndNote(String opPackageName, int callingUid,
5380 String... permissions) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005381 for (String perm : permissions) {
5382 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5383 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5384 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5385 }
5386 final int opCode = AppOpsManager.permissionToOpCode(perm);
Tony Mak58f28152017-09-20 21:23:48 +01005387 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOpNoThrow(
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005388 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5389 return true;
5390 }
5391 }
5392 }
5393 return false;
5394 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005395
Amith Yamasani67df64b2012-12-14 12:09:36 -08005396 private int handleIncomingUser(int userId) {
5397 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005398 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005399 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5400 } catch (RemoteException re) {
5401 // Shouldn't happen, local.
5402 }
5403 return userId;
5404 }
5405
Christopher Tateccbf84f2013-05-08 15:25:41 -07005406 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005407 String[] packages;
5408 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005409 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005410 packages = mPackageManager.getPackagesForUid(callingUid);
sunjian9ae597b62017-08-14 15:45:04 -07005411 if (packages == null) {
5412 Log.d(TAG, "No packages for callingUid " + callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005413 return false;
5414 }
sunjian9ae597b62017-08-14 15:45:04 -07005415 for (String name : packages) {
5416 try {
5417 PackageInfo packageInfo =
5418 mPackageManager.getPackageInfo(name, 0 /* flags */);
5419 if (packageInfo != null
5420 && (packageInfo.applicationInfo.privateFlags
5421 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5422 return true;
5423 }
5424 } catch (PackageManager.NameNotFoundException e) {
5425 Log.d(TAG, "Package not found " + e.getMessage());
5426 }
5427 }
5428 } finally {
5429 Binder.restoreCallingIdentity(identityToken);
Fred Quintana7be59642009-08-24 18:29:25 -07005430 }
5431 return false;
5432 }
5433
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005434 private boolean permissionIsGranted(
5435 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005436 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5437 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5438 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5439 }
5440 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005441 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005442
5443 if (isPrivileged(callerUid)) {
5444 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5445 Log.v(TAG, "Access to " + account + " granted calling uid "
5446 + callerUid + " privileged");
5447 }
5448 return true;
5449 }
5450 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5451 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5452 Log.v(TAG, "Access to " + account + " granted calling uid "
5453 + callerUid + " manages the account");
5454 }
5455 return true;
5456 }
5457 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5458 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5459 Log.v(TAG, "Access to " + account + " granted calling uid "
5460 + callerUid + " user granted access");
5461 }
5462 return true;
5463 }
5464
5465 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5466 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5467 }
5468
5469 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005470 }
5471
Svetoslavf3f02ac2015-09-08 14:36:35 -07005472 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5473 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005474 if (accountType == null) {
5475 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005476 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005477 return getTypesVisibleToCaller(callingUid, userId,
5478 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005479 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005480 }
5481
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005482 // Method checks visibility for applications targeing API level below {@link
5483 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005484 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005485 private boolean checkGetAccountsPermission(String packageName, int userId) {
5486 return isPermittedForPackage(packageName, userId, Manifest.permission.GET_ACCOUNTS,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005487 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5488 }
5489
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005490 private boolean checkReadContactsPermission(String packageName, int userId) {
5491 return isPermittedForPackage(packageName, userId, Manifest.permission.READ_CONTACTS);
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005492 }
5493
5494 // Heuristic to check that account type may be associated with some contacts data and
5495 // therefore READ_CONTACTS permission grants the access to account by default.
5496 private boolean accountTypeManagesContacts(String accountType, int userId) {
5497 if (accountType == null) {
5498 return false;
5499 }
5500 long identityToken = Binder.clearCallingIdentity();
5501 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5502 try {
5503 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5504 } finally {
5505 Binder.restoreCallingIdentity(identityToken);
5506 }
5507 // Check contacts related permissions for authenticator.
5508 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5509 : serviceInfos) {
5510 if (accountType.equals(serviceInfo.type.type)) {
Dmitry Dementyev6fb038c2019-04-15 11:44:00 -07005511 return isPermittedForPackage(serviceInfo.type.packageName, userId,
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005512 Manifest.permission.WRITE_CONTACTS);
5513 }
5514 }
5515 return false;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005516 }
5517
5518 /**
5519 * Method checks package uid and signature with Authenticator which manages accountType.
5520 *
5521 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5522 * SIGNATURE_CHECK_MISMATCH otherwise.
5523 */
5524 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5525 if (accountType == null) {
5526 return SIGNATURE_CHECK_MISMATCH;
5527 }
5528
5529 long identityToken = Binder.clearCallingIdentity();
5530 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5531 try {
5532 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5533 } finally {
5534 Binder.restoreCallingIdentity(identityToken);
5535 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005536 // Check for signature match with Authenticator.LocalServices.getService(PackageManagerInternal.class);
5537 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005538 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5539 : serviceInfos) {
5540 if (accountType.equals(serviceInfo.type.type)) {
5541 if (serviceInfo.uid == callingUid) {
5542 return SIGNATURE_CHECK_UID_MATCH;
5543 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005544 if (pmi.hasSignatureCapability(
5545 serviceInfo.uid, callingUid,
5546 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005547 return SIGNATURE_CHECK_MATCH;
5548 }
5549 }
5550 }
5551 return SIGNATURE_CHECK_MISMATCH;
5552 }
5553
5554 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005555 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5556 if (accountType == null) {
5557 return false;
5558 } else {
5559 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5560 }
5561 }
5562
Svetoslavf3f02ac2015-09-08 14:36:35 -07005563 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5564 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005565 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005566 }
5567
5568 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005569 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005570 }
5571
5572 private List<String> getTypesForCaller(
5573 int callingUid, int userId, boolean isOtherwisePermitted) {
5574 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005575 long identityToken = Binder.clearCallingIdentity();
5576 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5577 try {
5578 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5579 } finally {
5580 Binder.restoreCallingIdentity(identityToken);
5581 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005582
5583 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005584 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005585 serviceInfos) {
Dan Cashman303c4bb2018-04-10 07:41:16 -07005586 if (isOtherwisePermitted || pmi.hasSignatureCapability(
5587 serviceInfo.uid, callingUid,
5588 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005589 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005590 }
5591 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005592 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005593 }
5594
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005595 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5596 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5597 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5598 if (account.name.equals(accountName)) {
5599 return true;
5600 }
5601 }
5602 }
5603 return false;
5604 }
5605
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005606 private static void checkManageUsersPermission(String message) {
5607 if (ActivityManager.checkComponentPermission(
5608 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5609 != PackageManager.PERMISSION_GRANTED) {
5610 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5611 }
5612 }
5613
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005614 private static void checkManageOrCreateUsersPermission(String message) {
5615 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5616 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5617 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5618 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5619 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5620 + message);
5621 }
5622 }
5623
Amith Yamasani04e0d262012-02-14 11:50:53 -08005624 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5625 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005626 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005627 return true;
5628 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005629 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005630 synchronized (accounts.dbLock) {
5631 synchronized (accounts.cacheLock) {
5632 long grantsCount;
5633 if (authTokenType != null) {
5634 grantsCount = accounts.accountsDb
5635 .findMatchingGrantsCount(callerUid, authTokenType, account);
5636 } else {
5637 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5638 account);
5639 }
5640 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005641
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005642 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5643 // TODO: Skip this check when running automated tests. Replace this
5644 // with a more general solution.
Hui Yu139c2482018-08-10 15:37:51 -07005645 Log.d(TAG, "no credentials permission for usage of "
5646 + account.toSafeString() + ", "
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005647 + authTokenType + " by uid " + callerUid
5648 + " but ignoring since device is in test harness.");
5649 return true;
5650 }
5651 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005652 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005653 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005654 }
5655
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005656 private boolean isSystemUid(int callingUid) {
5657 String[] packages = null;
5658 long ident = Binder.clearCallingIdentity();
5659 try {
5660 packages = mPackageManager.getPackagesForUid(callingUid);
Alex Chau81a47cd2018-01-02 16:49:14 +00005661 if (packages != null) {
5662 for (String name : packages) {
5663 try {
5664 PackageInfo packageInfo =
5665 mPackageManager.getPackageInfo(name, 0 /* flags */);
5666 if (packageInfo != null
5667 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5668 != 0) {
5669 return true;
5670 }
5671 } catch (NameNotFoundException e) {
5672 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5673 }
5674 }
5675 } else {
5676 Log.w(TAG, "No known packages with uid " + callingUid);
5677 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005678 } finally {
5679 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005680 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005681 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005682 }
5683
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005684 /** Succeeds if any of the specified permissions are granted. */
5685 private void checkReadAccountsPermitted(
5686 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005687 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005688 int userId,
5689 String opPackageName) {
5690 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005691 String msg = String.format(
5692 "caller uid %s cannot access %s accounts",
5693 callingUid,
5694 accountType);
5695 Log.w(TAG, " " + msg);
5696 throw new SecurityException(msg);
5697 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005698 }
5699
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005700 private boolean canUserModifyAccounts(int userId, int callingUid) {
5701 // the managing app can always modify accounts
5702 if (isProfileOwner(callingUid)) {
5703 return true;
5704 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005705 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5706 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5707 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005708 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005709 return true;
5710 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005711
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005712 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5713 // the managing app can always modify accounts
5714 if (isProfileOwner(callingUid)) {
5715 return true;
5716 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005717 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5718 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005719 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005720 if (typesArray == null) {
5721 return true;
5722 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005723 for (String forbiddenType : typesArray) {
5724 if (forbiddenType.equals(accountType)) {
5725 return false;
5726 }
5727 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005728 return true;
5729 }
5730
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005731 private boolean isProfileOwner(int uid) {
5732 final DevicePolicyManagerInternal dpmi =
5733 LocalServices.getService(DevicePolicyManagerInternal.class);
5734 return (dpmi != null)
5735 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5736 }
5737
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005738 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005739 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5740 throws RemoteException {
5741 final int callingUid = getCallingUid();
5742
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005743 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005744 throw new SecurityException();
5745 }
5746
5747 if (value) {
5748 grantAppPermission(account, authTokenType, uid);
5749 } else {
5750 revokeAppPermission(account, authTokenType, uid);
5751 }
5752 }
5753
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005754 /**
5755 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5756 * <p>
5757 * Although this is public it can only be accessed via the AccountManagerService object
5758 * which is in the system. This means we don't need to protect it with permissions.
5759 * @hide
5760 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005761 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005762 if (account == null || authTokenType == null) {
5763 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005764 return;
5765 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005766 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005767 synchronized (accounts.dbLock) {
5768 synchronized (accounts.cacheLock) {
5769 long accountId = accounts.accountsDb.findDeAccountId(account);
5770 if (accountId >= 0) {
5771 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5772 }
5773 cancelNotification(
5774 getCredentialPermissionNotificationId(account, authTokenType, uid),
5775 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005776
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005777 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5778 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005779 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005780
5781 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5782 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5783 : mAppPermissionChangeListeners) {
5784 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5785 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005786 }
5787
5788 /**
5789 * Don't allow callers with the given uid permission to get credentials for
5790 * account/authTokenType.
5791 * <p>
5792 * Although this is public it can only be accessed via the AccountManagerService object
5793 * which is in the system. This means we don't need to protect it with permissions.
5794 * @hide
5795 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005796 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005797 if (account == null || authTokenType == null) {
5798 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005799 return;
5800 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005801 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005802 synchronized (accounts.dbLock) {
5803 synchronized (accounts.cacheLock) {
5804 accounts.accountsDb.beginTransaction();
5805 try {
5806 long accountId = accounts.accountsDb.findDeAccountId(account);
5807 if (accountId >= 0) {
5808 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5809 accountId, authTokenType, uid);
5810 accounts.accountsDb.setTransactionSuccessful();
5811 }
5812 } finally {
5813 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005814 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005815
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005816 cancelNotification(
5817 getCredentialPermissionNotificationId(account, authTokenType, uid),
5818 UserHandle.of(accounts.userId));
5819 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005820 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005821
5822 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5823 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5824 : mAppPermissionChangeListeners) {
5825 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5826 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005827 }
Fred Quintana56285a62010-12-02 14:20:51 -08005828
Amith Yamasani04e0d262012-02-14 11:50:53 -08005829 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5830 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005831 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005832 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005833 for (Account curAccount : oldAccountsForType) {
5834 if (!curAccount.equals(account)) {
5835 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005836 }
5837 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005838 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005839 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005840 } else {
5841 Account[] newAccountsForType = new Account[newAccountsList.size()];
5842 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005843 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005844 }
Fred Quintana56285a62010-12-02 14:20:51 -08005845 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005846 accounts.userDataCache.remove(account);
5847 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005848 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005849 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005850 }
5851
5852 /**
5853 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005854 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5855 * processes and if you will return this account to apps you should return the result.
5856 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005857 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005858 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005859 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005860 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5861 Account[] newAccountsForType = new Account[oldLength + 1];
5862 if (accountsForType != null) {
5863 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005864 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005865 String token = account.getAccessId() != null ? account.getAccessId()
5866 : UUID.randomUUID().toString();
5867 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005868 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005869 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005870 }
5871
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005872 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005873 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005874 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005875 String visibilityFilterPackage = callingPackage;
5876 if (visibilityFilterPackage == null) {
5877 visibilityFilterPackage = getPackageNameForUid(callingUid);
5878 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005879 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005880 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005881 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005882 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5883 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5884 || (includeManagedNotVisible
5885 && (visibility
5886 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5887 firstPass.put(account, visibility);
5888 }
5889 }
5890 Map<Account, Integer> secondPass =
5891 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5892
5893 Account[] filtered = new Account[secondPass.size()];
5894 filtered = secondPass.keySet().toArray(filtered);
5895 return filtered;
5896 }
5897
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005898 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005899 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005900 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005901 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005902 // first part is to filter shared accounts.
5903 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005904 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005905 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005906 return unfiltered;
5907 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005908 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005909 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005910 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005911 if (packages == null) {
5912 packages = new String[] {};
5913 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005914 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005915 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005916 // This might be a temporary way to specify a visible list
5917 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005918 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5919 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005920 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005921 return unfiltered;
5922 }
5923 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005924 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005925 if (ArrayUtils.isEmpty(sharedAccounts)) {
5926 return unfiltered;
5927 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005928 String requiredAccountType = "";
5929 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005930 // If there's an explicit callingPackage specified, check if that package
5931 // opted in to see restricted accounts.
5932 if (callingPackage != null) {
5933 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005934 if (pi != null && pi.restrictedAccountType != null) {
5935 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005936 }
5937 } else {
5938 // Otherwise check if the callingUid has a package that has opted in
5939 for (String packageName : packages) {
5940 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5941 if (pi != null && pi.restrictedAccountType != null) {
5942 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005943 break;
5944 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005945 }
5946 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005947 } catch (NameNotFoundException e) {
5948 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005949 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005950 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005951 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5952 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005953 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005954 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005955 } else {
5956 boolean found = false;
5957 for (Account shared : sharedAccounts) {
5958 if (shared.equals(account)) {
5959 found = true;
5960 break;
5961 }
5962 }
5963 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005964 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005965 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005966 }
5967 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005968 return filtered;
5969 } else {
5970 return unfiltered;
5971 }
5972 }
5973
Amith Yamasani27db4682013-03-30 17:07:47 -07005974 /*
5975 * packageName can be null. If not null, it should be used to filter out restricted accounts
5976 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005977 *
5978 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5979 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005980 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005981 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005982 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005983 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005984 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5985 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005986 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005987 Account[] accounts;
5988 synchronized (userAccounts.cacheLock) {
5989 accounts = userAccounts.accountCache.get(accountType);
5990 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005991 if (accounts == null) {
5992 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005993 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005994 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5995 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005996 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005997 } else {
5998 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005999 Account[] accountsArray;
6000 synchronized (userAccounts.cacheLock) {
6001 for (Account[] accounts : userAccounts.accountCache.values()) {
6002 totalLength += accounts.length;
6003 }
6004 if (totalLength == 0) {
6005 return EMPTY_ACCOUNT_ARRAY;
6006 }
6007 accountsArray = new Account[totalLength];
6008 totalLength = 0;
6009 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
6010 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
6011 accountsOfType.length);
6012 totalLength += accountsOfType.length;
6013 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006014 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07006015 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006016 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08006017 }
6018 }
6019
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006020 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006021 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08006022 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006023 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006024 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006025 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08006026 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006027 }
6028 if (value == null) {
6029 userDataForAccount.remove(key);
6030 } else {
6031 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08006032 }
6033 }
6034
Carlos Valdivia91979be2015-05-22 14:11:35 -07006035 protected String readCachedTokenInternal(
6036 UserAccounts accounts,
6037 Account account,
6038 String tokenType,
6039 String callingPackage,
6040 byte[] pkgSigDigest) {
Dmitry Dementyev18f0ca92017-06-12 17:56:47 -07006041 synchronized (accounts.cacheLock) {
6042 return accounts.accountTokenCaches.get(
6043 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07006044 }
6045 }
6046
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07006047 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006048 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08006049 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006050 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006051 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006052 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08006053 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006054 }
6055 if (value == null) {
6056 authTokensForAccount.remove(key);
6057 } else {
6058 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08006059 }
6060 }
6061
Amith Yamasani04e0d262012-02-14 11:50:53 -08006062 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
6063 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07006064 // Fast path - check if account is already cached
6065 synchronized (accounts.cacheLock) {
6066 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
6067 if (authTokensForAccount != null) {
6068 return authTokensForAccount.get(authTokenType);
6069 }
6070 }
6071 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07006072 synchronized (accounts.dbLock) {
6073 synchronized (accounts.cacheLock) {
6074 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
6075 if (authTokensForAccount == null) {
6076 // need to populate the cache for this account
6077 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
6078 accounts.authTokenCache.put(account, authTokensForAccount);
6079 }
6080 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08006081 }
Fred Quintana56285a62010-12-02 14:20:51 -08006082 }
6083 }
6084
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006085 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
6086 Map<String, String> userDataForAccount;
6087 // Fast path - check if data is already cached
6088 synchronized (accounts.cacheLock) {
6089 userDataForAccount = accounts.userDataCache.get(account);
6090 }
6091 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00006092 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006093 synchronized (accounts.dbLock) {
6094 synchronized (accounts.cacheLock) {
6095 userDataForAccount = accounts.userDataCache.get(account);
6096 if (userDataForAccount == null) {
6097 // need to populate the cache for this account
6098 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
6099 accounts.userDataCache.put(account, userDataForAccount);
6100 }
6101 }
6102 }
Fred Quintana56285a62010-12-02 14:20:51 -08006103 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00006104 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08006105 }
6106
Kenny Guy07ad8dc2014-09-01 20:56:12 +01006107 private Context getContextForUser(UserHandle user) {
6108 try {
6109 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
6110 } catch (NameNotFoundException e) {
6111 // Default to mContext, not finding the package system is running as is unlikely.
6112 return mContext;
6113 }
6114 }
Sandra Kwan78812282015-11-04 11:19:47 -08006115
6116 private void sendResponse(IAccountManagerResponse response, Bundle result) {
6117 try {
6118 response.onResult(result);
6119 } catch (RemoteException e) {
6120 // if the caller is dead then there is no one to care about remote
6121 // exceptions
6122 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6123 Log.v(TAG, "failure while notifying response", e);
6124 }
6125 }
6126 }
6127
6128 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
6129 String errorMessage) {
6130 try {
6131 response.onError(errorCode, errorMessage);
6132 } catch (RemoteException e) {
6133 // if the caller is dead then there is no one to care about remote
6134 // exceptions
6135 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6136 Log.v(TAG, "failure while notifying response", e);
6137 }
6138 }
6139 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006140
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006141 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07006142 private final Object mLock = new Object();
6143
6144 @GuardedBy("mLock")
6145 private AccountManagerBackupHelper mBackupHelper;
6146
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006147 @Override
6148 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
6149 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
6150 if (account == null) {
6151 Slog.w(TAG, "account cannot be null");
6152 return;
6153 }
6154 if (packageName == null) {
6155 Slog.w(TAG, "packageName cannot be null");
6156 return;
6157 }
6158 if (userId < UserHandle.USER_SYSTEM) {
6159 Slog.w(TAG, "user id must be concrete");
6160 return;
6161 }
6162 if (callback == null) {
6163 Slog.w(TAG, "callback cannot be null");
6164 return;
6165 }
6166
Dmitry Dementyev7b3ea132017-05-10 12:45:02 -07006167 int visibility =
6168 resolveAccountVisibility(account, packageName, getUserAccounts(userId));
6169 if (visibility == AccountManager.VISIBILITY_NOT_VISIBLE) {
6170 Slog.w(TAG, "requestAccountAccess: account is hidden");
6171 return;
6172 }
6173
Svet Ganovf6d424f12016-09-20 20:18:53 -07006174 if (AccountManagerService.this.hasAccountAccess(account, packageName,
6175 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006176 Bundle result = new Bundle();
6177 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
6178 callback.sendResult(result);
6179 return;
6180 }
6181
6182 final int uid;
6183 try {
Dmitry Dementyev940b7602018-10-09 16:40:06 -07006184 long identityToken = clearCallingIdentity();
6185 try {
6186 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
6187 } finally {
6188 restoreCallingIdentity(identityToken);
6189 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006190 } catch (NameNotFoundException e) {
6191 Slog.e(TAG, "Unknown package " + packageName);
6192 return;
6193 }
6194
6195 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006196 final UserAccounts userAccounts;
6197 synchronized (mUsers) {
6198 userAccounts = mUsers.get(userId);
6199 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04006200 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006201 doNotification(userAccounts, account, null, intent, packageName, userId);
6202 }
6203
6204 @Override
6205 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
6206 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
6207 mAppPermissionChangeListeners.add(listener);
6208 }
6209
6210 @Override
6211 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
6212 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006213 }
Svet Ganov5d09c992016-09-07 09:57:41 -07006214
6215 @Override
6216 public byte[] backupAccountAccessPermissions(int userId) {
6217 synchronized (mLock) {
6218 if (mBackupHelper == null) {
6219 mBackupHelper = new AccountManagerBackupHelper(
6220 AccountManagerService.this, this);
6221 }
6222 return mBackupHelper.backupAccountAccessPermissions(userId);
6223 }
6224 }
6225
6226 @Override
6227 public void restoreAccountAccessPermissions(byte[] data, int userId) {
6228 synchronized (mLock) {
6229 if (mBackupHelper == null) {
6230 mBackupHelper = new AccountManagerBackupHelper(
6231 AccountManagerService.this, this);
6232 }
6233 mBackupHelper.restoreAccountAccessPermissions(data, userId);
6234 }
6235 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006236 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07006237
6238 @VisibleForTesting
6239 static class Injector {
6240 private final Context mContext;
6241
6242 public Injector(Context context) {
6243 mContext = context;
6244 }
6245
6246 Looper getMessageHandlerLooper() {
6247 ServiceThread serviceThread = new ServiceThread(TAG,
6248 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
6249 serviceThread.start();
6250 return serviceThread.getLooper();
6251 }
6252
6253 Context getContext() {
6254 return mContext;
6255 }
6256
6257 void addLocalService(AccountManagerInternal service) {
6258 LocalServices.addService(AccountManagerInternal.class, service);
6259 }
6260
6261 String getDeDatabaseName(int userId) {
6262 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
6263 AccountsDb.DE_DATABASE_NAME);
6264 return databaseFile.getPath();
6265 }
6266
6267 String getCeDatabaseName(int userId) {
6268 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
6269 AccountsDb.CE_DATABASE_NAME);
6270 return databaseFile.getPath();
6271 }
6272
6273 String getPreNDatabaseName(int userId) {
6274 File systemDir = Environment.getDataSystemDirectory();
6275 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
6276 PRE_N_DATABASE_NAME);
6277 if (userId == 0) {
6278 // Migrate old file, if it exists, to the new location.
6279 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006280 // accidentally created in the old location,
6281 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07006282 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
6283 if (oldFile.exists() && !databaseFile.exists()) {
6284 // Check for use directory; create if it doesn't exist, else renameTo will fail
6285 File userDir = Environment.getUserSystemDirectory(userId);
6286 if (!userDir.exists()) {
6287 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006288 throw new IllegalStateException(
6289 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006290 }
6291 }
6292 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006293 throw new IllegalStateException(
6294 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006295 }
6296 }
6297 }
6298 return databaseFile.getPath();
6299 }
6300
6301 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
6302 return new AccountAuthenticatorCache(mContext);
6303 }
6304
6305 INotificationManager getNotificationManager() {
6306 return NotificationManager.getService();
6307 }
6308 }
Chris Wren717a8812017-03-31 15:34:39 -04006309
Andrew Scullc7770d62017-05-22 17:49:58 +01006310 private static class NotificationId {
Chris Wren717a8812017-03-31 15:34:39 -04006311 final String mTag;
6312 private final int mId;
6313
6314 NotificationId(String tag, int type) {
6315 mTag = tag;
6316 mId = type;
6317 }
6318 }
Fred Quintana60307342009-03-24 22:48:12 -07006319}