blob: 03da5b21fef8bb9bd4c1e18e82533c82c51c1b0b [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070025import android.accounts.AccountManagerInternal;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070027import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080028import android.accounts.GrantCredentialsPermissionActivity;
29import android.accounts.IAccountAuthenticator;
30import android.accounts.IAccountAuthenticatorResponse;
31import android.accounts.IAccountManager;
32import android.accounts.IAccountManagerResponse;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070033import android.annotation.IntRange;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070034import android.annotation.NonNull;
Svet Ganovf6d424f12016-09-20 20:18:53 -070035import android.annotation.Nullable;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080036import android.app.ActivityManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070037import android.app.ActivityThread;
Svetoslavf3f02ac2015-09-08 14:36:35 -070038import android.app.AppOpsManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070039import android.app.INotificationManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070040import android.app.Notification;
41import android.app.NotificationManager;
42import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000043import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010044import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000045import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070046import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070047import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070048import android.content.Context;
49import android.content.Intent;
50import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070051import android.content.IntentSender;
Fred Quintanab839afc2009-10-14 15:57:28 -070052import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080053import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070054import android.content.pm.ApplicationInfo;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070055import android.content.pm.IPackageManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070057import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070058import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070060import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070061import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070062import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070063import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070064import android.database.Cursor;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070065import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070066import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080068import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.IBinder;
71import android.os.Looper;
72import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070073import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070074import android.os.Process;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070075import android.os.RemoteCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -070076import android.os.RemoteException;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080077import android.os.StrictMode;
Fred Quintanaa698f422009-04-08 19:14:54 -070078import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070079import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070080import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import android.text.TextUtils;
82import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070083import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070084import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080085import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070086import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070087
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070088import com.android.internal.R;
Svet Ganov5d09c992016-09-07 09:57:41 -070089import com.android.internal.annotations.GuardedBy;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070090import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070091import com.android.internal.content.PackageMonitor;
Chris Wren282cfef2017-03-27 15:01:44 -040092import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050093import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani67df64b2012-12-14 12:09:36 -080094import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060095import com.android.internal.util.DumpUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080096import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -070097import com.android.internal.util.Preconditions;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000098import com.android.server.LocalServices;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -070099import com.android.server.ServiceThread;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600100import com.android.server.SystemService;
101
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700102import com.google.android.collect.Lists;
103import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700104
Oscar Montemayora8529f62009-11-18 10:14:20 -0800105import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700106import java.io.FileDescriptor;
107import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800108import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700109import java.security.MessageDigest;
110import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700111import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700112import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800113import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700114import java.util.Collection;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700115import java.util.Collections;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700116import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700117import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700118import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800119import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700120import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800121import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800122import java.util.Map.Entry;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700123import java.util.Objects;
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700124import java.util.Set;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700125import java.util.UUID;
Svet Ganovf6d424f12016-09-20 20:18:53 -0700126import java.util.concurrent.CopyOnWriteArrayList;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700127import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700128
Fred Quintana60307342009-03-24 22:48:12 -0700129/**
130 * A system service that provides account, password, and authtoken management for all
131 * accounts on the device. Some of these calls are implemented with the help of the corresponding
132 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
133 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700134 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700135 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700136 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700137public class AccountManagerService
138 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800139 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700140 private static final String TAG = "AccountManagerService";
141
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600142 public static class Lifecycle extends SystemService {
143 private AccountManagerService mService;
144
145 public Lifecycle(Context context) {
146 super(context);
147 }
148
149 @Override
150 public void onStart() {
Fyodor Kupolovda993802016-09-21 14:47:10 -0700151 mService = new AccountManagerService(new Injector(getContext()));
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600152 publishBinderService(Context.ACCOUNT_SERVICE, mService);
153 }
154
155 @Override
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600156 public void onUnlockUser(int userHandle) {
157 mService.onUnlockUser(userHandle);
158 }
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700159
160 @Override
161 public void onCleanupUser(int userHandle) {
162 mService.onCleanupUser(userHandle);
163 }
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600164 }
165
Svet Ganov5d09c992016-09-07 09:57:41 -0700166 final Context mContext;
Fred Quintana60307342009-03-24 22:48:12 -0700167
Fred Quintana56285a62010-12-02 14:20:51 -0800168 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700169 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700170 private UserManager mUserManager;
Fyodor Kupolovda993802016-09-21 14:47:10 -0700171 private final Injector mInjector;
Fred Quintana56285a62010-12-02 14:20:51 -0800172
Svet Ganov5d09c992016-09-07 09:57:41 -0700173 final MessageHandler mHandler;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700174
Fred Quintana60307342009-03-24 22:48:12 -0700175 // Messages that can be sent on mHandler
176 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700177 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700178
Fred Quintana56285a62010-12-02 14:20:51 -0800179 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700180 private static final String PRE_N_DATABASE_NAME = "accounts.db";
Fred Quintana7be59642009-08-24 18:29:25 -0700181 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800182
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800183 private static final int SIGNATURE_CHECK_MISMATCH = 0;
184 private static final int SIGNATURE_CHECK_MATCH = 1;
185 private static final int SIGNATURE_CHECK_UID_MATCH = 2;
186
Carlos Valdivia91979be2015-05-22 14:11:35 -0700187 static {
188 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Christopher Tatebded68f2017-02-21 11:41:55 -0800189 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
190 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700191 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700192
193 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700194
Amith Yamasani04e0d262012-02-14 11:50:53 -0800195 static class UserAccounts {
196 private final int userId;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700197 final AccountsDb accountsDb;
Chris Wren717a8812017-03-31 15:34:39 -0400198 private final HashMap<Pair<Pair<Account, String>, Integer>, NotificationId>
199 credentialsPermissionNotificationIds = new HashMap<>();
200 private final HashMap<Account, NotificationId> signinRequiredNotificationIds
201 = new HashMap<>();
Svet Ganov5d09c992016-09-07 09:57:41 -0700202 final Object cacheLock = new Object();
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700203 final Object dbLock = new Object(); // if needed, dbLock must be obtained before cacheLock
Amith Yamasani04e0d262012-02-14 11:50:53 -0800204 /** protected by the {@link #cacheLock} */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700205 final HashMap<String, Account[]> accountCache = new LinkedHashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800206 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700207 private final Map<Account, Map<String, String>> userDataCache = new HashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800208 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700209 private final Map<Account, Map<String, String>> authTokenCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700210 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700211 private final TokenCache accountTokenCaches = new TokenCache();
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700212 /** protected by the {@link #cacheLock} */
213 private final Map<Account, Map<String, Integer>> visibilityCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700214
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700215 /** protected by the {@link #mReceiversForType},
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700216 * type -> (packageName -> number of active receivers)
217 * type == null is used to get notifications about all account types
218 */
219 private final Map<String, Map<String, Integer>> mReceiversForType = new HashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800220
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700221 /**
222 * protected by the {@link #cacheLock}
223 *
224 * Caches the previous names associated with an account. Previous names
225 * should be cached because we expect that when an Account is renamed,
226 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
227 * want to know if the accounts they care about have been renamed.
228 *
229 * The previous names are wrapped in an {@link AtomicReference} so that
230 * we can distinguish between those accounts with no previous names and
231 * those whose previous names haven't been cached (yet).
232 */
233 private final HashMap<Account, AtomicReference<String>> previousNameCache =
234 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800235
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700236 private int debugDbInsertionPoint = -1;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700237 private SQLiteStatement statementForLogging; // TODO Move to AccountsDb
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700238
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700239 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800240 this.userId = userId;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700241 synchronized (dbLock) {
242 synchronized (cacheLock) {
243 accountsDb = AccountsDb.create(context, userId, preNDbFile, deDbFile);
244 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800245 }
246 }
247 }
248
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700249 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600250 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -0700251 // Not thread-safe. Only use in synchronized context
252 private final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Svet Ganovf6d424f12016-09-20 20:18:53 -0700253 private CopyOnWriteArrayList<AccountManagerInternal.OnAppPermissionChangeListener>
254 mAppPermissionChangeListeners = new CopyOnWriteArrayList<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800255
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700256 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700257 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700258
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700259 /**
260 * This should only be called by system code. One should only call this after the service
261 * has started.
262 * @return a reference to the AccountManagerService instance
263 * @hide
264 */
265 public static AccountManagerService getSingleton() {
266 return sThis.get();
267 }
Fred Quintana60307342009-03-24 22:48:12 -0700268
Fyodor Kupolovda993802016-09-21 14:47:10 -0700269 public AccountManagerService(Injector injector) {
270 mInjector = injector;
271 mContext = injector.getContext();
272 mPackageManager = mContext.getPackageManager();
Svetoslavf3f02ac2015-09-08 14:36:35 -0700273 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fyodor Kupolovda993802016-09-21 14:47:10 -0700274 mHandler = new MessageHandler(injector.getMessageHandlerLooper());
275 mAuthenticatorCache = mInjector.getAccountAuthenticatorCache();
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800276 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700277
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700278 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800279
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800280 IntentFilter intentFilter = new IntentFilter();
281 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
282 intentFilter.addDataScheme("package");
283 mContext.registerReceiver(new BroadcastReceiver() {
284 @Override
285 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700286 // Don't delete accounts when updating a authenticator's
287 // package.
288 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700289 /* Purging data requires file io, don't block the main thread. This is probably
290 * less than ideal because we are introducing a race condition where old grants
291 * could be exercised until they are purged. But that race condition existed
292 * anyway with the broadcast receiver.
293 *
294 * Ideally, we would completely clear the cache, purge data from the database,
295 * and then rebuild the cache. All under the cache lock. But that change is too
296 * large at this point.
297 */
Dmitry Dementyev0b676422017-03-09 11:51:26 -0800298 final String removedPackageName = intent.getData().getSchemeSpecificPart();
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700299 Runnable purgingRunnable = new Runnable() {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700300 @Override
301 public void run() {
302 purgeOldGrantsAll();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800303 // Notify authenticator about removed app?
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800304 removeVisibilityValuesForPackage(removedPackageName);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700305 }
306 };
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700307 mHandler.post(purgingRunnable);
Carlos Valdivia23f58262014-09-05 10:52:41 -0700308 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800309 }
310 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800311
Fyodor Kupolovda993802016-09-21 14:47:10 -0700312 injector.addLocalService(new AccountManagerInternalImpl());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700313
314 // Need to cancel account request notifications if the update/install can access the account
315 new PackageMonitor() {
316 @Override
317 public void onPackageAdded(String packageName, int uid) {
318 // Called on a handler, and running as the system
319 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
320 }
321
322 @Override
323 public void onPackageUpdateFinished(String packageName, int uid) {
324 // Called on a handler, and running as the system
325 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
326 }
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700327 }.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700328
329 // Cancel account request notification if an app op was preventing the account access
330 mAppOpsManager.startWatchingMode(AppOpsManager.OP_GET_ACCOUNTS, null,
331 new AppOpsManager.OnOpChangedInternalListener() {
332 @Override
333 public void onOpChanged(int op, String packageName) {
334 try {
335 final int userId = ActivityManager.getCurrentUser();
336 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
337 final int mode = mAppOpsManager.checkOpNoThrow(
338 AppOpsManager.OP_GET_ACCOUNTS, uid, packageName);
339 if (mode == AppOpsManager.MODE_ALLOWED) {
340 final long identity = Binder.clearCallingIdentity();
341 try {
342 cancelAccountAccessRequestNotificationIfNeeded(packageName, uid, true);
343 } finally {
344 Binder.restoreCallingIdentity(identity);
345 }
346 }
347 } catch (NameNotFoundException e) {
348 /* ignore */
349 }
350 }
351 });
352
353 // Cancel account request notification if a permission was preventing the account access
354 mPackageManager.addOnPermissionsChangeListener(
355 (int uid) -> {
356 Account[] accounts = null;
357 String[] packageNames = mPackageManager.getPackagesForUid(uid);
358 if (packageNames != null) {
359 final int userId = UserHandle.getUserId(uid);
360 final long identity = Binder.clearCallingIdentity();
361 try {
362 for (String packageName : packageNames) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800363 // if app asked for permission we need to cancel notification even
364 // for O+ applications.
365 if (mPackageManager.checkPermission(
366 Manifest.permission.GET_ACCOUNTS,
367 packageName) != PackageManager.PERMISSION_GRANTED) {
368 continue;
369 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700370
371 if (accounts == null) {
372 accounts = getAccountsAsUser(null, userId, "android");
373 if (ArrayUtils.isEmpty(accounts)) {
374 return;
375 }
376 }
377
378 for (Account account : accounts) {
379 cancelAccountAccessRequestNotificationIfNeeded(
380 account, uid, packageName, true);
381 }
382 }
383 } finally {
384 Binder.restoreCallingIdentity(identity);
385 }
386 }
387 });
388 }
389
390 private void cancelAccountAccessRequestNotificationIfNeeded(int uid,
391 boolean checkAccess) {
392 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
393 for (Account account : accounts) {
394 cancelAccountAccessRequestNotificationIfNeeded(account, uid, checkAccess);
395 }
396 }
397
398 private void cancelAccountAccessRequestNotificationIfNeeded(String packageName, int uid,
399 boolean checkAccess) {
400 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
401 for (Account account : accounts) {
402 cancelAccountAccessRequestNotificationIfNeeded(account, uid, packageName, checkAccess);
403 }
404 }
405
406 private void cancelAccountAccessRequestNotificationIfNeeded(Account account, int uid,
407 boolean checkAccess) {
408 String[] packageNames = mPackageManager.getPackagesForUid(uid);
409 if (packageNames != null) {
410 for (String packageName : packageNames) {
411 cancelAccountAccessRequestNotificationIfNeeded(account, uid,
412 packageName, checkAccess);
413 }
414 }
415 }
416
417 private void cancelAccountAccessRequestNotificationIfNeeded(Account account,
418 int uid, String packageName, boolean checkAccess) {
419 if (!checkAccess || hasAccountAccess(account, packageName,
420 UserHandle.getUserHandleForUid(uid))) {
421 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -0700422 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700423 UserHandle.getUserHandleForUid(uid));
424 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800425 }
426
Dianne Hackborn164371f2013-10-01 19:10:13 -0700427 @Override
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800428 public boolean addAccountExplicitlyWithVisibility(Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800429 Bundle extras, Map packageToVisibility) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800430 Bundle.setDefusable(extras, true);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700431 int callingUid = Binder.getCallingUid();
432 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800433 if (Log.isLoggable(TAG, Log.VERBOSE)) {
434 Log.v(TAG, "addAccountExplicitly: " + account + ", caller's uid " + callingUid
435 + ", pid " + Binder.getCallingPid());
436 }
437 Preconditions.checkNotNull(account, "account cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800438 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
439 String msg = String.format("uid %s cannot explicitly add accounts of type: %s",
440 callingUid, account.type);
441 throw new SecurityException(msg);
442 }
443 /*
444 * Child users are not allowed to add accounts. Only the accounts that are shared by the
445 * parent profile can be added to child profile.
446 *
447 * TODO: Only allow accounts that were shared to be added by a limited user.
448 */
449 // fails if the account already exists
450 long identityToken = clearCallingIdentity();
451 try {
452 UserAccounts accounts = getUserAccounts(userId);
453 return addAccountInternal(accounts, account, password, extras, callingUid,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800454 (Map<String, Integer>) packageToVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800455 } finally {
456 restoreCallingIdentity(identityToken);
457 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700458 }
459
460 @Override
Dmitry Dementyev52745472016-12-02 10:27:45 -0800461 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
462 String accountType) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800463 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700464 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800465 boolean isSystemUid = UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700466 List<String> managedTypes = getTypesForCaller(callingUid, userId, isSystemUid);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800467
468 if ((accountType != null && !managedTypes.contains(accountType))
469 || (accountType == null && !isSystemUid)) {
470 throw new SecurityException(
471 "getAccountsAndVisibilityForPackage() called from unauthorized uid "
472 + callingUid + " with packageName=" + packageName);
473 }
474 if (accountType != null) {
475 managedTypes = new ArrayList<String>();
476 managedTypes.add(accountType);
477 }
478
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800479 long identityToken = clearCallingIdentity();
480 try {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700481 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800482 return getAccountsAndVisibilityForPackage(packageName, managedTypes, callingUid,
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700483 accounts);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800484 } finally {
485 restoreCallingIdentity(identityToken);
486 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800487 }
488
489 /*
490 * accountTypes may not be null
491 */
492 private Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
493 List<String> accountTypes, Integer callingUid, UserAccounts accounts) {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700494 if (!packageExistsForUser(packageName, accounts.userId)) {
495 Log.d(TAG, "Package not found " + packageName);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800496 return new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800497 }
498
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800499 Map<Account, Integer> result = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800500 for (String accountType : accountTypes) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700501 synchronized (accounts.dbLock) {
502 synchronized (accounts.cacheLock) {
503 final Account[] accountsOfType = accounts.accountCache.get(accountType);
504 if (accountsOfType != null) {
505 for (Account account : accountsOfType) {
506 result.put(account,
507 resolveAccountVisibility(account, packageName, accounts));
508 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800509 }
510 }
511 }
512 }
513 return filterSharedAccounts(accounts, result, callingUid, packageName);
Dmitry Dementyev52745472016-12-02 10:27:45 -0800514 }
515
516 @Override
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800517 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700518 Preconditions.checkNotNull(account, "account cannot be null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700519 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700520 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800521 if (!isAccountManagedByCaller(account.type, callingUid, userId)
522 && !isSystemUid(callingUid)) {
523 String msg =
524 String.format("uid %s cannot get secrets for account %s", callingUid, account);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700525 throw new SecurityException(msg);
526 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700527
528 long identityToken = clearCallingIdentity();
529 try {
530 UserAccounts accounts = getUserAccounts(userId);
531 synchronized (accounts.dbLock) {
532 synchronized (accounts.cacheLock) {
533 return getPackagesAndVisibilityForAccountLocked(account, accounts);
534 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700535 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700536 } finally {
537 restoreCallingIdentity(identityToken);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700538 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700539
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800540 }
541
542 /**
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700543 * Returns Map with all package names and visibility values for given account.
544 * The method and returned map must be guarded by accounts.cacheLock
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800545 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800546 * @param account Account to get visibility values.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800547 * @param accounts UserAccount that currently hosts the account and application
548 *
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700549 * @return Map with cache for package names to visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800550 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700551 private @NonNull Map<String, Integer> getPackagesAndVisibilityForAccountLocked(Account account,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800552 UserAccounts accounts) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700553 Map<String, Integer> accountVisibility = accounts.visibilityCache.get(account);
554 if (accountVisibility == null) {
555 Log.d(TAG, "Visibility was not initialized");
556 accountVisibility = new HashMap<>();
557 accounts.visibilityCache.put(account, accountVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800558 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700559 return accountVisibility;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700560 }
561
562 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700563 public int getAccountVisibility(Account account, String packageName) {
564 Preconditions.checkNotNull(account, "account cannot be null");
565 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800566 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700567 int userId = UserHandle.getCallingUserId();
568 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800569 && !isSystemUid(callingUid)) {
570 String msg = String.format(
571 "uid %s cannot get secrets for accounts of type: %s",
572 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700573 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800574 throw new SecurityException(msg);
575 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700576 long identityToken = clearCallingIdentity();
577 try {
578 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyevcbe1bd12017-04-25 17:02:47 -0700579 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)) {
580 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
581 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
582 return visibility;
583 } else {
584 return AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
585 }
586 }
587 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName)) {
588 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
589 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
590 return visibility;
591 } else {
592 return AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
593 }
594 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700595 return resolveAccountVisibility(account, packageName, accounts);
596 } finally {
597 restoreCallingIdentity(identityToken);
598 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800599 }
600
601 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800602 * Method returns visibility for given account and package name.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800603 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800604 * @param account The account to check visibility.
605 * @param packageName Package name to check visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800606 * @param accounts UserAccount that currently hosts the account and application
607 *
608 * @return Visibility value, AccountManager.VISIBILITY_UNDEFINED if no value was stored.
609 *
610 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700611 private int getAccountVisibilityFromCache(Account account, String packageName,
612 UserAccounts accounts) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700613 synchronized (accounts.cacheLock) {
614 Map<String, Integer> accountVisibility =
615 getPackagesAndVisibilityForAccountLocked(account, accounts);
616 Integer visibility = accountVisibility.get(packageName);
617 return visibility != null ? visibility : AccountManager.VISIBILITY_UNDEFINED;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800618 }
619 }
620
621 /**
622 * Method which handles default values for Account visibility.
623 *
624 * @param account The account to check visibility.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800625 * @param packageName Package name to check visibility
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800626 * @param accounts UserAccount that currently hosts the account and application
627 *
628 * @return Visibility value, the method never returns AccountManager.VISIBILITY_UNDEFINED
629 *
630 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800631 private Integer resolveAccountVisibility(Account account, @NonNull String packageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800632 UserAccounts accounts) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800633 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800634 int uid = -1;
635 try {
636 long identityToken = clearCallingIdentity();
637 try {
638 uid = mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
639 } finally {
640 restoreCallingIdentity(identityToken);
641 }
642 } catch (NameNotFoundException e) {
643 Log.d(TAG, "Package not found " + e.getMessage());
644 return AccountManager.VISIBILITY_NOT_VISIBLE;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800645 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800646
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800647 // System visibility can not be restricted.
648 if (UserHandle.isSameApp(uid, Process.SYSTEM_UID)) {
649 return AccountManager.VISIBILITY_VISIBLE;
650 }
651
652 int signatureCheckResult =
653 checkPackageSignature(account.type, uid, accounts.userId);
654
655 // Authenticator can not restrict visibility to itself.
656 if (signatureCheckResult == SIGNATURE_CHECK_UID_MATCH) {
657 return AccountManager.VISIBILITY_VISIBLE; // Authenticator can always see the account
658 }
659
660 // Return stored value if it was set.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700661 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800662
663 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
664 return visibility;
665 }
666
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700667 boolean isPrivileged = isPermittedForPackage(packageName, uid, accounts.userId,
Dmitry Dementyevf794c8d2017-02-03 18:17:59 -0800668 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
669
670 // Device/Profile owner gets visibility by default.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800671 if (isProfileOwner(uid)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800672 return AccountManager.VISIBILITY_VISIBLE;
673 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800674
675 boolean preO = isPreOApplication(packageName);
676 if ((signatureCheckResult != SIGNATURE_CHECK_MISMATCH)
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700677 || (preO && checkGetAccountsPermission(packageName, uid, accounts.userId))
678 || (checkReadContactsPermission(packageName, uid, accounts.userId)
679 && accountTypeManagesContacts(account.type, accounts.userId))
680 || isPrivileged) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800681 // Use legacy for preO apps with GET_ACCOUNTS permission or pre/postO with signature
682 // match.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700683 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800684 AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800685 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
686 visibility = AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
687 }
688 } else {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700689 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800690 AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800691 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
692 visibility = AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
693 }
694 }
695 return visibility;
696 }
697
698 /**
699 * Checks targetSdk for a package;
700 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800701 * @param packageName Package name
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800702 *
703 * @return True if package's target SDK is below {@link android.os.Build.VERSION_CODES#O}, or
704 * undefined
705 */
706 private boolean isPreOApplication(String packageName) {
707 try {
708 long identityToken = clearCallingIdentity();
709 ApplicationInfo applicationInfo;
710 try {
711 applicationInfo = mPackageManager.getApplicationInfo(packageName, 0);
712 } finally {
713 restoreCallingIdentity(identityToken);
714 }
715
716 if (applicationInfo != null) {
717 int version = applicationInfo.targetSdkVersion;
718 return version < android.os.Build.VERSION_CODES.O;
719 }
720 return true;
721 } catch (NameNotFoundException e) {
722 Log.d(TAG, "Package not found " + e.getMessage());
723 return true;
724 }
Dmitry Dementyev58fa83622016-12-20 18:08:51 -0800725 }
726
727 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700728 public boolean setAccountVisibility(Account account, String packageName, int newVisibility) {
729 Preconditions.checkNotNull(account, "account cannot be null");
730 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800731 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700732 int userId = UserHandle.getCallingUserId();
733 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800734 && !isSystemUid(callingUid)) {
735 String msg = String.format(
736 "uid %s cannot get secrets for accounts of type: %s",
737 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700738 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800739 throw new SecurityException(msg);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700740 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700741 long identityToken = clearCallingIdentity();
742 try {
743 UserAccounts accounts = getUserAccounts(userId);
744 return setAccountVisibility(account, packageName, newVisibility, true /* notify */,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700745 accounts);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700746 } finally {
747 restoreCallingIdentity(identityToken);
748 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700749 }
750
751 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800752 * Updates visibility for given account name and package.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700753 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800754 * @param account Account to update visibility.
755 * @param packageName Package name for which visibility is updated.
756 * @param newVisibility New visibility calue
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800757 * @param notify if the flag is set applications will get notification about visibility change
758 * @param accounts UserAccount that currently hosts the account and application
759 *
760 * @return True if account visibility was changed.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700761 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800762 private boolean setAccountVisibility(Account account, String packageName, int newVisibility,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800763 boolean notify, UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700764 synchronized (accounts.dbLock) {
765 synchronized (accounts.cacheLock) {
766 Map<String, Integer> packagesToVisibility;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700767 List<String> accountRemovedReceivers;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700768 if (notify) {
769 if (isSpecialPackageKey(packageName)) {
770 packagesToVisibility =
771 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700772 accountRemovedReceivers = getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700773 } else {
774 if (!packageExistsForUser(packageName, accounts.userId)) {
775 return false; // package is not installed.
776 }
777 packagesToVisibility = new HashMap<>();
778 packagesToVisibility.put(packageName,
779 resolveAccountVisibility(account, packageName, accounts));
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700780 accountRemovedReceivers = new ArrayList<>();
781 if (shouldNotifyPackageOnAccountRemoval(account, packageName, accounts)) {
782 accountRemovedReceivers.add(packageName);
783 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700784 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800785 } else {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700786 // Notifications will not be send - only used during add account.
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700787 if (!isSpecialPackageKey(packageName) &&
788 !packageExistsForUser(packageName, accounts.userId)) {
789 // package is not installed and not meta value.
790 return false;
Nicolas Prevotf7d8df12016-09-16 17:45:34 +0100791 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700792 packagesToVisibility = Collections.emptyMap();
793 accountRemovedReceivers = Collections.emptyList();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800794 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700795
796 if (!updateAccountVisibilityLocked(account, packageName, newVisibility, accounts)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800797 return false;
798 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800799
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700800 if (notify) {
801 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
802 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700803 if (shouldNotifyOnVisibilityChange(packageToVisibility.getValue(),
804 resolveAccountVisibility(account, packageName, accounts))) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700805 notifyPackage(packageToVisibility.getKey(), accounts);
806 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700807 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700808 for (String packageNameToNotify : accountRemovedReceivers) {
809 sendAccountRemovedBroadcast(account, packageNameToNotify, accounts.userId);
810 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700811 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700812 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700813 return true;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800814 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700815 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700816 }
817
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700818 // Update account visibility in cache and database.
819 private boolean updateAccountVisibilityLocked(Account account, String packageName,
820 int newVisibility, UserAccounts accounts) {
821 final long accountId = accounts.accountsDb.findDeAccountId(account);
822 if (accountId < 0) {
823 return false;
824 }
825
826 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
827 try {
828 if (!accounts.accountsDb.setAccountVisibility(accountId, packageName,
829 newVisibility)) {
830 return false;
831 }
832 } finally {
833 StrictMode.setThreadPolicy(oldPolicy);
834 }
835 Map<String, Integer> accountVisibility =
836 getPackagesAndVisibilityForAccountLocked(account, accounts);
837 accountVisibility.put(packageName, newVisibility);
838 return true;
839 }
840
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700841 @Override
842 public void registerAccountListener(String[] accountTypes, String opPackageName) {
843 int callingUid = Binder.getCallingUid();
844 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700845
846 int userId = UserHandle.getCallingUserId();
847 long identityToken = clearCallingIdentity();
848 try {
849 UserAccounts accounts = getUserAccounts(userId);
850 registerAccountListener(accountTypes, opPackageName, accounts);
851 } finally {
852 restoreCallingIdentity(identityToken);
853 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800854 }
855
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700856 private void registerAccountListener(String[] accountTypes, String opPackageName,
857 UserAccounts accounts) {
858 synchronized (accounts.mReceiversForType) {
859 if (accountTypes == null) {
860 // null for any type
861 accountTypes = new String[] {null};
862 }
863 for (String type : accountTypes) {
864 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
865 if (receivers == null) {
866 receivers = new HashMap<>();
867 accounts.mReceiversForType.put(type, receivers);
868 }
869 Integer cnt = receivers.get(opPackageName);
870 receivers.put(opPackageName, cnt != null ? cnt + 1 : 1);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800871 }
872 }
873 }
874
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700875 @Override
876 public void unregisterAccountListener(String[] accountTypes, String opPackageName) {
877 int callingUid = Binder.getCallingUid();
878 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700879 int userId = UserHandle.getCallingUserId();
880 long identityToken = clearCallingIdentity();
881 try {
882 UserAccounts accounts = getUserAccounts(userId);
883 unregisterAccountListener(accountTypes, opPackageName, accounts);
884 } finally {
885 restoreCallingIdentity(identityToken);
886 }
887 }
888
889 private void unregisterAccountListener(String[] accountTypes, String opPackageName,
890 UserAccounts accounts) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700891 synchronized (accounts.mReceiversForType) {
892 if (accountTypes == null) {
893 // null for any type
894 accountTypes = new String[] {null};
895 }
896 for (String type : accountTypes) {
897 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
898 if (receivers == null || receivers.get(opPackageName) == null) {
899 throw new IllegalArgumentException("attempt to unregister wrong receiver");
900 }
901 Integer cnt = receivers.get(opPackageName);
902 if (cnt == 1) {
903 receivers.remove(opPackageName);
904 } else {
905 receivers.put(opPackageName, cnt - 1);
906 }
907 }
908 }
909 }
910
911 // Send notification to all packages which can potentially see the account
912 private void sendNotificationAccountUpdated(Account account, UserAccounts accounts) {
913 Map<String, Integer> packagesToVisibility = getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700914
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700915 for (Entry<String, Integer> packageToVisibility : packagesToVisibility.entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700916 if ((packageToVisibility.getValue() != AccountManager.VISIBILITY_NOT_VISIBLE)
917 && (packageToVisibility.getValue()
918 != AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE)) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700919 notifyPackage(packageToVisibility.getKey(), accounts);
920 }
921 }
922 }
923
924 /**
925 * Sends a direct intent to a package, notifying it of account visibility change.
926 *
927 * @param packageName to send Account to
928 * @param accounts UserAccount that currently hosts the account
929 */
930 private void notifyPackage(String packageName, UserAccounts accounts) {
931 Intent intent = new Intent(AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED);
932 intent.setPackage(packageName);
933 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
934 mContext.sendBroadcastAsUser(intent, new UserHandle(accounts.userId));
935 }
936
937 // Returns a map from package name to visibility, for packages subscribed
938 // to notifications about any account type, or type of provided account
939 // account type or all types.
940 private Map<String, Integer> getRequestingPackages(Account account, UserAccounts accounts) {
941 Set<String> packages = new HashSet<>();
942 synchronized (accounts.mReceiversForType) {
943 for (String type : new String[] {account.type, null}) {
944 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
945 if (receivers != null) {
946 packages.addAll(receivers.keySet());
947 }
948 }
949 }
950 Map<String, Integer> result = new HashMap<>();
951 for (String packageName : packages) {
952 result.put(packageName, resolveAccountVisibility(account, packageName, accounts));
953 }
954 return result;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800955 }
956
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700957 // Returns a list of packages listening to ACTION_ACCOUNT_REMOVED able to see the account.
958 private List<String> getAccountRemovedReceivers(Account account, UserAccounts accounts) {
959 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
960 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
961 List<ResolveInfo> receivers =
962 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
963 List<String> result = new ArrayList<>();
964 if (receivers == null) {
965 return result;
966 }
967 for (ResolveInfo resolveInfo: receivers) {
968 String packageName = resolveInfo.activityInfo.applicationInfo.packageName;
969 int visibility = resolveAccountVisibility(account, packageName, accounts);
970 if (visibility == AccountManager.VISIBILITY_VISIBLE
971 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
972 result.add(packageName);
973 }
974 }
975 return result;
976 }
977
978 // Returns true if given package is listening to ACTION_ACCOUNT_REMOVED and can see the account.
979 private boolean shouldNotifyPackageOnAccountRemoval(Account account,
980 String packageName, UserAccounts accounts) {
981 int visibility = resolveAccountVisibility(account, packageName, accounts);
982 if (visibility != AccountManager.VISIBILITY_VISIBLE
983 && visibility != AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
984 return false;
985 }
986
987 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
988 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
989 intent.setPackage(packageName);
990 List<ResolveInfo> receivers =
991 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
992 return (receivers != null && receivers.size() > 0);
993 }
994
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800995 private boolean packageExistsForUser(String packageName, int userId) {
996 try {
997 long identityToken = clearCallingIdentity();
998 try {
999 mPackageManager.getPackageUidAsUser(packageName, userId);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -07001000 return true;
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001001 } finally {
1002 restoreCallingIdentity(identityToken);
1003 }
1004 } catch (NameNotFoundException e) {
1005 return false;
1006 }
1007 }
1008
1009 /**
1010 * Returns true if packageName is one of special values.
1011 */
1012 private boolean isSpecialPackageKey(String packageName) {
1013 return (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)
1014 || AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName));
1015 }
1016
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001017 private void sendAccountsChangedBroadcast(int userId) {
1018 Log.i(TAG, "the accounts changed, sending broadcast of "
1019 + ACCOUNTS_CHANGED_INTENT.getAction());
1020 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001021 }
1022
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001023 private void sendAccountRemovedBroadcast(Account account, String packageName, int userId) {
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001024 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1025 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001026 intent.setPackage(packageName);
1027 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
1028 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001029 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
1030 }
1031
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001032 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -07001033 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1034 throws RemoteException {
1035 try {
1036 return super.onTransact(code, data, reply, flags);
1037 } catch (RuntimeException e) {
1038 // The account manager only throws security exceptions, so let's
1039 // log all others.
1040 if (!(e instanceof SecurityException)) {
1041 Slog.wtf(TAG, "Account Manager Crash", e);
1042 }
1043 throw e;
1044 }
1045 }
1046
Amith Yamasani258848d2012-08-10 17:06:33 -07001047 private UserManager getUserManager() {
1048 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001049 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -07001050 }
1051 return mUserManager;
1052 }
1053
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001054 /**
1055 * Validate internal set of accounts against installed authenticators for
1056 * given user. Clears cached authenticators before validating.
1057 */
1058 public void validateAccounts(int userId) {
1059 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001060 // Invalidate user-specific cache to make sure we catch any
1061 // removed authenticators.
1062 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
1063 }
1064
1065 /**
1066 * Validate internal set of accounts against installed authenticators for
1067 * given user. Clear cached authenticators before validating when requested.
1068 */
1069 private void validateAccountsInternal(
1070 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001071 if (Log.isLoggable(TAG, Log.DEBUG)) {
1072 Log.d(TAG, "validateAccountsInternal " + accounts.userId
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001073 + " isCeDatabaseAttached=" + accounts.accountsDb.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001074 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001075 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001076
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001077 if (invalidateAuthenticatorCache) {
1078 mAuthenticatorCache.invalidateCache(accounts.userId);
1079 }
1080
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001081 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
1082 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001083 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001084
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001085 synchronized (accounts.dbLock) {
1086 synchronized (accounts.cacheLock) {
1087 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001088
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001089 // Get a map of stored authenticator types to UID
1090 final AccountsDb accountsDb = accounts.accountsDb;
1091 Map<String, Integer> metaAuthUid = accountsDb.findMetaAuthUid();
1092 // Create a list of authenticator type whose previous uid no longer exists
1093 HashSet<String> obsoleteAuthType = Sets.newHashSet();
1094 SparseBooleanArray knownUids = null;
1095 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
1096 String type = authToUidEntry.getKey();
1097 int uid = authToUidEntry.getValue();
1098 Integer knownUid = knownAuth.get(type);
1099 if (knownUid != null && uid == knownUid) {
1100 // Remove it from the knownAuth list if it's unchanged.
1101 knownAuth.remove(type);
1102 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001103 /*
1104 * The authenticator is presently not cached and should only be triggered
1105 * when we think an authenticator has been removed (or is being updated).
1106 * But we still want to check if any data with the associated uid is
1107 * around. This is an (imperfect) signal that the package may be updating.
1108 *
1109 * A side effect of this is that an authenticator sharing a uid with
1110 * multiple apps won't get its credentials wiped as long as some app with
1111 * that uid is still on the device. But I suspect that this is a rare case.
1112 * And it isn't clear to me how an attacker could really exploit that
1113 * feature.
1114 *
1115 * The upshot is that we don't have to worry about accounts getting
1116 * uninstalled while the authenticator's package is being updated.
1117 *
1118 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001119 if (knownUids == null) {
1120 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
1121 }
1122 if (!knownUids.get(uid)) {
1123 // The authenticator is not presently available to the cache. And the
1124 // package no longer has a data directory (so we surmise it isn't
1125 // updating). So purge its data from the account databases.
1126 obsoleteAuthType.add(type);
1127 // And delete it from the TABLE_META
1128 accountsDb.deleteMetaByAuthTypeAndUid(type, uid);
1129 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001130 }
1131 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001132
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001133 // Add the newly registered authenticator to TABLE_META. If old authenticators have
1134 // been re-enabled (after being updated for example), then we just overwrite the old
1135 // values.
1136 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1137 accountsDb.insertOrReplaceMetaAuthTypeAndUid(entry.getKey(), entry.getValue());
1138 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001139
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001140 final Map<Long, Account> accountsMap = accountsDb.findAllDeAccounts();
1141 try {
1142 accounts.accountCache.clear();
1143 final HashMap<String, ArrayList<String>> accountNamesByType
1144 = new LinkedHashMap<>();
1145 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1146 final long accountId = accountEntry.getKey();
1147 final Account account = accountEntry.getValue();
1148 if (obsoleteAuthType.contains(account.type)) {
1149 Slog.w(TAG, "deleting account " + account.name + " because type "
1150 + account.type
1151 + "'s registered authenticator no longer exist.");
1152 Map<String, Integer> packagesToVisibility =
1153 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001154 List<String> accountRemovedReceivers =
1155 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001156 accountsDb.beginTransaction();
1157 try {
1158 accountsDb.deleteDeAccount(accountId);
1159 // Also delete from CE table if user is unlocked; if user is
1160 // currently locked the account will be removed later by
1161 // syncDeCeAccountsLocked
1162 if (userUnlocked) {
1163 accountsDb.deleteCeAccount(accountId);
1164 }
1165 accountsDb.setTransactionSuccessful();
1166 } finally {
1167 accountsDb.endTransaction();
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001168 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001169 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001170
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001171 logRecord(AccountsDb.DEBUG_ACTION_AUTHENTICATOR_REMOVE,
1172 AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001173
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001174 accounts.userDataCache.remove(account);
1175 accounts.authTokenCache.remove(account);
1176 accounts.accountTokenCaches.remove(account);
1177 accounts.visibilityCache.remove(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001178
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001179 for (Entry<String, Integer> packageToVisibility :
1180 packagesToVisibility.entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001181 if (shouldNotifyOnVisibilityChange(packageToVisibility.getValue(),
1182 AccountManager.VISIBILITY_NOT_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001183 notifyPackage(packageToVisibility.getKey(), accounts);
1184 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001185 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001186 for (String packageName : accountRemovedReceivers) {
1187 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
1188 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001189 } else {
1190 ArrayList<String> accountNames = accountNamesByType.get(account.type);
1191 if (accountNames == null) {
1192 accountNames = new ArrayList<>();
1193 accountNamesByType.put(account.type, accountNames);
1194 }
1195 accountNames.add(account.name);
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001196 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001197 }
1198 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
1199 final String accountType = cur.getKey();
1200 final ArrayList<String> accountNames = cur.getValue();
1201 final Account[] accountsForType = new Account[accountNames.size()];
1202 for (int i = 0; i < accountsForType.length; i++) {
1203 accountsForType[i] = new Account(accountNames.get(i), accountType,
1204 UUID.randomUUID().toString());
Fred Quintana56285a62010-12-02 14:20:51 -08001205 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001206 accounts.accountCache.put(accountType, accountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08001207 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001208 accounts.visibilityCache.putAll(accountsDb.findAllVisibilityValues());
1209 } finally {
1210 if (accountDeleted) {
1211 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintana56285a62010-12-02 14:20:51 -08001212 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001213 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001214 }
1215 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001216 }
1217
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001218 private boolean shouldNotifyOnVisibilityChange(int oldVisibility, int newVisibility) {
1219 boolean oldVisible = (oldVisibility == AccountManager.VISIBILITY_VISIBLE) ||
1220 (oldVisibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
1221 boolean newVisible = (newVisibility == AccountManager.VISIBILITY_VISIBLE) ||
1222 (newVisibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
1223 return oldVisible == newVisible;
1224 }
1225
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001226 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1227 // Get the UIDs of all apps that might have data on the device. We want
1228 // to preserve user data if the app might otherwise be storing data.
1229 List<PackageInfo> pkgsWithData =
1230 mPackageManager.getInstalledPackagesAsUser(
1231 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1232 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1233 for (PackageInfo pkgInfo : pkgsWithData) {
1234 if (pkgInfo.applicationInfo != null
1235 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1236 knownUids.put(pkgInfo.applicationInfo.uid, true);
1237 }
1238 }
1239 return knownUids;
1240 }
1241
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001242 static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001243 Context context,
1244 int userId) {
1245 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001246 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1247 }
1248
1249 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1250 IAccountAuthenticatorCache authCache,
1251 int userId) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08001252 HashMap<String, Integer> knownAuth = new LinkedHashMap<>();
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001253 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1254 .getAllServices(userId)) {
1255 knownAuth.put(service.type.type, service.uid);
1256 }
1257 return knownAuth;
1258 }
1259
Amith Yamasani04e0d262012-02-14 11:50:53 -08001260 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001261 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001262 }
1263
1264 protected UserAccounts getUserAccounts(int userId) {
1265 synchronized (mUsers) {
1266 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001267 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001268 if (accounts == null) {
Fyodor Kupolovda993802016-09-21 14:47:10 -07001269 File preNDbFile = new File(mInjector.getPreNDatabaseName(userId));
1270 File deDbFile = new File(mInjector.getDeDatabaseName(userId));
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001271 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001272 initializeDebugDbSizeAndCompileSqlStatementForLogging(accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001273 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001274 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001275 validateAccounts = true;
1276 }
1277 // open CE database if necessary
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001278 if (!accounts.accountsDb.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001279 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001280 synchronized (accounts.dbLock) {
1281 synchronized (accounts.cacheLock) {
1282 File ceDatabaseFile = new File(mInjector.getCeDatabaseName(userId));
1283 accounts.accountsDb.attachCeDatabase(ceDatabaseFile);
1284 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001285 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001286 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001287 }
1288 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001289 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 }
1291 return accounts;
1292 }
1293 }
1294
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001295 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1296 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001297 List<Account> accountsToRemove = accounts.accountsDb.findCeAccountsNotInDe();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001298 if (!accountsToRemove.isEmpty()) {
1299 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
1300 + accounts.userId + " was locked. Removing accounts from CE tables");
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001301 logRecord(accounts, AccountsDb.DEBUG_ACTION_SYNC_DE_CE_ACCOUNTS,
1302 AccountsDb.TABLE_ACCOUNTS);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001303
1304 for (Account account : accountsToRemove) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001305 removeAccountInternal(accounts, account, Process.SYSTEM_UID);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001306 }
1307 }
1308 }
1309
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001310 private void purgeOldGrantsAll() {
1311 synchronized (mUsers) {
1312 for (int i = 0; i < mUsers.size(); i++) {
1313 purgeOldGrants(mUsers.valueAt(i));
1314 }
1315 }
1316 }
1317
1318 private void purgeOldGrants(UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001319 synchronized (accounts.dbLock) {
1320 synchronized (accounts.cacheLock) {
1321 List<Integer> uids = accounts.accountsDb.findAllUidGrants();
1322 for (int uid : uids) {
1323 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1324 if (packageExists) {
1325 continue;
1326 }
1327 Log.d(TAG, "deleting grants for UID " + uid
1328 + " because its package is no longer installed");
1329 accounts.accountsDb.deleteGrantsByUid(uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001330 }
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001331 }
1332 }
1333 }
1334
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001335 private void removeVisibilityValuesForPackage(String packageName) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001336 if (isSpecialPackageKey(packageName)) {
1337 return;
1338 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001339 synchronized (mUsers) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001340 int numberOfUsers = mUsers.size();
1341 for (int i = 0; i < numberOfUsers; i++) {
1342 UserAccounts accounts = mUsers.valueAt(i);
1343 try {
1344 mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
1345 } catch (NameNotFoundException e) {
1346 // package does not exist - remove visibility values
1347 accounts.accountsDb.deleteAccountVisibilityForPackage(packageName);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001348 synchronized (accounts.dbLock) {
1349 synchronized (accounts.cacheLock) {
1350 for (Account account : accounts.visibilityCache.keySet()) {
1351 Map<String, Integer> accountVisibility =
1352 getPackagesAndVisibilityForAccountLocked(account, accounts);
1353 accountVisibility.remove(packageName);
1354 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001355 }
1356 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001357 }
1358 }
1359 }
1360 }
1361
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001362
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -07001363 private void onCleanupUser(int userId) {
1364 Log.i(TAG, "onCleanupUser " + userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001365 UserAccounts accounts;
1366 synchronized (mUsers) {
1367 accounts = mUsers.get(userId);
1368 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001369 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001370 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001371 if (accounts != null) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001372 synchronized (accounts.dbLock) {
1373 synchronized (accounts.cacheLock) {
1374 accounts.accountsDb.close();
1375 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001376 }
Amith Yamasani13593602012-03-22 16:16:17 -07001377 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001378 }
1379
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001380 @VisibleForTesting
1381 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001382 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1383 }
1384
1385 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001386 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1387 Log.v(TAG, "onUserUnlocked " + userId);
1388 }
1389 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001390 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001391 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001392 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001393 syncSharedAccounts(userId);
1394 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001395
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001396 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001397 // Check if there's a shared account that needs to be created as an account
1398 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1399 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001400 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001401 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001402 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001403 : UserHandle.USER_SYSTEM;
1404 if (parentUserId < 0) {
1405 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1406 return;
1407 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001408 for (Account sa : sharedAccounts) {
1409 if (ArrayUtils.contains(accounts, sa)) continue;
1410 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001411 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001412 }
1413 }
1414
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001415 @Override
1416 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001417 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001418 }
1419
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001420 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001421 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001422 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001423 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1424 Log.v(TAG, "getPassword: " + account
1425 + ", caller's uid " + Binder.getCallingUid()
1426 + ", pid " + Binder.getCallingPid());
1427 }
Fred Quintana382601f2010-03-25 12:25:10 -07001428 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001429 int userId = UserHandle.getCallingUserId();
1430 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001431 String msg = String.format(
1432 "uid %s cannot get secrets for accounts of type: %s",
1433 callingUid,
1434 account.type);
1435 throw new SecurityException(msg);
1436 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001437 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001438 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001439 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001440 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001441 } finally {
1442 restoreCallingIdentity(identityToken);
1443 }
1444 }
1445
Amith Yamasani04e0d262012-02-14 11:50:53 -08001446 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001447 if (account == null) {
1448 return null;
1449 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001450 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001451 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1452 return null;
1453 }
Fred Quintana31957f12009-10-21 13:43:10 -07001454
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001455 synchronized (accounts.dbLock) {
1456 synchronized (accounts.cacheLock) {
1457 return accounts.accountsDb
1458 .findAccountPasswordByNameAndType(account.name, account.type);
1459 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001460 }
1461 }
1462
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001463 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001464 public String getPreviousName(Account account) {
1465 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1466 Log.v(TAG, "getPreviousName: " + account
1467 + ", caller's uid " + Binder.getCallingUid()
1468 + ", pid " + Binder.getCallingPid());
1469 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001470 Preconditions.checkNotNull(account, "account cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001471 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001472 long identityToken = clearCallingIdentity();
1473 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001474 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001475 return readPreviousNameInternal(accounts, account);
1476 } finally {
1477 restoreCallingIdentity(identityToken);
1478 }
1479 }
1480
1481 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1482 if (account == null) {
1483 return null;
1484 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001485 synchronized (accounts.dbLock) {
1486 synchronized (accounts.cacheLock) {
1487 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1488 if (previousNameRef == null) {
1489 String previousName = accounts.accountsDb.findDeAccountPreviousName(account);
1490 previousNameRef = new AtomicReference<>(previousName);
1491 accounts.previousNameCache.put(account, previousNameRef);
1492 return previousName;
1493 } else {
1494 return previousNameRef.get();
1495 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001496 }
1497 }
1498 }
1499
1500 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001501 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001502 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001503 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001504 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1505 account, key, callingUid, Binder.getCallingPid());
1506 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001507 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001508 Preconditions.checkNotNull(account, "account cannot be null");
1509 Preconditions.checkNotNull(key, "key cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001510 int userId = UserHandle.getCallingUserId();
1511 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001512 String msg = String.format(
1513 "uid %s cannot get user data for accounts of type: %s",
1514 callingUid,
1515 account.type);
1516 throw new SecurityException(msg);
1517 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001518 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001519 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1520 return null;
1521 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001522 long identityToken = clearCallingIdentity();
1523 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001524 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001525 if (!accountExistsCache(accounts, account)) {
1526 return null;
Simranjit Kohli858511c2016-03-10 18:36:11 +00001527 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001528 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001529 } finally {
1530 restoreCallingIdentity(identityToken);
1531 }
1532 }
1533
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001534 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001535 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001536 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001537 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1538 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001539 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001540 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001541 + ", pid " + Binder.getCallingPid());
1542 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001543 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001544 if (isCrossUser(callingUid, userId)) {
1545 throw new SecurityException(
1546 String.format(
1547 "User %s tying to get authenticator types for %s" ,
1548 UserHandle.getCallingUserId(),
1549 userId));
1550 }
1551
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001552 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001553 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001554 return getAuthenticatorTypesInternal(userId);
1555
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001556 } finally {
1557 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001558 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001559 }
1560
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001561 /**
1562 * Should only be called inside of a clearCallingIdentity block.
1563 */
1564 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
Fyodor Kupolov81446482016-08-24 11:27:49 -07001565 mAuthenticatorCache.updateServices(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001566 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1567 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1568 AuthenticatorDescription[] types =
1569 new AuthenticatorDescription[authenticatorCollection.size()];
1570 int i = 0;
1571 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1572 : authenticatorCollection) {
1573 types[i] = authenticator.type;
1574 i++;
1575 }
1576 return types;
1577 }
1578
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001579 private boolean isCrossUser(int callingUid, int userId) {
1580 return (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001581 && callingUid != Process.SYSTEM_UID
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001582 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001583 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1584 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001585 }
1586
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001587 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001588 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001589 return addAccountExplicitlyWithVisibility(account, password, extras, null);
Fred Quintana60307342009-03-24 22:48:12 -07001590 }
1591
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001592 @Override
1593 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001594 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001595 int callingUid = Binder.getCallingUid();
1596 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1597 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001598 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001599 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001600 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1601 final UserAccounts toAccounts = getUserAccounts(userTo);
1602 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001603 if (response != null) {
1604 Bundle result = new Bundle();
1605 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1606 try {
1607 response.onResult(result);
1608 } catch (RemoteException e) {
1609 Slog.w(TAG, "Failed to report error back to the client." + e);
1610 }
1611 }
1612 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001613 }
1614
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001615 Slog.d(TAG, "Copying account " + account.name
1616 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001617 long identityToken = clearCallingIdentity();
1618 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001619 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001620 false /* stripAuthTokenFromResult */, account.name,
1621 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001622 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001623 protected String toDebugString(long now) {
1624 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1625 + ", " + account.type;
1626 }
1627
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001628 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001629 public void run() throws RemoteException {
1630 mAuthenticator.getAccountCredentialsForCloning(this, account);
1631 }
1632
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001633 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001634 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001635 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001636 if (result != null
1637 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1638 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001639 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001640 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001641 super.onResult(result);
1642 }
1643 }
1644 }.bind();
1645 } finally {
1646 restoreCallingIdentity(identityToken);
1647 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001648 }
1649
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001650 @Override
1651 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001652 final int callingUid = Binder.getCallingUid();
1653 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1654 String msg = String.format(
1655 "accountAuthenticated( account: %s, callerUid: %s)",
1656 account,
1657 callingUid);
1658 Log.v(TAG, msg);
1659 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001660 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001661 int userId = UserHandle.getCallingUserId();
1662 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001663 String msg = String.format(
1664 "uid %s cannot notify authentication for accounts of type: %s",
1665 callingUid,
1666 account.type);
1667 throw new SecurityException(msg);
1668 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001669
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001670 if (!canUserModifyAccounts(userId, callingUid) ||
1671 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001672 return false;
1673 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001674
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001675 long identityToken = clearCallingIdentity();
1676 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001677 UserAccounts accounts = getUserAccounts(userId);
1678 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001679 } finally {
1680 restoreCallingIdentity(identityToken);
1681 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001682 }
1683
1684 private boolean updateLastAuthenticatedTime(Account account) {
1685 final UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001686 synchronized (accounts.dbLock) {
1687 synchronized (accounts.cacheLock) {
1688 return accounts.accountsDb.updateAccountLastAuthenticatedTime(account);
1689 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001690 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001691 }
1692
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001693 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001694 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1695 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001696 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001697 long id = clearCallingIdentity();
1698 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001699 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001700 false /* stripAuthTokenFromResult */, account.name,
1701 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001702 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001703 protected String toDebugString(long now) {
1704 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1705 + ", " + account.type;
1706 }
1707
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001708 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001709 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001710 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov16bedd42017-03-30 10:00:49 -07001711 for (Account acc : getAccounts(parentUserId, mContext.getOpPackageName())) {
1712 if (acc.equals(account)) {
1713 mAuthenticator.addAccountFromCredentials(
1714 this, account, accountCredentials);
1715 break;
Amith Yamasani5be347b2013-03-31 17:44:31 -07001716 }
1717 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001718 }
1719
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001720 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001721 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001722 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001723 // TODO: Anything to do if if succedded?
1724 // TODO: If it failed: Show error notification? Should we remove the shadow
1725 // account to avoid retries?
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001726 // TODO: what we do with the visibility?
1727
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001728 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001729 }
1730
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001731 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001732 public void onError(int errorCode, String errorMessage) {
1733 super.onError(errorCode, errorMessage);
1734 // TODO: Show error notification to user
1735 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1736 }
1737
1738 }.bind();
1739 } finally {
1740 restoreCallingIdentity(id);
1741 }
1742 }
1743
Amith Yamasani04e0d262012-02-14 11:50:53 -08001744 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001745 Bundle extras, int callingUid, Map<String, Integer> packageToVisibility) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001746 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001747 if (account == null) {
1748 return false;
1749 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001750 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001751 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1752 + " is locked. callingUid=" + callingUid);
1753 return false;
1754 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001755 synchronized (accounts.dbLock) {
1756 synchronized (accounts.cacheLock) {
1757 accounts.accountsDb.beginTransaction();
1758 try {
1759 if (accounts.accountsDb.findCeAccountId(account) >= 0) {
1760 Log.w(TAG, "insertAccountIntoDatabase: " + account
1761 + ", skipping since the account already exists");
1762 return false;
1763 }
1764 long accountId = accounts.accountsDb.insertCeAccount(account, password);
1765 if (accountId < 0) {
1766 Log.w(TAG, "insertAccountIntoDatabase: " + account
1767 + ", skipping the DB insert failed");
1768 return false;
1769 }
1770 // Insert into DE table
1771 if (accounts.accountsDb.insertDeAccount(account, accountId) < 0) {
1772 Log.w(TAG, "insertAccountIntoDatabase: " + account
1773 + ", skipping the DB insert failed");
1774 return false;
1775 }
1776 if (extras != null) {
1777 for (String key : extras.keySet()) {
1778 final String value = extras.getString(key);
1779 if (accounts.accountsDb.insertExtra(accountId, key, value) < 0) {
1780 Log.w(TAG, "insertAccountIntoDatabase: " + account
1781 + ", skipping since insertExtra failed for key " + key);
1782 return false;
1783 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001784 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001785 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001786
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001787 if (packageToVisibility != null) {
1788 for (Entry<String, Integer> entry : packageToVisibility.entrySet()) {
1789 setAccountVisibility(account, entry.getKey() /* package */,
1790 entry.getValue() /* visibility */, false /* notify */,
1791 accounts);
1792 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001793 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001794 accounts.accountsDb.setTransactionSuccessful();
1795
1796 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
1797 accountId,
1798 accounts, callingUid);
1799
1800 insertAccountIntoCacheLocked(accounts, account);
1801 } finally {
1802 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001803 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001804 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001805 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001806 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1807 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001808 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001809
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001810 sendNotificationAccountUpdated(account, accounts);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001811 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1812 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001813
Amith Yamasani5be347b2013-03-31 17:44:31 -07001814 return true;
1815 }
1816
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001817 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001818 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001819 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001820 }
1821 }
1822
Amith Yamasani5be347b2013-03-31 17:44:31 -07001823 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001824 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001825 * running, then clone the account too.
1826 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001827 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001828 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001829 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001830 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001831 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001832 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001833 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001834 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07001835 mHandler.sendMessage(mHandler.obtainMessage(
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001836 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001837 }
1838 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001839 }
1840 }
1841
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001842 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001843 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001844 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001845 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001846 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08001847 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1848 Log.v(TAG, "hasFeatures: " + account
1849 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001850 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001851 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001852 + ", pid " + Binder.getCallingPid());
1853 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001854 Preconditions.checkArgument(account != null, "account cannot be null");
1855 Preconditions.checkArgument(response != null, "response cannot be null");
1856 Preconditions.checkArgument(features != null, "features cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001857 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001858 checkReadAccountsPermitted(callingUid, account.type, userId,
1859 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001860
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001861 long identityToken = clearCallingIdentity();
1862 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001863 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001864 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001865 } finally {
1866 restoreCallingIdentity(identityToken);
1867 }
1868 }
1869
1870 private class TestFeaturesSession extends Session {
1871 private final String[] mFeatures;
1872 private final Account mAccount;
1873
Amith Yamasani04e0d262012-02-14 11:50:53 -08001874 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001875 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001876 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001877 true /* stripAuthTokenFromResult */, account.name,
1878 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001879 mFeatures = features;
1880 mAccount = account;
1881 }
1882
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001883 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001884 public void run() throws RemoteException {
1885 try {
1886 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1887 } catch (RemoteException e) {
1888 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1889 }
1890 }
1891
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001892 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001893 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001894 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001895 IAccountManagerResponse response = getResponseAndClose();
1896 if (response != null) {
1897 try {
1898 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001899 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001900 return;
1901 }
Fred Quintana56285a62010-12-02 14:20:51 -08001902 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1903 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1904 + response);
1905 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001906 final Bundle newResult = new Bundle();
1907 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1908 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1909 response.onResult(newResult);
1910 } catch (RemoteException e) {
1911 // if the caller is dead then there is no one to care about remote exceptions
1912 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1913 Log.v(TAG, "failure while notifying response", e);
1914 }
1915 }
1916 }
1917 }
1918
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001919 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001920 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001921 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001922 + ", " + mAccount
1923 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1924 }
1925 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001926
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001927 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001928 public void renameAccount(
1929 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001930 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001931 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1932 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001933 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001934 + ", pid " + Binder.getCallingPid());
1935 }
1936 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001937 int userId = UserHandle.getCallingUserId();
1938 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001939 String msg = String.format(
1940 "uid %s cannot rename accounts of type: %s",
1941 callingUid,
1942 accountToRename.type);
1943 throw new SecurityException(msg);
1944 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001945 long identityToken = clearCallingIdentity();
1946 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001947 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001948 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001949 Bundle result = new Bundle();
1950 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1951 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001952 result.putString(AccountManager.KEY_ACCOUNT_ACCESS_ID,
1953 resultingAccount.getAccessId());
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001954 try {
1955 response.onResult(result);
1956 } catch (RemoteException e) {
1957 Log.w(TAG, e.getMessage());
1958 }
1959 } finally {
1960 restoreCallingIdentity(identityToken);
1961 }
1962 }
1963
1964 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001965 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001966 Account resultAccount = null;
1967 /*
1968 * Cancel existing notifications. Let authenticators
1969 * re-post notifications as required. But we don't know if
1970 * the authenticators have bound their notifications to
1971 * now stale account name data.
1972 *
1973 * With a rename api, we might not need to do this anymore but it
1974 * shouldn't hurt.
1975 */
1976 cancelNotification(
1977 getSigninRequiredNotificationId(accounts, accountToRename),
Chris Wren717a8812017-03-31 15:34:39 -04001978 new UserHandle(accounts.userId));
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001979 synchronized(accounts.credentialsPermissionNotificationIds) {
1980 for (Pair<Pair<Account, String>, Integer> pair:
1981 accounts.credentialsPermissionNotificationIds.keySet()) {
1982 if (accountToRename.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04001983 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001984 cancelNotification(id, new UserHandle(accounts.userId));
1985 }
1986 }
1987 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001988 synchronized (accounts.dbLock) {
1989 synchronized (accounts.cacheLock) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001990 List<String> accountRemovedReceivers =
1991 getAccountRemovedReceivers(accountToRename, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001992 accounts.accountsDb.beginTransaction();
1993 Account renamedAccount = new Account(newName, accountToRename.type);
1994 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
1995 Log.e(TAG, "renameAccount failed - account with new name already exists");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001996 return null;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001997 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001998 try {
1999 final long accountId = accounts.accountsDb.findDeAccountId(accountToRename);
2000 if (accountId >= 0) {
2001 accounts.accountsDb.renameCeAccount(accountId, newName);
2002 if (accounts.accountsDb.renameDeAccount(
2003 accountId, newName, accountToRename.name)) {
2004 accounts.accountsDb.setTransactionSuccessful();
2005 } else {
2006 Log.e(TAG, "renameAccount failed");
2007 return null;
2008 }
2009 } else {
2010 Log.e(TAG, "renameAccount failed - old account does not exist");
2011 return null;
2012 }
2013 } finally {
2014 accounts.accountsDb.endTransaction();
2015 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002016 /*
2017 * Database transaction was successful. Clean up cached
2018 * data associated with the account in the user profile.
2019 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002020 renamedAccount = insertAccountIntoCacheLocked(accounts, renamedAccount);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002021 /*
2022 * Extract the data and token caches before removing the
2023 * old account to preserve the user data associated with
2024 * the account.
2025 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002026 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
2027 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
2028 Map<String, Integer> tmpVisibility = accounts.visibilityCache.get(accountToRename);
2029 removeAccountFromCacheLocked(accounts, accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002030 /*
2031 * Update the cached data associated with the renamed
2032 * account.
2033 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002034 accounts.userDataCache.put(renamedAccount, tmpData);
2035 accounts.authTokenCache.put(renamedAccount, tmpTokens);
2036 accounts.visibilityCache.put(renamedAccount, tmpVisibility);
2037 accounts.previousNameCache.put(
2038 renamedAccount,
2039 new AtomicReference<>(accountToRename.name));
2040 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002041
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002042 int parentUserId = accounts.userId;
2043 if (canHaveProfile(parentUserId)) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002044 /*
2045 * Owner or system user account was renamed, rename the account for
2046 * those users with which the account was shared.
2047 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002048 List<UserInfo> users = getUserManager().getUsers(true);
2049 for (UserInfo user : users) {
2050 if (user.isRestricted()
2051 && (user.restrictedProfileParentId == parentUserId)) {
2052 renameSharedAccountAsUser(accountToRename, newName, user.id);
2053 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002054 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002055 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002056
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002057 sendNotificationAccountUpdated(resultAccount, accounts);
2058 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002059 for (String packageName : accountRemovedReceivers) {
2060 sendAccountRemovedBroadcast(accountToRename, packageName, accounts.userId);
2061 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002062 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002063 }
2064 return resultAccount;
2065 }
2066
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002067 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002068 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002069 return userInfo != null && userInfo.canHaveProfile();
2070 }
2071
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002072 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002073 public void removeAccount(IAccountManagerResponse response, Account account,
2074 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002075 removeAccountAsUser(
2076 response,
2077 account,
2078 expectActivityLaunch,
2079 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002080 }
2081
2082 @Override
2083 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002084 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002085 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002086 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2087 Log.v(TAG, "removeAccount: " + account
2088 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002089 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002090 + ", pid " + Binder.getCallingPid()
2091 + ", for user id " + userId);
2092 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002093 Preconditions.checkArgument(account != null, "account cannot be null");
2094 Preconditions.checkArgument(response != null, "response cannot be null");
2095
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002096 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002097 if (isCrossUser(callingUid, userId)) {
2098 throw new SecurityException(
2099 String.format(
2100 "User %s tying remove account for %s" ,
2101 UserHandle.getCallingUserId(),
2102 userId));
2103 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002104 /*
2105 * Only the system or authenticator should be allowed to remove accounts for that
2106 * authenticator. This will let users remove accounts (via Settings in the system) but not
2107 * arbitrary applications (like competing authenticators).
2108 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002109 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00002110 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
2111 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002112 String msg = String.format(
2113 "uid %s cannot remove accounts of type: %s",
2114 callingUid,
2115 account.type);
2116 throw new SecurityException(msg);
2117 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002118 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002119 try {
2120 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2121 "User cannot modify accounts");
2122 } catch (RemoteException re) {
2123 }
2124 return;
2125 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002126 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002127 try {
2128 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2129 "User cannot modify accounts of this type (policy).");
2130 } catch (RemoteException re) {
2131 }
2132 return;
2133 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002134 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002135 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002136 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002137 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002138 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002139 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002140 if (account.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002141 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002142 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002143 }
2144 }
2145 }
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002146 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002147 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002148 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2149 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002150 accountId,
2151 accounts,
2152 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002153 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002154 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2155 } finally {
2156 restoreCallingIdentity(identityToken);
2157 }
2158 }
2159
2160 @Override
2161 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002162 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2164 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002165 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002166 + ", pid " + Binder.getCallingPid());
2167 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002168 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002169 if (account == null) {
2170 /*
2171 * Null accounts should result in returning false, as per
2172 * AccountManage.addAccountExplicitly(...) java doc.
2173 */
2174 Log.e(TAG, "account is null");
2175 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002176 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002177 String msg = String.format(
2178 "uid %s cannot explicitly add accounts of type: %s",
2179 callingUid,
2180 account.type);
2181 throw new SecurityException(msg);
2182 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002183 UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002184 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002185 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002186 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2187 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002188 accountId,
2189 accounts,
2190 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002191 long identityToken = clearCallingIdentity();
2192 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002193 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002194 } finally {
2195 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002196 }
Fred Quintana60307342009-03-24 22:48:12 -07002197 }
2198
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002199 private class RemoveAccountSession extends Session {
2200 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002201 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002202 Account account, boolean expectActivityLaunch) {
2203 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002204 true /* stripAuthTokenFromResult */, account.name,
2205 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002206 mAccount = account;
2207 }
2208
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002209 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002210 protected String toDebugString(long now) {
2211 return super.toDebugString(now) + ", removeAccount"
2212 + ", account " + mAccount;
2213 }
2214
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002215 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002216 public void run() throws RemoteException {
2217 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2218 }
2219
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002220 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002221 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002222 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002223 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2224 && !result.containsKey(AccountManager.KEY_INTENT)) {
2225 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002226 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002227 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002228 }
2229 IAccountManagerResponse response = getResponseAndClose();
2230 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002231 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2232 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2233 + response);
2234 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002235 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002236 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002237 try {
2238 response.onResult(result2);
2239 } catch (RemoteException e) {
2240 // ignore
2241 }
2242 }
2243 }
2244 super.onResult(result);
2245 }
2246 }
2247
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002248 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002249 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002250 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002251 }
2252
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002253 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002254 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002255 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002256 if (!userUnlocked) {
2257 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2258 + " is still locked. CE data will be removed later");
2259 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002260 synchronized (accounts.dbLock) {
2261 synchronized (accounts.cacheLock) {
2262 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2263 accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002264 List<String> accountRemovedReceivers =
2265 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002266 accounts.accountsDb.beginTransaction();
2267 // Set to a dummy value, this will only be used if the database
2268 // transaction succeeds.
2269 long accountId = -1;
2270 try {
2271 accountId = accounts.accountsDb.findDeAccountId(account);
2272 if (accountId >= 0) {
2273 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002274 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002275 // always delete from CE table if CE storage is available
2276 // DE account could be removed while CE was locked
2277 if (userUnlocked) {
2278 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2279 if (ceAccountId >= 0) {
2280 accounts.accountsDb.deleteCeAccount(ceAccountId);
2281 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002282 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002283 accounts.accountsDb.setTransactionSuccessful();
2284 } finally {
2285 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002286 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002287 if (isChanged) {
2288 removeAccountFromCacheLocked(accounts, account);
2289 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2290 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002291 if ((packageToVisibility.getValue() == AccountManager.VISIBILITY_VISIBLE)
2292 || (packageToVisibility.getValue()
2293 == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002294 notifyPackage(packageToVisibility.getKey(), accounts);
2295 }
2296 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002297
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002298 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2299 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002300 for (String packageName : accountRemovedReceivers) {
2301 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
2302 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002303 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2304 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2305 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2306 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002307 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002308 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002309 long id = Binder.clearCallingIdentity();
2310 try {
2311 int parentUserId = accounts.userId;
2312 if (canHaveProfile(parentUserId)) {
2313 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002314 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002315 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002316 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002317 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002318 }
2319 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002320 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002321 } finally {
2322 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002323 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002324
2325 if (isChanged) {
2326 synchronized (accounts.credentialsPermissionNotificationIds) {
2327 for (Pair<Pair<Account, String>, Integer> key
2328 : accounts.credentialsPermissionNotificationIds.keySet()) {
2329 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002330 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002331 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002332 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002333 account, uid, false));
2334 }
2335 }
2336 }
2337 }
2338
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002339 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002340 }
2341
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002342 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002343 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002344 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002345 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2346 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002347 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2348 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002349 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002350 + ", pid " + Binder.getCallingPid());
2351 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002352 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002353 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002354 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002355 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002356 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002357 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002358 accounts.accountsDb.beginTransaction();
2359 try {
2360 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2361 accounts.accountsDb.setTransactionSuccessful();
2362 } finally {
2363 accounts.accountsDb.endTransaction();
2364 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002365 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002366 for (Pair<Account, String> tokenInfo : deletedTokens) {
2367 Account act = tokenInfo.first;
2368 String tokenType = tokenInfo.second;
2369 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002370 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002371 // wipe out cached token in memory.
2372 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002373 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002374 }
Fred Quintana60307342009-03-24 22:48:12 -07002375 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002376 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002377 }
2378 }
2379
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002380 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002381 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002382 // TODO Move to AccountsDB
2383 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002384 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002385
Fred Quintana33269202009-04-20 16:05:10 -07002386 try {
2387 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002388 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002389 String accountName = cursor.getString(1);
2390 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002391 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002392 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002393 }
Fred Quintana33269202009-04-20 16:05:10 -07002394 } finally {
2395 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002396 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002397 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002398 }
2399
Carlos Valdivia91979be2015-05-22 14:11:35 -07002400 private void saveCachedToken(
2401 UserAccounts accounts,
2402 Account account,
2403 String callerPkg,
2404 byte[] callerSigDigest,
2405 String tokenType,
2406 String token,
2407 long expiryMillis) {
2408
2409 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2410 return;
2411 }
2412 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002413 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002414 synchronized (accounts.cacheLock) {
2415 accounts.accountTokenCaches.put(
2416 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002417 }
2418 }
2419
Amith Yamasani04e0d262012-02-14 11:50:53 -08002420 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2421 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002422 if (account == null || type == null) {
2423 return false;
2424 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002425 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002426 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002427 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002428 accounts.accountsDb.beginTransaction();
2429 boolean updateCache = false;
2430 try {
2431 long accountId = accounts.accountsDb.findDeAccountId(account);
2432 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002433 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002434 }
2435 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2436 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2437 accounts.accountsDb.setTransactionSuccessful();
2438 updateCache = true;
2439 return true;
2440 }
2441 return false;
2442 } finally {
2443 accounts.accountsDb.endTransaction();
2444 if (updateCache) {
2445 synchronized (accounts.cacheLock) {
2446 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2447 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002448 }
Fred Quintana33269202009-04-20 16:05:10 -07002449 }
Fred Quintana60307342009-03-24 22:48:12 -07002450 }
2451 }
2452
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002453 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002454 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002455 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002456 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2457 Log.v(TAG, "peekAuthToken: " + account
2458 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002459 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002460 + ", pid " + Binder.getCallingPid());
2461 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002462 Preconditions.checkNotNull(account, "account cannot be null");
2463 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002464 int userId = UserHandle.getCallingUserId();
2465 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002466 String msg = String.format(
2467 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2468 callingUid,
2469 account.type);
2470 throw new SecurityException(msg);
2471 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002472 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002473 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2474 + callingUid);
2475 return null;
2476 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002477 long identityToken = clearCallingIdentity();
2478 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002479 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002480 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002481 } finally {
2482 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002483 }
Fred Quintana60307342009-03-24 22:48:12 -07002484 }
2485
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002486 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002487 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002488 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002489 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2490 Log.v(TAG, "setAuthToken: " + account
2491 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002492 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002493 + ", pid " + Binder.getCallingPid());
2494 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002495 Preconditions.checkNotNull(account, "account cannot be null");
2496 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002497 int userId = UserHandle.getCallingUserId();
2498 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002499 String msg = String.format(
2500 "uid %s cannot set auth tokens associated with accounts of type: %s",
2501 callingUid,
2502 account.type);
2503 throw new SecurityException(msg);
2504 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002505 long identityToken = clearCallingIdentity();
2506 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002507 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002508 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002509 } finally {
2510 restoreCallingIdentity(identityToken);
2511 }
Fred Quintana60307342009-03-24 22:48:12 -07002512 }
2513
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002514 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002515 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002516 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002517 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2518 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002519 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002520 + ", pid " + Binder.getCallingPid());
2521 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002522 Preconditions.checkNotNull(account, "account 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 set secrets for accounts of type: %s",
2527 callingUid,
2528 account.type);
2529 throw new SecurityException(msg);
2530 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002531 long identityToken = clearCallingIdentity();
2532 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002533 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002534 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002535 } finally {
2536 restoreCallingIdentity(identityToken);
2537 }
Fred Quintana60307342009-03-24 22:48:12 -07002538 }
2539
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002540 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2541 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002542 if (account == null) {
2543 return;
2544 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002545 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002546 synchronized (accounts.dbLock) {
2547 synchronized (accounts.cacheLock) {
2548 accounts.accountsDb.beginTransaction();
2549 try {
2550 final long accountId = accounts.accountsDb.findDeAccountId(account);
2551 if (accountId >= 0) {
2552 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2553 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2554 accounts.authTokenCache.remove(account);
2555 accounts.accountTokenCaches.remove(account);
2556 accounts.accountsDb.setTransactionSuccessful();
2557 // If there is an account whose password will be updated and the database
2558 // transactions succeed, then we say that a change has occured. Even if the
2559 // new password is the same as the old and there were no authtokens to
2560 // delete.
2561 isChanged = true;
2562 String action = (password == null || password.length() == 0) ?
2563 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2564 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2565 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2566 callingUid);
2567 }
2568 } finally {
2569 accounts.accountsDb.endTransaction();
2570 if (isChanged) {
2571 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2572 sendNotificationAccountUpdated(account, accounts);
2573 sendAccountsChangedBroadcast(accounts.userId);
2574 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002575 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002576 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002577 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002578 }
2579
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002580 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002581 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002582 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002583 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2584 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002585 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002586 + ", pid " + Binder.getCallingPid());
2587 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002588 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002589 int userId = UserHandle.getCallingUserId();
2590 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002591 String msg = String.format(
2592 "uid %s cannot clear passwords for accounts of type: %s",
2593 callingUid,
2594 account.type);
2595 throw new SecurityException(msg);
2596 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002597 long identityToken = clearCallingIdentity();
2598 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002599 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002600 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002601 } finally {
2602 restoreCallingIdentity(identityToken);
2603 }
Fred Quintana60307342009-03-24 22:48:12 -07002604 }
2605
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002606 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002607 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002608 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002609 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2610 Log.v(TAG, "setUserData: " + account
2611 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002612 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002613 + ", pid " + Binder.getCallingPid());
2614 }
Fred Quintana382601f2010-03-25 12:25:10 -07002615 if (key == null) throw new IllegalArgumentException("key is null");
2616 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002617 int userId = UserHandle.getCallingUserId();
2618 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002619 String msg = String.format(
2620 "uid %s cannot set user data for accounts of type: %s",
2621 callingUid,
2622 account.type);
2623 throw new SecurityException(msg);
2624 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002625 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002626 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002627 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002628 if (!accountExistsCache(accounts, account)) {
2629 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002630 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002631 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002632 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002633 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002634 }
2635 }
2636
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002637 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2638 synchronized (accounts.cacheLock) {
2639 if (accounts.accountCache.containsKey(account.type)) {
2640 for (Account acc : accounts.accountCache.get(account.type)) {
2641 if (acc.name.equals(account.name)) {
2642 return true;
2643 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002644 }
2645 }
2646 }
2647 return false;
2648 }
2649
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002650 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002651 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002652 synchronized (accounts.dbLock) {
2653 accounts.accountsDb.beginTransaction();
2654 try {
2655 long accountId = accounts.accountsDb.findDeAccountId(account);
2656 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002657 return;
2658 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002659 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2660 if (extrasId < 0) {
2661 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2662 if (extrasId < 0) {
2663 return;
2664 }
2665 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2666 return;
2667 }
2668 accounts.accountsDb.setTransactionSuccessful();
2669 } finally {
2670 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002671 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002672 synchronized (accounts.cacheLock) {
2673 writeUserDataIntoCacheLocked(accounts, account, key, value);
2674 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002675 }
2676 }
2677
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002678 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002679 if (result == null) {
2680 Log.e(TAG, "the result is unexpectedly null", new Exception());
2681 }
2682 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2683 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2684 + response);
2685 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002686 try {
2687 response.onResult(result);
2688 } catch (RemoteException e) {
2689 // if the caller is dead then there is no one to care about remote
2690 // exceptions
2691 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2692 Log.v(TAG, "failure while notifying response", e);
2693 }
2694 }
2695 }
2696
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002697 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002698 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2699 final String authTokenType)
2700 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002701 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2702 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002703
Fred Quintanad9640ec2012-05-23 12:37:00 -07002704 final int callingUid = getCallingUid();
2705 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002706 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002707 throw new SecurityException("can only call from system");
2708 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002709 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002710 long identityToken = clearCallingIdentity();
2711 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002712 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002713 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2714 false /* stripAuthTokenFromResult */, null /* accountName */,
2715 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002716 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002717 protected String toDebugString(long now) {
2718 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002719 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002720 + ", authTokenType " + authTokenType;
2721 }
2722
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002723 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002724 public void run() throws RemoteException {
2725 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2726 }
2727
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002728 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002729 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002730 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002731 if (result != null) {
2732 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2733 Bundle bundle = new Bundle();
2734 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2735 super.onResult(bundle);
2736 return;
2737 } else {
2738 super.onResult(result);
2739 }
2740 }
2741 }.bind();
2742 } finally {
2743 restoreCallingIdentity(identityToken);
2744 }
2745 }
2746
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002747 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002748 public void getAuthToken(
2749 IAccountManagerResponse response,
2750 final Account account,
2751 final String authTokenType,
2752 final boolean notifyOnAuthFailure,
2753 final boolean expectActivityLaunch,
2754 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002755 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002756 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2757 Log.v(TAG, "getAuthToken: " + account
2758 + ", response " + response
2759 + ", authTokenType " + authTokenType
2760 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2761 + ", expectActivityLaunch " + expectActivityLaunch
2762 + ", caller's uid " + Binder.getCallingUid()
2763 + ", pid " + Binder.getCallingPid());
2764 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002765 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002766 try {
2767 if (account == null) {
2768 Slog.w(TAG, "getAuthToken called with null account");
2769 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2770 return;
2771 }
2772 if (authTokenType == null) {
2773 Slog.w(TAG, "getAuthToken called with null authTokenType");
2774 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2775 return;
2776 }
2777 } catch (RemoteException e) {
2778 Slog.w(TAG, "Failed to report error back to the client." + e);
2779 return;
2780 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002781 int userId = UserHandle.getCallingUserId();
2782 long ident = Binder.clearCallingIdentity();
2783 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002784 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002785 try {
2786 accounts = getUserAccounts(userId);
2787 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2788 AuthenticatorDescription.newKey(account.type), accounts.userId);
2789 } finally {
2790 Binder.restoreCallingIdentity(ident);
2791 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002792
Costin Manolachea40c6302010-12-13 14:50:45 -08002793 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002794 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002795
2796 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002797 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002798 final boolean permissionGranted =
2799 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002800
Carlos Valdivia91979be2015-05-22 14:11:35 -07002801 // Get the calling package. We will use it for the purpose of caching.
2802 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002803 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002804 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002805 try {
2806 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2807 } finally {
2808 Binder.restoreCallingIdentity(ident);
2809 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002810 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2811 String msg = String.format(
2812 "Uid %s is attempting to illegally masquerade as package %s!",
2813 callerUid,
2814 callerPkg);
2815 throw new SecurityException(msg);
2816 }
2817
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002818 // let authenticator know the identity of the caller
2819 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2820 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002821
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002822 if (notifyOnAuthFailure) {
2823 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002824 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002825
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002826 long identityToken = clearCallingIdentity();
2827 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002828 // Distill the caller's package signatures into a single digest.
2829 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2830
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002831 // if the caller has permission, do the peek. otherwise go the more expensive
2832 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002833 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002834 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002835 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002836 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002837 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2838 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2839 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002840 onResult(response, result);
2841 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002842 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002843 }
2844
Carlos Valdivia91979be2015-05-22 14:11:35 -07002845 if (customTokens) {
2846 /*
2847 * Look up tokens in the new cache only if the loginOptions don't have parameters
2848 * outside of those expected to be injected by the AccountManager, e.g.
2849 * ANDORID_PACKAGE_NAME.
2850 */
2851 String token = readCachedTokenInternal(
2852 accounts,
2853 account,
2854 authTokenType,
2855 callerPkg,
2856 callerPkgSigDigest);
2857 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002858 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2859 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2860 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002861 Bundle result = new Bundle();
2862 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2863 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2864 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2865 onResult(response, result);
2866 return;
2867 }
2868 }
2869
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002870 new Session(
2871 accounts,
2872 response,
2873 account.type,
2874 expectActivityLaunch,
2875 false /* stripAuthTokenFromResult */,
2876 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002877 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002878 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002879 protected String toDebugString(long now) {
2880 if (loginOptions != null) loginOptions.keySet();
2881 return super.toDebugString(now) + ", getAuthToken"
2882 + ", " + account
2883 + ", authTokenType " + authTokenType
2884 + ", loginOptions " + loginOptions
2885 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2886 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002887
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002888 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002889 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002890 // If the caller doesn't have permission then create and return the
2891 // "grant permission" intent instead of the "getAuthToken" intent.
2892 if (!permissionGranted) {
2893 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2894 } else {
2895 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2896 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002897 }
2898
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002899 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002900 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002901 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002902 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002903 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002904 Intent intent = newGrantCredentialsPermissionIntent(
2905 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002906 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002907 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002908 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002909 authTokenType,
2910 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002911 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002912 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002913 onResult(bundle);
2914 return;
2915 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002916 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002917 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002918 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2919 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002920 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002921 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002922 "the type and name should not be empty");
2923 return;
2924 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002925 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002926 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002927 saveAuthTokenToDatabase(
2928 mAccounts,
2929 resultAccount,
2930 authTokenType,
2931 authToken);
2932 }
2933 long expiryMillis = result.getLong(
2934 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2935 if (customTokens
2936 && expiryMillis > System.currentTimeMillis()) {
2937 saveCachedToken(
2938 mAccounts,
2939 account,
2940 callerPkg,
2941 callerPkgSigDigest,
2942 authTokenType,
2943 authToken,
2944 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002945 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002946 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002947
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002948 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002949 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002950 /*
2951 * Make sure that the supplied intent is owned by the authenticator
2952 * giving it to the system. Otherwise a malicious authenticator could
2953 * have users launching arbitrary activities by tricking users to
2954 * interact with malicious notifications.
2955 */
2956 checkKeyIntent(
2957 Binder.getCallingUid(),
2958 intent);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002959 doNotification(
2960 mAccounts,
2961 account,
2962 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002963 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002964 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002965 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002966 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002967 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002968 }.bind();
2969 } finally {
2970 restoreCallingIdentity(identityToken);
2971 }
Fred Quintana60307342009-03-24 22:48:12 -07002972 }
2973
Carlos Valdivia91979be2015-05-22 14:11:35 -07002974 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2975 MessageDigest digester;
2976 try {
2977 digester = MessageDigest.getInstance("SHA-256");
2978 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2979 callerPkg, PackageManager.GET_SIGNATURES);
2980 for (Signature sig : pkgInfo.signatures) {
2981 digester.update(sig.toByteArray());
2982 }
2983 } catch (NoSuchAlgorithmException x) {
2984 Log.wtf(TAG, "SHA-256 should be available", x);
2985 digester = null;
2986 } catch (NameNotFoundException e) {
2987 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2988 digester = null;
2989 }
2990 return (digester == null) ? null : digester.digest();
2991 }
2992
Dianne Hackborn41203752012-08-31 14:05:51 -07002993 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002994 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002995 int uid = intent.getIntExtra(
2996 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2997 String authTokenType = intent.getStringExtra(
2998 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002999 final String titleAndSubtitle =
3000 mContext.getString(R.string.permission_request_notification_with_subtitle,
3001 account.name);
3002 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07003003 String title = titleAndSubtitle;
3004 String subtitle = "";
3005 if (index > 0) {
3006 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04003007 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07003008 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07003009 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003010 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05003011 Notification n =
3012 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
3013 .setSmallIcon(android.R.drawable.stat_sys_warning)
3014 .setWhen(0)
3015 .setColor(contextForUser.getColor(
3016 com.android.internal.R.color.system_notification_accent_color))
3017 .setContentTitle(title)
3018 .setContentText(subtitle)
3019 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
3020 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
3021 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003022 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003023 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003024 }
3025
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003026 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
3027 int uid, AccountAuthenticatorResponse response, String authTokenType,
3028 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003029
3030 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003031
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003032 if (startInNewTask) {
3033 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
3034 // Since it was set in Eclair+ we can't change it without breaking apps using
3035 // the intent from a non-Activity context. This is the default behavior.
3036 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3037 }
Chris Wren717a8812017-03-31 15:34:39 -04003038 intent.addCategory(getCredentialPermissionNotificationId(account,
3039 authTokenType, uid).mTag + (packageName != null ? packageName : ""));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003040 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003041 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
3042 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003043 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003044
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003045 return intent;
3046 }
3047
Chris Wren717a8812017-03-31 15:34:39 -04003048 private NotificationId getCredentialPermissionNotificationId(Account account,
3049 String authTokenType, int uid) {
3050 NotificationId nId;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003051 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003052 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003053 final Pair<Pair<Account, String>, Integer> key =
3054 new Pair<Pair<Account, String>, Integer>(
3055 new Pair<Account, String>(account, authTokenType), uid);
Chris Wren717a8812017-03-31 15:34:39 -04003056 nId = accounts.credentialsPermissionNotificationIds.get(key);
3057 if (nId == null) {
3058 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION
3059 + ":" + account.hashCode() + ":" + authTokenType.hashCode();
3060 int id = SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION;
3061 nId = new NotificationId(tag, id);
3062 accounts.credentialsPermissionNotificationIds.put(key, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003063 }
3064 }
Chris Wren717a8812017-03-31 15:34:39 -04003065 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003066 }
3067
Chris Wren717a8812017-03-31 15:34:39 -04003068 private NotificationId getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
3069 NotificationId nId;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003070 synchronized (accounts.signinRequiredNotificationIds) {
Chris Wren717a8812017-03-31 15:34:39 -04003071 nId = accounts.signinRequiredNotificationIds.get(account);
3072 if (nId == null) {
3073 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN
3074 + ":" + account.hashCode();
3075 int id = SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN;
3076 nId = new NotificationId(tag, id);
3077 accounts.signinRequiredNotificationIds.put(account, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003078 }
3079 }
Chris Wren717a8812017-03-31 15:34:39 -04003080 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003081 }
3082
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003083 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07003084 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07003085 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003086 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003087 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003088 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3089 Log.v(TAG, "addAccount: accountType " + accountType
3090 + ", response " + response
3091 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003092 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08003093 + ", expectActivityLaunch " + expectActivityLaunch
3094 + ", caller's uid " + Binder.getCallingUid()
3095 + ", pid " + Binder.getCallingPid());
3096 }
Fred Quintana382601f2010-03-25 12:25:10 -07003097 if (response == null) throw new IllegalArgumentException("response is null");
3098 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003099
Amith Yamasani71e6c692013-03-24 17:39:28 -07003100 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003101 final int uid = Binder.getCallingUid();
3102 final int userId = UserHandle.getUserId(uid);
3103 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003104 try {
3105 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3106 "User is not allowed to add an account!");
3107 } catch (RemoteException re) {
3108 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003109 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003110 return;
3111 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003112 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003113 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003114 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3115 "User cannot modify accounts of this type (policy).");
3116 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003117 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003118 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3119 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003120 return;
3121 }
3122
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003123 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003124 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3125 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3126 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3127
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003128 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003129 long identityToken = clearCallingIdentity();
3130 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003131 UserAccounts accounts = getUserAccounts(usrId);
3132 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003133 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3134 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003135 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003136 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003137 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003138 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003139 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003140 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003141 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003142 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003143
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003144 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003145 protected String toDebugString(long now) {
3146 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003147 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003148 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003149 }
3150 }.bind();
3151 } finally {
3152 restoreCallingIdentity(identityToken);
3153 }
Fred Quintana60307342009-03-24 22:48:12 -07003154 }
3155
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003156 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003157 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3158 final String authTokenType, final String[] requiredFeatures,
3159 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003160 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003161 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003162 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3163 Log.v(TAG, "addAccount: accountType " + accountType
3164 + ", response " + response
3165 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003166 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003167 + ", expectActivityLaunch " + expectActivityLaunch
3168 + ", caller's uid " + Binder.getCallingUid()
3169 + ", pid " + Binder.getCallingPid()
3170 + ", for user id " + userId);
3171 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003172 Preconditions.checkArgument(response != null, "response cannot be null");
3173 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003174 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003175 if (isCrossUser(callingUid, userId)) {
3176 throw new SecurityException(
3177 String.format(
3178 "User %s trying to add account for %s" ,
3179 UserHandle.getCallingUserId(),
3180 userId));
3181 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003182
3183 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003184 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003185 try {
3186 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3187 "User is not allowed to add an account!");
3188 } catch (RemoteException re) {
3189 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003190 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003191 return;
3192 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003193 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003194 try {
3195 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3196 "User cannot modify accounts of this type (policy).");
3197 } catch (RemoteException re) {
3198 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003199 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3200 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003201 return;
3202 }
3203
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003204 final int pid = Binder.getCallingPid();
3205 final int uid = Binder.getCallingUid();
3206 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3207 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3208 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3209
3210 long identityToken = clearCallingIdentity();
3211 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003212 UserAccounts accounts = getUserAccounts(userId);
3213 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003214 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3215 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003216 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003217 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003218 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003219 @Override
3220 public void run() throws RemoteException {
3221 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3222 options);
3223 }
3224
3225 @Override
3226 protected String toDebugString(long now) {
3227 return super.toDebugString(now) + ", addAccount"
3228 + ", accountType " + accountType
3229 + ", requiredFeatures "
3230 + (requiredFeatures != null
3231 ? TextUtils.join(",", requiredFeatures)
3232 : null);
3233 }
3234 }.bind();
3235 } finally {
3236 restoreCallingIdentity(identityToken);
3237 }
3238 }
3239
Sandra Kwan78812282015-11-04 11:19:47 -08003240 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003241 public void startAddAccountSession(
3242 final IAccountManagerResponse response,
3243 final String accountType,
3244 final String authTokenType,
3245 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003246 final boolean expectActivityLaunch,
3247 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003248 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003249 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3250 Log.v(TAG,
3251 "startAddAccountSession: accountType " + accountType
3252 + ", response " + response
3253 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003254 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003255 + ", expectActivityLaunch " + expectActivityLaunch
3256 + ", caller's uid " + Binder.getCallingUid()
3257 + ", pid " + Binder.getCallingPid());
3258 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003259 Preconditions.checkArgument(response != null, "response cannot be null");
3260 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003261
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003262 final int uid = Binder.getCallingUid();
3263 final int userId = UserHandle.getUserId(uid);
3264 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003265 try {
3266 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3267 "User is not allowed to add an account!");
3268 } catch (RemoteException re) {
3269 }
3270 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3271 return;
3272 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003273 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003274 try {
3275 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3276 "User cannot modify accounts of this type (policy).");
3277 } catch (RemoteException re) {
3278 }
3279 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3280 userId);
3281 return;
3282 }
Sandra Kwan78812282015-11-04 11:19:47 -08003283 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003284 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3285 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3286 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3287
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003288 // Check to see if the Password should be included to the caller.
3289 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3290 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003291 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003292
Sandra Kwan78812282015-11-04 11:19:47 -08003293 long identityToken = clearCallingIdentity();
3294 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003295 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003296 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3297 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003298 new StartAccountSession(
3299 accounts,
3300 response,
3301 accountType,
3302 expectActivityLaunch,
3303 null /* accountName */,
3304 false /* authDetailsRequired */,
3305 true /* updateLastAuthenticationTime */,
3306 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003307 @Override
3308 public void run() throws RemoteException {
3309 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3310 requiredFeatures, options);
3311 }
3312
3313 @Override
3314 protected String toDebugString(long now) {
3315 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3316 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3317 + accountType + ", requiredFeatures "
3318 + (requiredFeatures != null ? requiredFeaturesStr : null);
3319 }
3320 }.bind();
3321 } finally {
3322 restoreCallingIdentity(identityToken);
3323 }
3324 }
3325
3326 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3327 private abstract class StartAccountSession extends Session {
3328
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003329 private final boolean mIsPasswordForwardingAllowed;
3330
3331 public StartAccountSession(
3332 UserAccounts accounts,
3333 IAccountManagerResponse response,
3334 String accountType,
3335 boolean expectActivityLaunch,
3336 String accountName,
3337 boolean authDetailsRequired,
3338 boolean updateLastAuthenticationTime,
3339 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003340 super(accounts, response, accountType, expectActivityLaunch,
3341 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3342 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003343 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003344 }
3345
3346 @Override
3347 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003348 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003349 mNumResults++;
3350 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003351 if (result != null
3352 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003353 checkKeyIntent(
3354 Binder.getCallingUid(),
3355 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08003356 }
Sandra Kwan78812282015-11-04 11:19:47 -08003357 IAccountManagerResponse response;
3358 if (mExpectActivityLaunch && result != null
3359 && result.containsKey(AccountManager.KEY_INTENT)) {
3360 response = mResponse;
3361 } else {
3362 response = getResponseAndClose();
3363 }
3364 if (response == null) {
3365 return;
3366 }
3367 if (result == null) {
3368 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3369 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3370 + response);
3371 }
3372 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3373 "null bundle returned");
3374 return;
3375 }
3376
3377 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3378 // All AccountManager error codes are greater
3379 // than 0
3380 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3381 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3382 return;
3383 }
3384
Hongming Jin368aa192016-07-29 14:29:54 -07003385 // Omit passwords if the caller isn't permitted to see them.
3386 if (!mIsPasswordForwardingAllowed) {
3387 result.remove(AccountManager.KEY_PASSWORD);
3388 }
3389
Sandra Kwan78812282015-11-04 11:19:47 -08003390 // Strip auth token from result.
3391 result.remove(AccountManager.KEY_AUTHTOKEN);
3392
3393 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3394 Log.v(TAG,
3395 getClass().getSimpleName() + " calling onResult() on response " + response);
3396 }
3397
3398 // Get the session bundle created by authenticator. The
3399 // bundle contains data necessary for finishing the session
3400 // later. The session bundle will be encrypted here and
3401 // decrypted later when trying to finish the session.
3402 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3403 if (sessionBundle != null) {
3404 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3405 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003406 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003407 Log.w(TAG, "Account type in session bundle doesn't match request.");
3408 }
3409 // Add accountType info to session bundle. This will
3410 // override any value set by authenticator.
3411 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3412
3413 // Encrypt session bundle before returning to caller.
3414 try {
3415 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3416 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3417 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3418 } catch (GeneralSecurityException e) {
3419 if (Log.isLoggable(TAG, Log.DEBUG)) {
3420 Log.v(TAG, "Failed to encrypt session bundle!", e);
3421 }
3422 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3423 "failed to encrypt session bundle");
3424 return;
3425 }
3426 }
3427
3428 sendResponse(response, result);
3429 }
3430 }
3431
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003432 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003433 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003434 @NonNull Bundle sessionBundle,
3435 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003436 Bundle appInfo,
3437 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003438 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003439 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003440 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3441 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003442 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003443 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003444 + ", caller's uid " + callingUid
3445 + ", caller's user id " + UserHandle.getCallingUserId()
3446 + ", pid " + Binder.getCallingPid()
3447 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003448 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003449 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003450 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3451 // Account type is added to it before encryption.
3452 if (sessionBundle == null || sessionBundle.size() == 0) {
3453 throw new IllegalArgumentException("sessionBundle is empty");
3454 }
3455
Dmitry Dementyev52745472016-12-02 10:27:45 -08003456 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003457 if (isCrossUser(callingUid, userId)) {
3458 throw new SecurityException(
3459 String.format(
3460 "User %s trying to finish session for %s without cross user permission",
3461 UserHandle.getCallingUserId(),
3462 userId));
3463 }
3464
Sandra Kwan0b84b452016-01-20 15:25:42 -08003465 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003466 sendErrorResponse(response,
3467 AccountManager.ERROR_CODE_USER_RESTRICTED,
3468 "User is not allowed to add an account!");
3469 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3470 return;
3471 }
3472
3473 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003474 final Bundle decryptedBundle;
3475 final String accountType;
3476 // First decrypt session bundle to get account type for checking permission.
3477 try {
3478 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3479 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3480 if (decryptedBundle == null) {
3481 sendErrorResponse(
3482 response,
3483 AccountManager.ERROR_CODE_BAD_REQUEST,
3484 "failed to decrypt session bundle");
3485 return;
3486 }
3487 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3488 // Account type cannot be null. This should not happen if session bundle was created
3489 // properly by #StartAccountSession.
3490 if (TextUtils.isEmpty(accountType)) {
3491 sendErrorResponse(
3492 response,
3493 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3494 "accountType is empty");
3495 return;
3496 }
3497
3498 // If by any chances, decryptedBundle contains colliding keys with
3499 // system info
3500 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3501 // update credentials flow, we should replace with the new values of the current call.
3502 if (appInfo != null) {
3503 decryptedBundle.putAll(appInfo);
3504 }
3505
3506 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003507 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003508 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3509 } catch (GeneralSecurityException e) {
3510 if (Log.isLoggable(TAG, Log.DEBUG)) {
3511 Log.v(TAG, "Failed to decrypt session bundle!", e);
3512 }
3513 sendErrorResponse(
3514 response,
3515 AccountManager.ERROR_CODE_BAD_REQUEST,
3516 "failed to decrypt session bundle");
3517 return;
3518 }
3519
Sandra Kwan0b84b452016-01-20 15:25:42 -08003520 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003521 sendErrorResponse(
3522 response,
3523 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3524 "User cannot modify accounts of this type (policy).");
3525 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3526 userId);
3527 return;
3528 }
3529
3530 long identityToken = clearCallingIdentity();
3531 try {
3532 UserAccounts accounts = getUserAccounts(userId);
3533 logRecordWithUid(
3534 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003535 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3536 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003537 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003538 new Session(
3539 accounts,
3540 response,
3541 accountType,
3542 expectActivityLaunch,
3543 true /* stripAuthTokenFromResult */,
3544 null /* accountName */,
3545 false /* authDetailsRequired */,
3546 true /* updateLastAuthenticationTime */) {
3547 @Override
3548 public void run() throws RemoteException {
3549 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3550 }
3551
3552 @Override
3553 protected String toDebugString(long now) {
3554 return super.toDebugString(now)
3555 + ", finishSession"
3556 + ", accountType " + accountType;
3557 }
3558 }.bind();
3559 } finally {
3560 restoreCallingIdentity(identityToken);
3561 }
3562 }
3563
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003564 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003565 final DevicePolicyManagerInternal dpmi =
3566 LocalServices.getService(DevicePolicyManagerInternal.class);
3567 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003568 if (dpmi == null) {
3569 intent = getDefaultCantAddAccountIntent(errorCode);
3570 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003571 intent = dpmi.createUserRestrictionSupportIntent(userId,
3572 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3573 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3574 intent = dpmi.createShowAdminSupportIntent(userId, false);
3575 }
3576 if (intent == null) {
3577 intent = getDefaultCantAddAccountIntent(errorCode);
3578 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003579 long identityToken = clearCallingIdentity();
3580 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003581 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003582 } finally {
3583 restoreCallingIdentity(identityToken);
3584 }
3585 }
3586
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003587 /**
3588 * Called when we don't know precisely who is preventing us from adding an account.
3589 */
3590 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3591 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3592 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3593 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3594 return cantAddAccount;
3595 }
3596
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003597 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003598 public void confirmCredentialsAsUser(
3599 IAccountManagerResponse response,
3600 final Account account,
3601 final Bundle options,
3602 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003603 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003604 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003605 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003606 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3607 Log.v(TAG, "confirmCredentials: " + account
3608 + ", response " + response
3609 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003610 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003611 + ", pid " + Binder.getCallingPid());
3612 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003613 // Only allow the system process to read accounts of other users
3614 if (isCrossUser(callingUid, userId)) {
3615 throw new SecurityException(
3616 String.format(
3617 "User %s trying to confirm account credentials for %s" ,
3618 UserHandle.getCallingUserId(),
3619 userId));
3620 }
Fred Quintana382601f2010-03-25 12:25:10 -07003621 if (response == null) throw new IllegalArgumentException("response is null");
3622 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003623 long identityToken = clearCallingIdentity();
3624 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003625 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003626 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003627 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003628 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003629 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003630 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003631 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003632 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003633 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003634 protected String toDebugString(long now) {
3635 return super.toDebugString(now) + ", confirmCredentials"
3636 + ", " + account;
3637 }
3638 }.bind();
3639 } finally {
3640 restoreCallingIdentity(identityToken);
3641 }
Fred Quintana60307342009-03-24 22:48:12 -07003642 }
3643
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003644 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003645 public void updateCredentials(IAccountManagerResponse response, final Account account,
3646 final String authTokenType, final boolean expectActivityLaunch,
3647 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003648 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003649 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3650 Log.v(TAG, "updateCredentials: " + account
3651 + ", response " + response
3652 + ", authTokenType " + authTokenType
3653 + ", expectActivityLaunch " + expectActivityLaunch
3654 + ", caller's uid " + Binder.getCallingUid()
3655 + ", pid " + Binder.getCallingPid());
3656 }
Fred Quintana382601f2010-03-25 12:25:10 -07003657 if (response == null) throw new IllegalArgumentException("response is null");
3658 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003659 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003660 long identityToken = clearCallingIdentity();
3661 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003662 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003663 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003664 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003665 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003666 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003667 public void run() throws RemoteException {
3668 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3669 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003670 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003671 protected String toDebugString(long now) {
3672 if (loginOptions != null) loginOptions.keySet();
3673 return super.toDebugString(now) + ", updateCredentials"
3674 + ", " + account
3675 + ", authTokenType " + authTokenType
3676 + ", loginOptions " + loginOptions;
3677 }
3678 }.bind();
3679 } finally {
3680 restoreCallingIdentity(identityToken);
3681 }
Fred Quintana60307342009-03-24 22:48:12 -07003682 }
3683
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003684 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003685 public void startUpdateCredentialsSession(
3686 IAccountManagerResponse response,
3687 final Account account,
3688 final String authTokenType,
3689 final boolean expectActivityLaunch,
3690 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003691 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003692 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3693 Log.v(TAG,
3694 "startUpdateCredentialsSession: " + account + ", response " + response
3695 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3696 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3697 + ", pid " + Binder.getCallingPid());
3698 }
3699 if (response == null) {
3700 throw new IllegalArgumentException("response is null");
3701 }
3702 if (account == null) {
3703 throw new IllegalArgumentException("account is null");
3704 }
Sandra Kwana578d112015-12-16 16:01:43 -08003705
3706 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003707 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003708
3709 // Check to see if the Password should be included to the caller.
3710 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3711 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003712 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003713
Sandra Kwane68c37e2015-11-12 17:11:49 -08003714 long identityToken = clearCallingIdentity();
3715 try {
3716 UserAccounts accounts = getUserAccounts(userId);
3717 new StartAccountSession(
3718 accounts,
3719 response,
3720 account.type,
3721 expectActivityLaunch,
3722 account.name,
3723 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003724 true /* updateLastCredentialTime */,
3725 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003726 @Override
3727 public void run() throws RemoteException {
3728 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3729 loginOptions);
3730 }
3731
3732 @Override
3733 protected String toDebugString(long now) {
3734 if (loginOptions != null)
3735 loginOptions.keySet();
3736 return super.toDebugString(now)
3737 + ", startUpdateCredentialsSession"
3738 + ", " + account
3739 + ", authTokenType " + authTokenType
3740 + ", loginOptions " + loginOptions;
3741 }
3742 }.bind();
3743 } finally {
3744 restoreCallingIdentity(identityToken);
3745 }
3746 }
3747
3748 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003749 public void isCredentialsUpdateSuggested(
3750 IAccountManagerResponse response,
3751 final Account account,
3752 final String statusToken) {
3753 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3754 Log.v(TAG,
3755 "isCredentialsUpdateSuggested: " + account + ", response " + response
3756 + ", caller's uid " + Binder.getCallingUid()
3757 + ", pid " + Binder.getCallingPid());
3758 }
3759 if (response == null) {
3760 throw new IllegalArgumentException("response is null");
3761 }
3762 if (account == null) {
3763 throw new IllegalArgumentException("account is null");
3764 }
3765 if (TextUtils.isEmpty(statusToken)) {
3766 throw new IllegalArgumentException("status token is empty");
3767 }
3768
Sandra Kwan390c9d22016-01-12 14:13:37 -08003769 int usrId = UserHandle.getCallingUserId();
3770 long identityToken = clearCallingIdentity();
3771 try {
3772 UserAccounts accounts = getUserAccounts(usrId);
3773 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3774 false /* stripAuthTokenFromResult */, account.name,
3775 false /* authDetailsRequired */) {
3776 @Override
3777 protected String toDebugString(long now) {
3778 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3779 + ", " + account;
3780 }
3781
3782 @Override
3783 public void run() throws RemoteException {
3784 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3785 }
3786
3787 @Override
3788 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003789 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003790 IAccountManagerResponse response = getResponseAndClose();
3791 if (response == null) {
3792 return;
3793 }
3794
3795 if (result == null) {
3796 sendErrorResponse(
3797 response,
3798 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3799 "null bundle");
3800 return;
3801 }
3802
3803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3804 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3805 + response);
3806 }
3807 // Check to see if an error occurred. We know if an error occurred because all
3808 // error codes are greater than 0.
3809 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3810 sendErrorResponse(response,
3811 result.getInt(AccountManager.KEY_ERROR_CODE),
3812 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3813 return;
3814 }
3815 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3816 sendErrorResponse(
3817 response,
3818 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3819 "no result in response");
3820 return;
3821 }
3822 final Bundle newResult = new Bundle();
3823 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3824 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3825 sendResponse(response, newResult);
3826 }
3827 }.bind();
3828 } finally {
3829 restoreCallingIdentity(identityToken);
3830 }
3831 }
3832
3833 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003834 public void editProperties(IAccountManagerResponse response, final String accountType,
3835 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003836 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003837 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3838 Log.v(TAG, "editProperties: accountType " + accountType
3839 + ", response " + response
3840 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003841 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003842 + ", pid " + Binder.getCallingPid());
3843 }
Fred Quintana382601f2010-03-25 12:25:10 -07003844 if (response == null) throw new IllegalArgumentException("response is null");
3845 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003846 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003847 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3848 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003849 String msg = String.format(
3850 "uid %s cannot edit authenticator properites for account type: %s",
3851 callingUid,
3852 accountType);
3853 throw new SecurityException(msg);
3854 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003855 long identityToken = clearCallingIdentity();
3856 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003857 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003858 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003859 true /* stripAuthTokenFromResult */, null /* accountName */,
3860 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003861 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003862 public void run() throws RemoteException {
3863 mAuthenticator.editProperties(this, mAccountType);
3864 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003865 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003866 protected String toDebugString(long now) {
3867 return super.toDebugString(now) + ", editProperties"
3868 + ", accountType " + accountType;
3869 }
3870 }.bind();
3871 } finally {
3872 restoreCallingIdentity(identityToken);
3873 }
Fred Quintana60307342009-03-24 22:48:12 -07003874 }
3875
Amith Yamasani12747872015-12-07 14:19:49 -08003876 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003877 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3878 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003879 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003880 throw new SecurityException("Can be called only by system UID");
3881 }
3882 Preconditions.checkNotNull(account, "account cannot be null");
3883 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3884 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3885
3886 final int userId = userHandle.getIdentifier();
3887
3888 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3889
3890 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003891 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003892 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003893 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003894 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003895 return false;
3896 }
3897 }
3898
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003899 // Returns package with oldest target SDK for given UID.
3900 private String getPackageNameForUid(int uid) {
3901 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3902 if (ArrayUtils.isEmpty(packageNames)) {
3903 return null;
3904 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003905 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003906 if (packageNames.length == 1) {
3907 return packageName;
3908 }
3909 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003910 int oldestVersion = Integer.MAX_VALUE;
3911 for (String name : packageNames) {
3912 try {
3913 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3914 if (applicationInfo != null) {
3915 int version = applicationInfo.targetSdkVersion;
3916 if (version < oldestVersion) {
3917 oldestVersion = version;
3918 packageName = name;
3919 }
3920 }
3921 } catch (NameNotFoundException e) {
3922 // skip
3923 }
3924 }
3925 return packageName;
3926 }
3927
Svet Ganovf6d424f12016-09-20 20:18:53 -07003928 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3929 int uid) {
3930 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003931 packageName = getPackageNameForUid(uid);
3932 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07003933 return false;
3934 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003935 }
3936
3937 // Use null token which means any token. Having a token means the package
3938 // is trusted by the authenticator, hence it is fine to access the account.
3939 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
3940 return true;
3941 }
3942 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003943 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07003944
Dmitry Dementyeve366f822017-01-31 10:25:10 -08003945 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003946 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003947 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003948 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003949 }
3950
3951 @Override
3952 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3953 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003954 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003955 throw new SecurityException("Can be called only by system UID");
3956 }
3957
3958 Preconditions.checkNotNull(account, "account cannot be null");
3959 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3960 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3961
3962 final int userId = userHandle.getIdentifier();
3963
3964 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3965
3966 final int uid;
3967 try {
3968 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
3969 } catch (NameNotFoundException e) {
3970 Slog.e(TAG, "Unknown package " + packageName);
3971 return null;
3972 }
3973
3974 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
3975
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003976 final long identity = Binder.clearCallingIdentity();
3977 try {
3978 return PendingIntent.getActivityAsUser(
3979 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
3980 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
3981 null, new UserHandle(userId)).getIntentSender();
3982 } finally {
3983 Binder.restoreCallingIdentity(identity);
3984 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003985 }
3986
3987 private Intent newRequestAccountAccessIntent(Account account, String packageName,
3988 int uid, RemoteCallback callback) {
3989 return newGrantCredentialsPermissionIntent(account, packageName, uid,
3990 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
3991 @Override
3992 public void onResult(Bundle value) throws RemoteException {
3993 handleAuthenticatorResponse(true);
3994 }
3995
3996 @Override
3997 public void onRequestContinued() {
3998 /* ignore */
3999 }
4000
4001 @Override
4002 public void onError(int errorCode, String errorMessage) throws RemoteException {
4003 handleAuthenticatorResponse(false);
4004 }
4005
4006 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
4007 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07004008 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004009 UserHandle.getUserHandleForUid(uid));
4010 if (callback != null) {
4011 Bundle result = new Bundle();
4012 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
4013 callback.sendResult(result);
4014 }
4015 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004016 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004017 }
4018
4019 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08004020 public boolean someUserHasAccount(@NonNull final Account account) {
4021 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
4022 throw new SecurityException("Only system can check for accounts across users");
4023 }
4024 final long token = Binder.clearCallingIdentity();
4025 try {
4026 AccountAndUser[] allAccounts = getAllAccounts();
4027 for (int i = allAccounts.length - 1; i >= 0; i--) {
4028 if (allAccounts[i].account.equals(account)) {
4029 return true;
4030 }
4031 }
4032 return false;
4033 } finally {
4034 Binder.restoreCallingIdentity(token);
4035 }
4036 }
4037
Fred Quintana33269202009-04-20 16:05:10 -07004038 private class GetAccountsByTypeAndFeatureSession extends Session {
4039 private final String[] mFeatures;
4040 private volatile Account[] mAccountsOfType = null;
4041 private volatile ArrayList<Account> mAccountsWithFeatures = null;
4042 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004043 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004044 private final String mPackageName;
Fred Quintana33269202009-04-20 16:05:10 -07004045
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004046 public GetAccountsByTypeAndFeatureSession(
4047 UserAccounts accounts,
4048 IAccountManagerResponse response,
4049 String type,
4050 String[] features,
4051 int callingUid,
4052 String packageName) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004053 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004054 true /* stripAuthTokenFromResult */, null /* accountName */,
4055 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004056 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07004057 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004058 mPackageName = packageName;
Fred Quintana33269202009-04-20 16:05:10 -07004059 }
4060
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004061 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004062 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004063 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
4064 mCallingUid, mPackageName, false /* include managed not visible*/);
Fred Quintana33269202009-04-20 16:05:10 -07004065 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07004066 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07004067 mCurrentAccount = 0;
4068
4069 checkAccount();
4070 }
4071
4072 public void checkAccount() {
4073 if (mCurrentAccount >= mAccountsOfType.length) {
4074 sendResult();
4075 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07004076 }
Fred Quintana33269202009-04-20 16:05:10 -07004077
Fred Quintana29e94b82010-03-10 12:11:51 -08004078 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
4079 if (accountAuthenticator == null) {
4080 // It is possible that the authenticator has died, which is indicated by
4081 // mAuthenticator being set to null. If this happens then just abort.
4082 // There is no need to send back a result or error in this case since
4083 // that already happened when mAuthenticator was cleared.
4084 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4085 Log.v(TAG, "checkAccount: aborting session since we are no longer"
4086 + " connected to the authenticator, " + toDebugString());
4087 }
4088 return;
4089 }
Fred Quintana33269202009-04-20 16:05:10 -07004090 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08004091 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07004092 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004093 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07004094 }
4095 }
4096
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004097 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004098 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004099 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07004100 mNumResults++;
4101 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004102 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07004103 return;
4104 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004105 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07004106 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
4107 }
4108 mCurrentAccount++;
4109 checkAccount();
4110 }
4111
4112 public void sendResult() {
4113 IAccountManagerResponse response = getResponseAndClose();
4114 if (response != null) {
4115 try {
4116 Account[] accounts = new Account[mAccountsWithFeatures.size()];
4117 for (int i = 0; i < accounts.length; i++) {
4118 accounts[i] = mAccountsWithFeatures.get(i);
4119 }
Fred Quintana56285a62010-12-02 14:20:51 -08004120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4121 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
4122 + response);
4123 }
Fred Quintana33269202009-04-20 16:05:10 -07004124 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004125 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004126 response.onResult(result);
4127 } catch (RemoteException e) {
4128 // if the caller is dead then there is no one to care about remote exceptions
4129 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4130 Log.v(TAG, "failure while notifying response", e);
4131 }
4132 }
4133 }
4134 }
4135
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004136 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004137 protected String toDebugString(long now) {
4138 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4139 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4140 }
4141 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004142
Amith Yamasani04e0d262012-02-14 11:50:53 -08004143 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004144 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004145 * @hide
4146 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004147 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004148 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004149 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004150 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004151 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4152 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004153 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004154 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004155 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004156 long identityToken = clearCallingIdentity();
4157 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004158 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004159 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004160 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004161 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004162 opPackageName,
4163 visibleAccountTypes,
4164 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004165 } finally {
4166 restoreCallingIdentity(identityToken);
4167 }
4168 }
4169
Amith Yamasanif29f2362012-04-05 18:29:52 -07004170 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004171 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004172 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004173 * @hide
4174 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004175 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004176 public AccountAndUser[] getRunningAccounts() {
4177 final int[] runningUserIds;
4178 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004179 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004180 } catch (RemoteException e) {
4181 // Running in system_server; should never happen
4182 throw new RuntimeException(e);
4183 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004184 return getAccounts(runningUserIds);
4185 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004186
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004187 /**
4188 * Returns accounts for all users, ignores visibility values.
4189 *
4190 * @hide
4191 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004192 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004193 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004194 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004195 final int[] userIds = new int[users.size()];
4196 for (int i = 0; i < userIds.length; i++) {
4197 userIds[i] = users.get(i).id;
4198 }
4199 return getAccounts(userIds);
4200 }
4201
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004202 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004203 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004204 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004205 for (int userId : userIds) {
4206 UserAccounts userAccounts = getUserAccounts(userId);
4207 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004208 Account[] accounts = getAccountsFromCache(
4209 userAccounts,
4210 null /* type */,
4211 Binder.getCallingUid(),
4212 null /* packageName */,
4213 false /* include managed not visible*/);
4214 for (Account account : accounts) {
4215 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004216 }
4217 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004218
4219 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4220 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004221 }
4222
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004223 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004224 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004225 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004226 int callingUid = Binder.getCallingUid();
4227 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004228 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004229 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004230 }
4231
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004232 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004233 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004234 String type,
4235 int userId,
4236 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004237 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004238 String opPackageName,
4239 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004240 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004241 // Only allow the system process to read accounts of other users
4242 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004243 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004244 && mContext.checkCallingOrSelfPermission(
4245 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4246 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004247 throw new SecurityException("User " + UserHandle.getCallingUserId()
4248 + " trying to get account for " + userId);
4249 }
4250
Fred Quintana56285a62010-12-02 14:20:51 -08004251 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4252 Log.v(TAG, "getAccounts: accountType " + type
4253 + ", caller's uid " + Binder.getCallingUid()
4254 + ", pid " + Binder.getCallingPid());
4255 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004256
4257 // If the original calling app was using account choosing activity
4258 // provided by the framework or authenticator we'll passing in
4259 // the original caller's uid here, which is what should be used for filtering.
4260 List<String> managedTypes =
4261 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4262 if (packageUid != -1 &&
4263 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4264 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004265 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004266 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004267 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004268 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4269 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004270 if (visibleAccountTypes.isEmpty()
4271 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004272 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004273 } else if (visibleAccountTypes.contains(type)) {
4274 // Prune the list down to just the requested type.
4275 visibleAccountTypes = new ArrayList<>();
4276 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004277 } // else aggregate all the visible accounts (it won't matter if the
4278 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004279
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004280 long identityToken = clearCallingIdentity();
4281 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004282 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004283 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004284 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004285 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004286 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004287 visibleAccountTypes,
4288 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004289 } finally {
4290 restoreCallingIdentity(identityToken);
4291 }
4292 }
4293
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004294 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004295 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004296 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004297 int callingUid,
4298 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004299 List<String> visibleAccountTypes,
4300 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004301 ArrayList<Account> visibleAccounts = new ArrayList<>();
4302 for (String visibleType : visibleAccountTypes) {
4303 Account[] accountsForType = getAccountsFromCache(
4304 userAccounts, visibleType, callingUid, callingPackage,
4305 includeUserManagedNotVisible);
4306 if (accountsForType != null) {
4307 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004308 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004309 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004310 Account[] result = new Account[visibleAccounts.size()];
4311 for (int i = 0; i < visibleAccounts.size(); i++) {
4312 result[i] = visibleAccounts.get(i);
4313 }
4314 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004315 }
4316
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004317 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004318 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4319 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004320 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004321 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004322 for (Account account : accounts) {
4323 addSharedAccountAsUser(account, userId);
4324 }
4325 }
4326
4327 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004328 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004329 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004330 accounts.accountsDb.deleteSharedAccount(account);
4331 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004332 if (accountId < 0) {
4333 Log.w(TAG, "insertAccountIntoDatabase: " + account
4334 + ", skipping the DB insert failed");
4335 return false;
4336 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004337 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4338 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004339 return true;
4340 }
4341
4342 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004343 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4344 userId = handleIncomingUser(userId);
4345 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004346 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4347 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004348 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004349 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004350 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004351 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004352 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004353 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004354 }
4355 return r > 0;
4356 }
4357
4358 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004359 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004360 return removeSharedAccountAsUser(account, userId, getCallingUid());
4361 }
4362
4363 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004364 userId = handleIncomingUser(userId);
4365 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004366 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4367 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004368 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004369 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004370 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004371 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004372 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004373 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004374 }
4375
4376 @Override
4377 public Account[] getSharedAccountsAsUser(int userId) {
4378 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004379 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004380 synchronized (accounts.dbLock) {
4381 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4382 Account[] accountArray = new Account[accountList.size()];
4383 accountList.toArray(accountArray);
4384 return accountArray;
4385 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004386 }
4387
4388 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004389 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004390 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004391 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004392 }
4393
Amith Yamasani27db4682013-03-30 17:07:47 -07004394 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004395 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004396 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004397 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004398 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004399 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004400 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4401 + callingUid + " with uid=" + uid);
4402 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004403 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004404 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004405 }
4406
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004407 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004408 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004409 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4410 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004411 int callingUid = Binder.getCallingUid();
4412 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004413 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004414 int packageUid = -1;
4415 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004416 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4417 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004418 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004419 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004420 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004421 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004422 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4423 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004424 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004425 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004426 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004427 }
4428
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004429 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004430 public void getAccountsByFeatures(
4431 IAccountManagerResponse response,
4432 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004433 String[] features,
4434 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004435 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004436 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004437 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4438 Log.v(TAG, "getAccounts: accountType " + type
4439 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004440 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004441 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004442 + ", pid " + Binder.getCallingPid());
4443 }
Fred Quintana382601f2010-03-25 12:25:10 -07004444 if (response == null) throw new IllegalArgumentException("response is null");
4445 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004446 int userId = UserHandle.getCallingUserId();
4447
Svetoslavf3f02ac2015-09-08 14:36:35 -07004448 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4449 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004450 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004451 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004452 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004453 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004454 try {
4455 response.onResult(result);
4456 } catch (RemoteException e) {
4457 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4458 }
4459 return;
4460 }
Fred Quintana33269202009-04-20 16:05:10 -07004461 long identityToken = clearCallingIdentity();
4462 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004463 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004464 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004465 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4466 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004467 Bundle result = new Bundle();
4468 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4469 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004470 return;
4471 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004472 new GetAccountsByTypeAndFeatureSession(
4473 userAccounts,
4474 response,
4475 type,
4476 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004477 callingUid,
4478 opPackageName).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004479 } finally {
4480 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004481 }
4482 }
4483
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004484 @Override
4485 public void onAccountAccessed(String token) throws RemoteException {
4486 final int uid = Binder.getCallingUid();
4487 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4488 return;
4489 }
4490 final int userId = UserHandle.getCallingUserId();
4491 final long identity = Binder.clearCallingIdentity();
4492 try {
4493 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4494 if (Objects.equals(account.getAccessId(), token)) {
4495 // An app just accessed the account. At this point it knows about
4496 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004497 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004498 if (!hasAccountAccess(account, null, uid)) {
4499 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4500 uid, true);
4501 }
4502 }
4503 }
4504 } finally {
4505 Binder.restoreCallingIdentity(identity);
4506 }
4507 }
4508
Fred Quintanaa698f422009-04-08 19:14:54 -07004509 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004510 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004511 IAccountManagerResponse mResponse;
4512 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004513 final boolean mExpectActivityLaunch;
4514 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004515 final String mAccountName;
4516 // Indicates if we need to add auth details(like last credential time)
4517 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004518 // If set, we need to update the last authenticated time. This is
4519 // currently
4520 // used on
4521 // successful confirming credentials.
4522 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004523
Fred Quintana33269202009-04-20 16:05:10 -07004524 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004525 private int mNumRequestContinued = 0;
4526 private int mNumErrors = 0;
4527
Fred Quintana60307342009-03-24 22:48:12 -07004528 IAccountAuthenticator mAuthenticator = null;
4529
Fred Quintana8570f742010-02-18 10:32:54 -08004530 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004531 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004532
Amith Yamasani04e0d262012-02-14 11:50:53 -08004533 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004534 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4535 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004536 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4537 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4538 }
4539
4540 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4541 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4542 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004543 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004544 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004545 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004546 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004547 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004548 mResponse = response;
4549 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004550 mExpectActivityLaunch = expectActivityLaunch;
4551 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004552 mAccountName = accountName;
4553 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004554 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004555
Fred Quintanaa698f422009-04-08 19:14:54 -07004556 synchronized (mSessions) {
4557 mSessions.put(toString(), this);
4558 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004559 if (response != null) {
4560 try {
4561 response.asBinder().linkToDeath(this, 0 /* flags */);
4562 } catch (RemoteException e) {
4563 mResponse = null;
4564 binderDied();
4565 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004566 }
Fred Quintana60307342009-03-24 22:48:12 -07004567 }
4568
Fred Quintanaa698f422009-04-08 19:14:54 -07004569 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004570 if (mResponse == null) {
4571 // this session has already been closed
4572 return null;
4573 }
Fred Quintana60307342009-03-24 22:48:12 -07004574 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004575 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004576 return response;
4577 }
4578
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004579 /**
4580 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4581 * security policy.
4582 *
4583 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004584 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004585 * supplied entries in the system Settings app.
4586 */
4587 protected void checkKeyIntent(
4588 int authUid,
4589 Intent intent) throws SecurityException {
4590 long bid = Binder.clearCallingIdentity();
4591 try {
4592 PackageManager pm = mContext.getPackageManager();
4593 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4594 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4595 int targetUid = targetActivityInfo.applicationInfo.uid;
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004596 if (!isExportedSystemActivity(targetActivityInfo)
4597 && (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid,
4598 targetUid))) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004599 String pkgName = targetActivityInfo.packageName;
4600 String activityName = targetActivityInfo.name;
4601 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4602 + "does not share a signature with the supplying authenticator (%s).";
4603 throw new SecurityException(
4604 String.format(tmpl, activityName, pkgName, mAccountType));
4605 }
4606 } finally {
4607 Binder.restoreCallingIdentity(bid);
4608 }
4609 }
4610
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004611 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4612 String className = activityInfo.name;
4613 return "android".equals(activityInfo.packageName) &&
4614 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4615 || CantAddAccountActivity.class.getName().equals(className));
4616 }
4617
Fred Quintanaa698f422009-04-08 19:14:54 -07004618 private void close() {
4619 synchronized (mSessions) {
4620 if (mSessions.remove(toString()) == null) {
4621 // the session was already closed, so bail out now
4622 return;
4623 }
4624 }
4625 if (mResponse != null) {
4626 // stop listening for response deaths
4627 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4628
4629 // clear this so that we don't accidentally send any further results
4630 mResponse = null;
4631 }
4632 cancelTimeout();
4633 unbind();
4634 }
4635
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004636 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004637 public void binderDied() {
4638 mResponse = null;
4639 close();
4640 }
4641
4642 protected String toDebugString() {
4643 return toDebugString(SystemClock.elapsedRealtime());
4644 }
4645
4646 protected String toDebugString(long now) {
4647 return "Session: expectLaunch " + mExpectActivityLaunch
4648 + ", connected " + (mAuthenticator != null)
4649 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4650 + "/" + mNumErrors + ")"
4651 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4652 }
4653
Fred Quintana60307342009-03-24 22:48:12 -07004654 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004655 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4656 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4657 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004658 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004659 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004660 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004661 }
4662 }
4663
4664 private void unbind() {
4665 if (mAuthenticator != null) {
4666 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004667 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004668 }
4669 }
4670
Fred Quintana60307342009-03-24 22:48:12 -07004671 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004672 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004673 }
4674
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004675 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004676 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004677 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004678 try {
4679 run();
4680 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004681 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004682 "remote exception");
4683 }
Fred Quintana60307342009-03-24 22:48:12 -07004684 }
4685
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004686 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004687 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004688 mAuthenticator = null;
4689 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004690 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004691 try {
4692 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4693 "disconnected");
4694 } catch (RemoteException e) {
4695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4696 Log.v(TAG, "Session.onServiceDisconnected: "
4697 + "caught RemoteException while responding", e);
4698 }
4699 }
Fred Quintana60307342009-03-24 22:48:12 -07004700 }
4701 }
4702
Fred Quintanab839afc2009-10-14 15:57:28 -07004703 public abstract void run() throws RemoteException;
4704
Fred Quintana60307342009-03-24 22:48:12 -07004705 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004706 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004707 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004708 try {
4709 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4710 "timeout");
4711 } catch (RemoteException e) {
4712 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4713 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4714 e);
4715 }
4716 }
Fred Quintana60307342009-03-24 22:48:12 -07004717 }
4718 }
4719
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004720 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004721 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004722 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004723 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004724 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004725 if (result != null) {
4726 boolean isSuccessfulConfirmCreds = result.getBoolean(
4727 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004728 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004729 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4730 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004731 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004732 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4733 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004734 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004735 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004736 if (needUpdate || mAuthDetailsRequired) {
4737 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4738 if (needUpdate && accountPresent) {
4739 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4740 }
4741 if (mAuthDetailsRequired) {
4742 long lastAuthenticatedTime = -1;
4743 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004744 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004745 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004746 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004747 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004748 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004749 lastAuthenticatedTime);
4750 }
4751 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004752 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004753 if (result != null
4754 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004755 checkKeyIntent(
4756 Binder.getCallingUid(),
4757 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004758 }
4759 if (result != null
4760 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004761 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4762 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004763 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4764 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004765 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4766 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004767 }
Fred Quintana60307342009-03-24 22:48:12 -07004768 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004769 IAccountManagerResponse response;
4770 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004771 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004772 response = mResponse;
4773 } else {
4774 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004775 }
Fred Quintana60307342009-03-24 22:48:12 -07004776 if (response != null) {
4777 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004778 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4780 Log.v(TAG, getClass().getSimpleName()
4781 + " calling onError() on response " + response);
4782 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004783 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004784 "null bundle returned");
4785 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004786 if (mStripAuthTokenFromResult) {
4787 result.remove(AccountManager.KEY_AUTHTOKEN);
4788 }
Fred Quintana56285a62010-12-02 14:20:51 -08004789 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4790 Log.v(TAG, getClass().getSimpleName()
4791 + " calling onResult() on response " + response);
4792 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004793 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4794 (intent == null)) {
4795 // All AccountManager error codes are greater than 0
4796 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4797 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4798 } else {
4799 response.onResult(result);
4800 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004801 }
Fred Quintana60307342009-03-24 22:48:12 -07004802 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004803 // if the caller is dead then there is no one to care about remote exceptions
4804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4805 Log.v(TAG, "failure while notifying response", e);
4806 }
Fred Quintana60307342009-03-24 22:48:12 -07004807 }
4808 }
4809 }
Fred Quintana60307342009-03-24 22:48:12 -07004810
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004811 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004812 public void onRequestContinued() {
4813 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004814 }
4815
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004816 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004817 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004818 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004819 IAccountManagerResponse response = getResponseAndClose();
4820 if (response != null) {
4821 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004822 Log.v(TAG, getClass().getSimpleName()
4823 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004824 }
4825 try {
4826 response.onError(errorCode, errorMessage);
4827 } catch (RemoteException e) {
4828 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4829 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4830 }
4831 }
4832 } else {
4833 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4834 Log.v(TAG, "Session.onError: already closed");
4835 }
Fred Quintana60307342009-03-24 22:48:12 -07004836 }
4837 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004838
4839 /**
4840 * find the component name for the authenticator and initiate a bind
4841 * if no authenticator or the bind fails then return false, otherwise return true
4842 */
4843 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004844 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4845 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4846 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004847 if (authenticatorInfo == null) {
4848 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4849 Log.v(TAG, "there is no authenticator for " + authenticatorType
4850 + ", bailing out");
4851 }
4852 return false;
4853 }
4854
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004855 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004856 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004857 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4858 + " which isn't encryption aware");
4859 return false;
4860 }
4861
Fred Quintanab839afc2009-10-14 15:57:28 -07004862 Intent intent = new Intent();
4863 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4864 intent.setComponent(authenticatorInfo.componentName);
4865 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4866 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4867 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004868 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004869 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004870 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4871 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4872 }
4873 return false;
4874 }
4875
Fred Quintanab839afc2009-10-14 15:57:28 -07004876 return true;
4877 }
Fred Quintana60307342009-03-24 22:48:12 -07004878 }
4879
Svet Ganov5d09c992016-09-07 09:57:41 -07004880 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07004881 MessageHandler(Looper looper) {
4882 super(looper);
4883 }
Costin Manolache3348f142009-09-29 18:58:36 -07004884
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004885 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004886 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004887 switch (msg.what) {
4888 case MESSAGE_TIMED_OUT:
4889 Session session = (Session)msg.obj;
4890 session.onTimedOut();
4891 break;
4892
Amith Yamasani5be347b2013-03-31 17:44:31 -07004893 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004894 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004895 break;
4896
Fred Quintana60307342009-03-24 22:48:12 -07004897 default:
4898 throw new IllegalStateException("unhandled message: " + msg.what);
4899 }
4900 }
4901 }
4902
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004903 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004904 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004905 }
4906
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004907 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004908 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004909 }
4910
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004911 /*
4912 * This function receives an opened writable database.
4913 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004914 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004915 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004916 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004917 }
4918
4919 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004920 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004921 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004922 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004923 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004924
4925 class LogRecordTask implements Runnable {
4926 private final String action;
4927 private final String tableName;
4928 private final long accountId;
4929 private final UserAccounts userAccount;
4930 private final int callingUid;
4931 private final long userDebugDbInsertionPoint;
4932
4933 LogRecordTask(final String action,
4934 final String tableName,
4935 final long accountId,
4936 final UserAccounts userAccount,
4937 final int callingUid,
4938 final long userDebugDbInsertionPoint) {
4939 this.action = action;
4940 this.tableName = tableName;
4941 this.accountId = accountId;
4942 this.userAccount = userAccount;
4943 this.callingUid = callingUid;
4944 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
4945 }
4946
4947 public void run() {
4948 SQLiteStatement logStatement = userAccount.statementForLogging;
4949 logStatement.bindLong(1, accountId);
4950 logStatement.bindString(2, action);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004951 logStatement.bindString(3, mDateFormat.format(new Date()));
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004952 logStatement.bindLong(4, callingUid);
4953 logStatement.bindString(5, tableName);
4954 logStatement.bindLong(6, userDebugDbInsertionPoint);
4955 logStatement.execute();
4956 logStatement.clearBindings();
4957 }
4958 }
4959
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004960 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
4961 callingUid, userAccount.debugDbInsertionPoint);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004962 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004963 % AccountsDb.MAX_DEBUG_DB_SIZE;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004964 mHandler.post(logTask);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004965 }
4966
4967 /*
4968 * This should only be called once to compile the sql statement for logging
4969 * and to find the insertion point.
4970 */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004971 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(UserAccounts userAccount) {
4972 userAccount.debugDbInsertionPoint = userAccount.accountsDb
4973 .calculateDebugTableInsertionPoint();
4974 userAccount.statementForLogging = userAccount.accountsDb.compileSqlStatementForLogging();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004975 }
4976
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004977 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004978 return asBinder();
4979 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004980
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004981 /**
4982 * Searches array of arguments for the specified string
4983 * @param args array of argument strings
4984 * @param value value to search for
4985 * @return true if the value is contained in the array
4986 */
4987 private static boolean scanArgs(String[] args, String value) {
4988 if (args != null) {
4989 for (String arg : args) {
4990 if (value.equals(arg)) {
4991 return true;
4992 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004993 }
4994 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004995 return false;
4996 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004997
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004998 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004999 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005000 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005001 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005002 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005003
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005004 final List<UserInfo> users = getUserManager().getUsers();
5005 for (UserInfo user : users) {
5006 ipw.println("User " + user + ":");
5007 ipw.increaseIndent();
5008 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5009 ipw.println();
5010 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005011 }
5012 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005013
Amith Yamasani04e0d262012-02-14 11:50:53 -08005014 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5015 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005016 if (isCheckinRequest) {
5017 // This is a checkin request. *Only* upload the account types and the count of
5018 // each.
5019 synchronized (userAccounts.dbLock) {
5020 userAccounts.accountsDb.dumpDeAccountsTable(fout);
5021 }
5022 } else {
5023 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
5024 Process.SYSTEM_UID, null /* packageName */, false);
5025 fout.println("Accounts: " + accounts.length);
5026 for (Account account : accounts) {
5027 fout.println(" " + account);
5028 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005029
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005030 // Add debug information.
5031 fout.println();
5032 synchronized (userAccounts.dbLock) {
5033 userAccounts.accountsDb.dumpDebugTable(fout);
5034 }
5035 fout.println();
5036 synchronized (mSessions) {
5037 final long now = SystemClock.elapsedRealtime();
5038 fout.println("Active Sessions: " + mSessions.size());
5039 for (Session session : mSessions.values()) {
5040 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005041 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005042 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005043
5044 fout.println();
5045 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005046 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005047 }
5048
Amith Yamasani04e0d262012-02-14 11:50:53 -08005049 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005050 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005051 long identityToken = clearCallingIdentity();
5052 try {
5053 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5054 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5055 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005056
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005057 if (intent.getComponent() != null &&
5058 GrantCredentialsPermissionActivity.class.getName().equals(
5059 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005060 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005061 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005062 Context contextForUser = getContextForUser(new UserHandle(userId));
Chris Wren717a8812017-03-31 15:34:39 -04005063 final NotificationId id = getSigninRequiredNotificationId(accounts, account);
5064 intent.addCategory(id.mTag);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005065
Fred Quintana33f889a2009-09-14 17:31:26 -07005066 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005067 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05005068 Notification n =
5069 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005070 .setWhen(0)
5071 .setSmallIcon(android.R.drawable.stat_sys_warning)
5072 .setColor(contextForUser.getColor(
5073 com.android.internal.R.color.system_notification_accent_color))
5074 .setContentTitle(String.format(notificationTitleFormat, account.name))
5075 .setContentText(message)
5076 .setContentIntent(PendingIntent.getActivityAsUser(
5077 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005078 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005079 .build();
Chris Wren717a8812017-03-31 15:34:39 -04005080 installNotification(id, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005081 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005082 } finally {
5083 restoreCallingIdentity(identityToken);
5084 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005085 }
5086
Chris Wren717a8812017-03-31 15:34:39 -04005087 private void installNotification(NotificationId id, final Notification notification,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005088 String packageName, int userId) {
5089 final long token = clearCallingIdentity();
5090 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005091 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005092 try {
Chris Wren717a8812017-03-31 15:34:39 -04005093 notificationManager.enqueueNotificationWithTag(packageName, packageName,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04005094 id.mTag, id.mId, notification, userId);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005095 } catch (RemoteException e) {
5096 /* ignore - local call */
5097 }
5098 } finally {
5099 Binder.restoreCallingIdentity(token);
5100 }
Fred Quintana56285a62010-12-02 14:20:51 -08005101 }
5102
Chris Wren717a8812017-03-31 15:34:39 -04005103 private void cancelNotification(NotificationId id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005104 cancelNotification(id, mContext.getPackageName(), user);
5105 }
5106
Chris Wren717a8812017-03-31 15:34:39 -04005107 private void cancelNotification(NotificationId id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005108 long identityToken = clearCallingIdentity();
5109 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005110 INotificationManager service = mInjector.getNotificationManager();
Chris Wren717a8812017-03-31 15:34:39 -04005111 service.cancelNotificationWithTag(packageName, id.mTag, id.mId, user.getIdentifier());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005112 } catch (RemoteException e) {
5113 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005114 } finally {
5115 restoreCallingIdentity(identityToken);
5116 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005117 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005118
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005119 private boolean isPermittedForPackage(String packageName, int uid, int userId,
5120 String... permissions) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005121 final long identity = Binder.clearCallingIdentity();
5122 try {
5123 IPackageManager pm = ActivityThread.getPackageManager();
5124 for (String perm : permissions) {
5125 if (pm.checkPermission(perm, packageName, userId)
5126 == PackageManager.PERMISSION_GRANTED) {
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005127 // Checks runtime permission revocation.
5128 final int opCode = AppOpsManager.permissionToOpCode(perm);
5129 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5130 opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
5131 return true;
5132 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005133 }
5134 }
5135 } catch (RemoteException e) {
5136 /* ignore - local call */
5137 } finally {
5138 Binder.restoreCallingIdentity(identity);
5139 }
5140 return false;
5141 }
5142
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005143 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5144 for (String perm : permissions) {
5145 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5146 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5147 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5148 }
5149 final int opCode = AppOpsManager.permissionToOpCode(perm);
5150 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5151 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5152 return true;
5153 }
5154 }
5155 }
5156 return false;
5157 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005158
Amith Yamasani67df64b2012-12-14 12:09:36 -08005159 private int handleIncomingUser(int userId) {
5160 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005161 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005162 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5163 } catch (RemoteException re) {
5164 // Shouldn't happen, local.
5165 }
5166 return userId;
5167 }
5168
Christopher Tateccbf84f2013-05-08 15:25:41 -07005169 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005170 String[] packages;
5171 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005172 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005173 packages = mPackageManager.getPackagesForUid(callingUid);
5174 } finally {
5175 Binder.restoreCallingIdentity(identityToken);
5176 }
5177 if (packages == null) {
5178 Log.d(TAG, "No packages for callingUid " + callingUid);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005179 return false;
5180 }
Fred Quintana7be59642009-08-24 18:29:25 -07005181 for (String name : packages) {
5182 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005183 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005184 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005185 && (packageInfo.applicationInfo.privateFlags
5186 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005187 return true;
5188 }
5189 } catch (PackageManager.NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005190 Log.d(TAG, "Package not found " + e.getMessage());
Fred Quintana7be59642009-08-24 18:29:25 -07005191 return false;
5192 }
5193 }
5194 return false;
5195 }
5196
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005197 private boolean permissionIsGranted(
5198 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005199 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5200 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5201 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5202 }
5203 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005204 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005205
5206 if (isPrivileged(callerUid)) {
5207 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5208 Log.v(TAG, "Access to " + account + " granted calling uid "
5209 + callerUid + " privileged");
5210 }
5211 return true;
5212 }
5213 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5214 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5215 Log.v(TAG, "Access to " + account + " granted calling uid "
5216 + callerUid + " manages the account");
5217 }
5218 return true;
5219 }
5220 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5221 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5222 Log.v(TAG, "Access to " + account + " granted calling uid "
5223 + callerUid + " user granted access");
5224 }
5225 return true;
5226 }
5227
5228 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5229 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5230 }
5231
5232 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005233 }
5234
Svetoslavf3f02ac2015-09-08 14:36:35 -07005235 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5236 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005237 if (accountType == null) {
5238 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005239 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005240 return getTypesVisibleToCaller(callingUid, userId,
5241 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005242 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005243 }
5244
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005245 // Method checks visibility for applications targeing API level below {@link
5246 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005247 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005248 private boolean checkGetAccountsPermission(String packageName, int uid, int userId) {
5249 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.GET_ACCOUNTS,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005250 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5251 }
5252
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005253 private boolean checkReadContactsPermission(String packageName, int uid, int userId) {
5254 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.READ_CONTACTS);
5255 }
5256
5257 // Heuristic to check that account type may be associated with some contacts data and
5258 // therefore READ_CONTACTS permission grants the access to account by default.
5259 private boolean accountTypeManagesContacts(String accountType, int userId) {
5260 if (accountType == null) {
5261 return false;
5262 }
5263 long identityToken = Binder.clearCallingIdentity();
5264 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5265 try {
5266 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5267 } finally {
5268 Binder.restoreCallingIdentity(identityToken);
5269 }
5270 // Check contacts related permissions for authenticator.
5271 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5272 : serviceInfos) {
5273 if (accountType.equals(serviceInfo.type.type)) {
5274 return isPermittedForPackage(serviceInfo.type.packageName, serviceInfo.uid, userId,
5275 Manifest.permission.WRITE_CONTACTS);
5276 }
5277 }
5278 return false;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005279 }
5280
5281 /**
5282 * Method checks package uid and signature with Authenticator which manages accountType.
5283 *
5284 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5285 * SIGNATURE_CHECK_MISMATCH otherwise.
5286 */
5287 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5288 if (accountType == null) {
5289 return SIGNATURE_CHECK_MISMATCH;
5290 }
5291
5292 long identityToken = Binder.clearCallingIdentity();
5293 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5294 try {
5295 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5296 } finally {
5297 Binder.restoreCallingIdentity(identityToken);
5298 }
5299 // Check for signature match with Authenticator.
5300 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5301 : serviceInfos) {
5302 if (accountType.equals(serviceInfo.type.type)) {
5303 if (serviceInfo.uid == callingUid) {
5304 return SIGNATURE_CHECK_UID_MATCH;
5305 }
5306 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5307 if (sigChk == PackageManager.SIGNATURE_MATCH) {
5308 return SIGNATURE_CHECK_MATCH;
5309 }
5310 }
5311 }
5312 return SIGNATURE_CHECK_MISMATCH;
5313 }
5314
5315 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005316 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5317 if (accountType == null) {
5318 return false;
5319 } else {
5320 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5321 }
5322 }
5323
Svetoslavf3f02ac2015-09-08 14:36:35 -07005324 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5325 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005326 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005327 }
5328
5329 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005330 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005331 }
5332
5333 private List<String> getTypesForCaller(
5334 int callingUid, int userId, boolean isOtherwisePermitted) {
5335 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005336 long identityToken = Binder.clearCallingIdentity();
5337 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5338 try {
5339 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5340 } finally {
5341 Binder.restoreCallingIdentity(identityToken);
5342 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005343 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005344 serviceInfos) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005345 if (isOtherwisePermitted || (mPackageManager.checkSignatures(serviceInfo.uid,
5346 callingUid) == PackageManager.SIGNATURE_MATCH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005347 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005348 }
5349 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005350 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005351 }
5352
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005353 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5354 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5355 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5356 if (account.name.equals(accountName)) {
5357 return true;
5358 }
5359 }
5360 }
5361 return false;
5362 }
5363
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005364 private static void checkManageUsersPermission(String message) {
5365 if (ActivityManager.checkComponentPermission(
5366 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5367 != PackageManager.PERMISSION_GRANTED) {
5368 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5369 }
5370 }
5371
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005372 private static void checkManageOrCreateUsersPermission(String message) {
5373 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5374 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5375 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5376 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5377 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5378 + message);
5379 }
5380 }
5381
Amith Yamasani04e0d262012-02-14 11:50:53 -08005382 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5383 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005384 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005385 return true;
5386 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005387 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005388 synchronized (accounts.dbLock) {
5389 synchronized (accounts.cacheLock) {
5390 long grantsCount;
5391 if (authTokenType != null) {
5392 grantsCount = accounts.accountsDb
5393 .findMatchingGrantsCount(callerUid, authTokenType, account);
5394 } else {
5395 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5396 account);
5397 }
5398 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005399
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005400 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5401 // TODO: Skip this check when running automated tests. Replace this
5402 // with a more general solution.
5403 Log.d(TAG, "no credentials permission for usage of " + account + ", "
5404 + authTokenType + " by uid " + callerUid
5405 + " but ignoring since device is in test harness.");
5406 return true;
5407 }
5408 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005409 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005410 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005411 }
5412
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005413 private boolean isSystemUid(int callingUid) {
5414 String[] packages = null;
5415 long ident = Binder.clearCallingIdentity();
5416 try {
5417 packages = mPackageManager.getPackagesForUid(callingUid);
5418 } finally {
5419 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005420 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005421 if (packages != null) {
5422 for (String name : packages) {
5423 try {
5424 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5425 if (packageInfo != null
5426 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5427 != 0) {
5428 return true;
5429 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005430 } catch (NameNotFoundException e) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005431 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5432 }
5433 }
5434 } else {
5435 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005436 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005437 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005438 }
5439
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005440 /** Succeeds if any of the specified permissions are granted. */
5441 private void checkReadAccountsPermitted(
5442 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005443 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005444 int userId,
5445 String opPackageName) {
5446 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005447 String msg = String.format(
5448 "caller uid %s cannot access %s accounts",
5449 callingUid,
5450 accountType);
5451 Log.w(TAG, " " + msg);
5452 throw new SecurityException(msg);
5453 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005454 }
5455
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005456 private boolean canUserModifyAccounts(int userId, int callingUid) {
5457 // the managing app can always modify accounts
5458 if (isProfileOwner(callingUid)) {
5459 return true;
5460 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005461 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5462 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5463 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005464 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005465 return true;
5466 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005467
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005468 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5469 // the managing app can always modify accounts
5470 if (isProfileOwner(callingUid)) {
5471 return true;
5472 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005473 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5474 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005475 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005476 if (typesArray == null) {
5477 return true;
5478 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005479 for (String forbiddenType : typesArray) {
5480 if (forbiddenType.equals(accountType)) {
5481 return false;
5482 }
5483 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005484 return true;
5485 }
5486
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005487 private boolean isProfileOwner(int uid) {
5488 final DevicePolicyManagerInternal dpmi =
5489 LocalServices.getService(DevicePolicyManagerInternal.class);
5490 return (dpmi != null)
5491 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5492 }
5493
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005494 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005495 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5496 throws RemoteException {
5497 final int callingUid = getCallingUid();
5498
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005499 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005500 throw new SecurityException();
5501 }
5502
5503 if (value) {
5504 grantAppPermission(account, authTokenType, uid);
5505 } else {
5506 revokeAppPermission(account, authTokenType, uid);
5507 }
5508 }
5509
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005510 /**
5511 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5512 * <p>
5513 * Although this is public it can only be accessed via the AccountManagerService object
5514 * which is in the system. This means we don't need to protect it with permissions.
5515 * @hide
5516 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005517 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005518 if (account == null || authTokenType == null) {
5519 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005520 return;
5521 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005522 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005523 synchronized (accounts.dbLock) {
5524 synchronized (accounts.cacheLock) {
5525 long accountId = accounts.accountsDb.findDeAccountId(account);
5526 if (accountId >= 0) {
5527 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5528 }
5529 cancelNotification(
5530 getCredentialPermissionNotificationId(account, authTokenType, uid),
5531 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005532
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005533 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5534 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005535 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005536
5537 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5538 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5539 : mAppPermissionChangeListeners) {
5540 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5541 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005542 }
5543
5544 /**
5545 * Don't allow callers with the given uid permission to get credentials for
5546 * account/authTokenType.
5547 * <p>
5548 * Although this is public it can only be accessed via the AccountManagerService object
5549 * which is in the system. This means we don't need to protect it with permissions.
5550 * @hide
5551 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005552 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005553 if (account == null || authTokenType == null) {
5554 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005555 return;
5556 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005557 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005558 synchronized (accounts.dbLock) {
5559 synchronized (accounts.cacheLock) {
5560 accounts.accountsDb.beginTransaction();
5561 try {
5562 long accountId = accounts.accountsDb.findDeAccountId(account);
5563 if (accountId >= 0) {
5564 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5565 accountId, authTokenType, uid);
5566 accounts.accountsDb.setTransactionSuccessful();
5567 }
5568 } finally {
5569 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005570 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005571
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005572 cancelNotification(
5573 getCredentialPermissionNotificationId(account, authTokenType, uid),
5574 UserHandle.of(accounts.userId));
5575 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005576 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005577
5578 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5579 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5580 : mAppPermissionChangeListeners) {
5581 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5582 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005583 }
Fred Quintana56285a62010-12-02 14:20:51 -08005584
Amith Yamasani04e0d262012-02-14 11:50:53 -08005585 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5586 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005587 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005588 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005589 for (Account curAccount : oldAccountsForType) {
5590 if (!curAccount.equals(account)) {
5591 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005592 }
5593 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005594 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005595 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005596 } else {
5597 Account[] newAccountsForType = new Account[newAccountsList.size()];
5598 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005599 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005600 }
Fred Quintana56285a62010-12-02 14:20:51 -08005601 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005602 accounts.userDataCache.remove(account);
5603 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005604 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005605 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005606 }
5607
5608 /**
5609 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005610 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5611 * processes and if you will return this account to apps you should return the result.
5612 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005613 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005614 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005615 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005616 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5617 Account[] newAccountsForType = new Account[oldLength + 1];
5618 if (accountsForType != null) {
5619 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005620 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005621 String token = account.getAccessId() != null ? account.getAccessId()
5622 : UUID.randomUUID().toString();
5623 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005624 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005625 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005626 }
5627
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005628 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005629 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005630 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005631 String visibilityFilterPackage = callingPackage;
5632 if (visibilityFilterPackage == null) {
5633 visibilityFilterPackage = getPackageNameForUid(callingUid);
5634 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005635 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005636 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005637 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005638 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5639 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5640 || (includeManagedNotVisible
5641 && (visibility
5642 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5643 firstPass.put(account, visibility);
5644 }
5645 }
5646 Map<Account, Integer> secondPass =
5647 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5648
5649 Account[] filtered = new Account[secondPass.size()];
5650 filtered = secondPass.keySet().toArray(filtered);
5651 return filtered;
5652 }
5653
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005654 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005655 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005656 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005657 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005658 // first part is to filter shared accounts.
5659 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005660 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005661 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005662 return unfiltered;
5663 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005664 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005665 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005666 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005667 if (packages == null) {
5668 packages = new String[] {};
5669 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005670 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005671 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005672 // This might be a temporary way to specify a visible list
5673 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005674 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5675 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005676 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005677 return unfiltered;
5678 }
5679 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005680 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005681 if (ArrayUtils.isEmpty(sharedAccounts)) {
5682 return unfiltered;
5683 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005684 String requiredAccountType = "";
5685 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005686 // If there's an explicit callingPackage specified, check if that package
5687 // opted in to see restricted accounts.
5688 if (callingPackage != null) {
5689 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005690 if (pi != null && pi.restrictedAccountType != null) {
5691 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005692 }
5693 } else {
5694 // Otherwise check if the callingUid has a package that has opted in
5695 for (String packageName : packages) {
5696 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5697 if (pi != null && pi.restrictedAccountType != null) {
5698 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005699 break;
5700 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005701 }
5702 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005703 } catch (NameNotFoundException e) {
5704 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005705 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005706 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005707 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5708 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005709 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005710 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005711 } else {
5712 boolean found = false;
5713 for (Account shared : sharedAccounts) {
5714 if (shared.equals(account)) {
5715 found = true;
5716 break;
5717 }
5718 }
5719 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005720 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005721 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005722 }
5723 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005724 return filtered;
5725 } else {
5726 return unfiltered;
5727 }
5728 }
5729
Amith Yamasani27db4682013-03-30 17:07:47 -07005730 /*
5731 * packageName can be null. If not null, it should be used to filter out restricted accounts
5732 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005733 *
5734 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5735 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005736 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005737 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005738 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005739 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005740 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5741 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005742 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005743 Account[] accounts;
5744 synchronized (userAccounts.cacheLock) {
5745 accounts = userAccounts.accountCache.get(accountType);
5746 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005747 if (accounts == null) {
5748 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005749 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005750 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5751 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005752 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005753 } else {
5754 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005755 Account[] accountsArray;
5756 synchronized (userAccounts.cacheLock) {
5757 for (Account[] accounts : userAccounts.accountCache.values()) {
5758 totalLength += accounts.length;
5759 }
5760 if (totalLength == 0) {
5761 return EMPTY_ACCOUNT_ARRAY;
5762 }
5763 accountsArray = new Account[totalLength];
5764 totalLength = 0;
5765 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5766 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
5767 accountsOfType.length);
5768 totalLength += accountsOfType.length;
5769 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005770 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005771 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005772 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005773 }
5774 }
5775
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005776 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005777 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005778 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005779 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005780 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005781 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005782 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005783 }
5784 if (value == null) {
5785 userDataForAccount.remove(key);
5786 } else {
5787 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005788 }
5789 }
5790
Carlos Valdivia91979be2015-05-22 14:11:35 -07005791 protected String readCachedTokenInternal(
5792 UserAccounts accounts,
5793 Account account,
5794 String tokenType,
5795 String callingPackage,
5796 byte[] pkgSigDigest) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005797 synchronized (accounts.dbLock) {
5798 synchronized (accounts.cacheLock) {
5799 return accounts.accountTokenCaches.get(
5800 account, tokenType, callingPackage, pkgSigDigest);
5801 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07005802 }
5803 }
5804
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005805 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005806 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005807 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005808 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005809 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005810 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005811 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005812 }
5813 if (value == null) {
5814 authTokensForAccount.remove(key);
5815 } else {
5816 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005817 }
5818 }
5819
Amith Yamasani04e0d262012-02-14 11:50:53 -08005820 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5821 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005822 // Fast path - check if account is already cached
5823 synchronized (accounts.cacheLock) {
5824 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5825 if (authTokensForAccount != null) {
5826 return authTokensForAccount.get(authTokenType);
5827 }
5828 }
5829 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005830 synchronized (accounts.dbLock) {
5831 synchronized (accounts.cacheLock) {
5832 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5833 if (authTokensForAccount == null) {
5834 // need to populate the cache for this account
5835 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
5836 accounts.authTokenCache.put(account, authTokensForAccount);
5837 }
5838 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08005839 }
Fred Quintana56285a62010-12-02 14:20:51 -08005840 }
5841 }
5842
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005843 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
5844 Map<String, String> userDataForAccount;
5845 // Fast path - check if data is already cached
5846 synchronized (accounts.cacheLock) {
5847 userDataForAccount = accounts.userDataCache.get(account);
5848 }
5849 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00005850 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005851 synchronized (accounts.dbLock) {
5852 synchronized (accounts.cacheLock) {
5853 userDataForAccount = accounts.userDataCache.get(account);
5854 if (userDataForAccount == null) {
5855 // need to populate the cache for this account
5856 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
5857 accounts.userDataCache.put(account, userDataForAccount);
5858 }
5859 }
5860 }
Fred Quintana56285a62010-12-02 14:20:51 -08005861 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005862 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005863 }
5864
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005865 private Context getContextForUser(UserHandle user) {
5866 try {
5867 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5868 } catch (NameNotFoundException e) {
5869 // Default to mContext, not finding the package system is running as is unlikely.
5870 return mContext;
5871 }
5872 }
Sandra Kwan78812282015-11-04 11:19:47 -08005873
5874 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5875 try {
5876 response.onResult(result);
5877 } catch (RemoteException e) {
5878 // if the caller is dead then there is no one to care about remote
5879 // exceptions
5880 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5881 Log.v(TAG, "failure while notifying response", e);
5882 }
5883 }
5884 }
5885
5886 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5887 String errorMessage) {
5888 try {
5889 response.onError(errorCode, errorMessage);
5890 } catch (RemoteException e) {
5891 // if the caller is dead then there is no one to care about remote
5892 // exceptions
5893 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5894 Log.v(TAG, "failure while notifying response", e);
5895 }
5896 }
5897 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005898
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005899 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07005900 private final Object mLock = new Object();
5901
5902 @GuardedBy("mLock")
5903 private AccountManagerBackupHelper mBackupHelper;
5904
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005905 @Override
5906 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
5907 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
5908 if (account == null) {
5909 Slog.w(TAG, "account cannot be null");
5910 return;
5911 }
5912 if (packageName == null) {
5913 Slog.w(TAG, "packageName cannot be null");
5914 return;
5915 }
5916 if (userId < UserHandle.USER_SYSTEM) {
5917 Slog.w(TAG, "user id must be concrete");
5918 return;
5919 }
5920 if (callback == null) {
5921 Slog.w(TAG, "callback cannot be null");
5922 return;
5923 }
5924
Svet Ganovf6d424f12016-09-20 20:18:53 -07005925 if (AccountManagerService.this.hasAccountAccess(account, packageName,
5926 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005927 Bundle result = new Bundle();
5928 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
5929 callback.sendResult(result);
5930 return;
5931 }
5932
5933 final int uid;
5934 try {
5935 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
5936 } catch (NameNotFoundException e) {
5937 Slog.e(TAG, "Unknown package " + packageName);
5938 return;
5939 }
5940
5941 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07005942 final UserAccounts userAccounts;
5943 synchronized (mUsers) {
5944 userAccounts = mUsers.get(userId);
5945 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04005946 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07005947 doNotification(userAccounts, account, null, intent, packageName, userId);
5948 }
5949
5950 @Override
5951 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
5952 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5953 mAppPermissionChangeListeners.add(listener);
5954 }
5955
5956 @Override
5957 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
5958 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005959 }
Svet Ganov5d09c992016-09-07 09:57:41 -07005960
5961 @Override
5962 public byte[] backupAccountAccessPermissions(int userId) {
5963 synchronized (mLock) {
5964 if (mBackupHelper == null) {
5965 mBackupHelper = new AccountManagerBackupHelper(
5966 AccountManagerService.this, this);
5967 }
5968 return mBackupHelper.backupAccountAccessPermissions(userId);
5969 }
5970 }
5971
5972 @Override
5973 public void restoreAccountAccessPermissions(byte[] data, int userId) {
5974 synchronized (mLock) {
5975 if (mBackupHelper == null) {
5976 mBackupHelper = new AccountManagerBackupHelper(
5977 AccountManagerService.this, this);
5978 }
5979 mBackupHelper.restoreAccountAccessPermissions(data, userId);
5980 }
5981 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005982 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07005983
5984 @VisibleForTesting
5985 static class Injector {
5986 private final Context mContext;
5987
5988 public Injector(Context context) {
5989 mContext = context;
5990 }
5991
5992 Looper getMessageHandlerLooper() {
5993 ServiceThread serviceThread = new ServiceThread(TAG,
5994 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
5995 serviceThread.start();
5996 return serviceThread.getLooper();
5997 }
5998
5999 Context getContext() {
6000 return mContext;
6001 }
6002
6003 void addLocalService(AccountManagerInternal service) {
6004 LocalServices.addService(AccountManagerInternal.class, service);
6005 }
6006
6007 String getDeDatabaseName(int userId) {
6008 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
6009 AccountsDb.DE_DATABASE_NAME);
6010 return databaseFile.getPath();
6011 }
6012
6013 String getCeDatabaseName(int userId) {
6014 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
6015 AccountsDb.CE_DATABASE_NAME);
6016 return databaseFile.getPath();
6017 }
6018
6019 String getPreNDatabaseName(int userId) {
6020 File systemDir = Environment.getDataSystemDirectory();
6021 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
6022 PRE_N_DATABASE_NAME);
6023 if (userId == 0) {
6024 // Migrate old file, if it exists, to the new location.
6025 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006026 // accidentally created in the old location,
6027 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07006028 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
6029 if (oldFile.exists() && !databaseFile.exists()) {
6030 // Check for use directory; create if it doesn't exist, else renameTo will fail
6031 File userDir = Environment.getUserSystemDirectory(userId);
6032 if (!userDir.exists()) {
6033 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006034 throw new IllegalStateException(
6035 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006036 }
6037 }
6038 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006039 throw new IllegalStateException(
6040 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006041 }
6042 }
6043 }
6044 return databaseFile.getPath();
6045 }
6046
6047 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
6048 return new AccountAuthenticatorCache(mContext);
6049 }
6050
6051 INotificationManager getNotificationManager() {
6052 return NotificationManager.getService();
6053 }
6054 }
Chris Wren717a8812017-03-31 15:34:39 -04006055
6056 private class NotificationId {
6057 final String mTag;
6058 private final int mId;
6059
6060 NotificationId(String tag, int type) {
6061 mTag = tag;
6062 mId = type;
6063 }
6064 }
Fred Quintana60307342009-03-24 22:48:12 -07006065}